getSession returns/is null in hooks.server.ts (svelte5/sveltekit)

Here's relevant parts: hooks.server.ts: ...try { // Validate the token using getSession const sessionData = await auth.api.getSession({ headers: event.request.headers // Includes Cookie: session=token }); ... i've confirmed through console.log that the "event.request.headers" contains a token (I'm using "auth.api.signInEmail" in routes/login/page.server.ts") [previous code processed email and password input from a form - both email and password are present and valid] try { const loginResponse = await auth.api.signInEmail({ body: { email: email, password: password }, // asResponse: true, headers: request.headers }); console.log('login - headers', request.headers); console.log('login - session', JSON.stringify(loginResponse, null, 2)); if (!loginResponse.token) { throw new Error('No token returned'); } // Set session cookie cookies.set('version1_session', loginResponse.token, { path: '/', maxAge: 30 * 24 * 60 * 60 // httpOnly: true, // sameSite: 'lax' // secure: process.env.NODE_ENV === 'production' });
... The database is being updated with session id, create/update dates, token, etc. i've confirmed that the token. in the database is the same one found in the header in "hooks". I've tried the "auth.api.getSession" in "routes/+layout.server.ts" and "routes/login/+page.server.ts" with same null result. In looking at the better-auth code for the sessions.ts that exposes getSession, it appears (to my very novice eyes) that it should use that token to query the database and on finding the token, return a session object and a user object. Any help would be GREATLY appreciated.
2 Replies
rtmorgan
rtmorgan•7d ago
I don't believe you can set the cookie with the token value returned from the auth.api.signInEmail call. This is a valid token (meaning it matches the token value stored in the session table), but the cookie's token value needs to be set to a value of the token concatenated with a '.' and then the hmac-sha256 hash of the token using your auth secret so that it can be validated during subsequent usage. If instead you use the response object returned from auth.api.signInEmail, there will be a 'set-cookie' header that contains this full token value (token + hmac) which you can extract and set as a cookie within your action.
braveheartwilliam
braveheartwilliamOP•6d ago
Thank-you! Another reply said the same thing but I had commented out the "asResponse" so couldn't see the "set-cookie".Thanks for taking the time to reply. 😀

Did you find this page helpful?