Next.js Discord

Discord Forum

Login with jwt token issue

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
this is my code to login and save the token but it is not saving the token, plus I have a middleware that checks the token it is redirecting me to login again
import api from "@/lib/api";
import { IApiResponse } from "@/type/IApiResponse";
import { ILoginResponse } from "@/type/ILoginResponse";
import { serialize } from "cookie";

type LoginModel = {
  email: string;
  password: string;
};

export const loginUser = async ({
  email,
  password,
}: LoginModel): Promise<IApiResponse<ILoginResponse>> => {
  try {
    const response = await api.post<IApiResponse<ILoginResponse>>(
      "/auth/login",
      {
        email,
        password,
      }
    );
    debugger;
    if (response.data.isSuccess && response.data.data) {
      const serialized = serialize("token", response.data.data.token, {
        httpOnly: true,
        sameSite: "strict",
        path: "/",
        maxAge: 2 * 60 * 60,
      });

      const res = {
        message: "Authenticated!",
      };

      new Response(JSON.stringify(res), {
        status: 200,
        headers: { "Set-Cookie": serialized },
      });
    }

    return response.data;
  } catch (error: any) {
    throw error.response?.data || { message: "Login failed" };
  }
};

1 Reply

Yellowstripe scad
I may be incorrect but I'm sure you can set a cookie from a header...

Use something like this:

import { setCookie } from 'cookies-next';

export default function handler(req, res) {
  setCookie('myCookie', 'cookieValue', { req, res, maxAge: 60 * 60 * 24 }); // 1 day
  res.status(200).json({ message: 'Cookie set!' });
}