BA
Better Auth•2mo ago
Dmitry

Cached Session Cookie (JWT) is not refreshed (SvelteKit)

I noticed that when enabling the Session Cookie Cache, Better auth doesn't generate a new Session Cookie (JWT) after the expiration (max-age). I'm doing getSession() in a SvelteKit server hook. Is there something I need to do to initiate the session cookie (JWT) refresh?
4 Replies
Dmitry
DmitryOP•2mo ago
Bump! 🙂
bekacru
bekacru•2mo ago
It does generate a new cookie but make sure you're calling getSession on the client as well or you'd have to parse and set cookies from the serever hook. When you call getSession on the server, it won't be able to set cookies.
Dmitry
DmitryOP•2mo ago
Oh interesting. Might be able to set it from the server hook.. not sure if I want to do it client side tbh. Is the parsing pretty straight forward server side..or...? Look's like there is a setSessionCookie function I can use.. it requires a context though. How would I fetch the context?
mark
mark•2mo ago
This my middleware in express. It can refresh the cache cookie when it expired.
export const sessionMW = async (
req: Request,
res: Response,
next: Function
) => {
const ctx = {
headers: fromNodeHeaders(req.headers),
setCookie: (name: string, data: string, options: any) => {
console.log(`Setting cookie: ${name}`);
res.cookie(name, data, {
...options,
maxAge: config.sessionCache_maxAge * 1000, // 5 minutes
});
},
};
const session = await auth.api.getSession(ctx);

if (!session) {
return res.status(401).json({ error: "Unauthorized: Invalid session" });
}

req.session = session;
next();
};
export const sessionMW = async (
req: Request,
res: Response,
next: Function
) => {
const ctx = {
headers: fromNodeHeaders(req.headers),
setCookie: (name: string, data: string, options: any) => {
console.log(`Setting cookie: ${name}`);
res.cookie(name, data, {
...options,
maxAge: config.sessionCache_maxAge * 1000, // 5 minutes
});
},
};
const session = await auth.api.getSession(ctx);

if (!session) {
return res.status(401).json({ error: "Unauthorized: Invalid session" });
}

req.session = session;
next();
};
However, it works in v1.1.21 but not in v1.2.4 I'm still trying to figure out how to do it

Did you find this page helpful?