Unable to access cookie in api
Unanswered
Weevil parasitoid posted this in #help-forum
Weevil parasitoidOP
Hey guys I am using lucia for authentication and I want to add protected routes. So I made an api route to verify the cookie. But the problem is that I can't access the cookie in my api route.
The result is {user:null,session:null} and the cookie is undefined.
I don't understand why this is happening. What should i do?
'use server';
import { verifyAuth } from "@/lib/db";
import { cookies } from "next/headers";
export async function GET(request) {
const result = await verifyAuth();
const cookie = cookies().get('auth_session');
console.log(cookie);
console.log(result);
return new Response(JSON.stringify({ user: result.user }), {
headers: { 'Content-Type': 'application/json' },
});
}The result is {user:null,session:null} and the cookie is undefined.
export async function verifyAuth() {
const sessionCookie = cookies().get(lucia.sessionCookieName);
if (!sessionCookie) {
return {
user: null,
session: null
};
}
const sessionId = sessionCookie.value;
if (!sessionId) {
return {
user: null,
session: null
};
}
const result = await lucia.validateSession(sessionId);
try {
if (result.session && result.session.fresh) {
const sessionCookie = lucia.createSessionCookie(result.session.id); //refresh session
cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
}
else {
const sessionCookie = lucia.createBlankSessionCookie(); // clear expired cookie
cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
}
}
catch (e) {
console.log(e);
}
return result;
} I don't understand why this is happening. What should i do?
2 Replies
Oak shoot sawfly
Can you share how the cookie is being stored either via code or browser.
Check if the domain and path matches. Also check for expiry
Check if the domain and path matches. Also check for expiry
Black carp
Have you verified that your Lucia cookie is being created and stored in your browser cookies?