I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies.
Within a file named cookie.ts, which contains helper functions, there are two functions - one for setting the cookie after receiving it from the backend, and another for retrieving the cookie from the browser.
export const setAuthToken = (
expiresIn: number,
accessToken: string | null,
baseUrl: string
) => {
return fetch(`${baseUrl}/api/auth/login`, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ expiresIn, accessToken }),
});
};
export const getAccessTokenCookie = async (baseUrl: string) => {
const response = await fetch(`${baseUrl}/api/auth/login`, {
method: "get",
});
const data = await response.json();
console.log(data, "data");
return data.token;
};
The setAuthToken function sends a fetch request to /app/api/auth/login/route.ts.
import { cookies } from "next/headers";
export async function POST(request: Request) {
const body = await request.json();
const { expiresIn, accessToken } = body;
cookies().set({
name: "access_token",
value: accessToken,
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: "strict",
maxAge: expiresIn,
path: "/",
});
}
export async function GET() {
const accessToken = cookies().get("access_token");
console.log(accessToken, "accessToken");
if (!accessToken?.value) {
return new Response(JSON.stringify({ token: null }), {
headers: {
"Content-Type": "application/json",
},
});
}
return new Response(JSON.stringify({ token: accessToken.value }), {
headers: {
"Content-Type": "application/json",
},
});
}
Although the POST request in setAuthToken successfully creates and stores the cookie, when attempting to retrieve it through getAccessTokenCookie, the cookie cannot be found, even within the GET function of the route.ts file.