N
Nuxt2mo ago
Taylan

getServerSession() returns null on server middleware

Hi,
import { getServerSession, getToken } from '#auth';

export default eventHandler(async (event) => {
const session = await getServerSession(event);
if (!session) {
throw createError({
statusMessage: 'Unauthenticated',
statusCode: 403
});
}
});
import { getServerSession, getToken } from '#auth';

export default eventHandler(async (event) => {
const session = await getServerSession(event);
if (!session) {
throw createError({
statusMessage: 'Unauthenticated',
statusCode: 403
});
}
});
inside of server/middleware/auth.ts returns null on same cases. There was a warning about it and recommended solution was to pass cookies to headers and i have already applied it during any request. But still, especially on page refresh, session returns null. Also, i realized that if there is a async fetch call inside of any .vue component's onMounted() method, this middleware is called. Ex: if there are 4 calls it is called 4 times even if i dont mount that page. Any recommendations to overcome this issue?
4 Replies
manniL
manniL2mo ago
Is this maybe related to how you fetch data? See https://www.youtube.com/watch?v=7vfwYaHtv3U
Alexander Lichter
YouTube
Passing Cookies with event.$fetch and useRequestFetch in Nuxt
Ever wondered why cookies are not passed correctly to subrequests - e.g. during SSR or when using Nitro/H3? Then this video is for you. Together we have a look how to pass all the important information, including event context and headers to further calls, eliminating different behavior on server and client. #nuxtjs #nuxt #vue #webdevelopment ...
Taylan
TaylanOP2mo ago
Hi, thx but refreshed page has no api calls. only, middleware returns session as null on refresh when using getToken() and getServerSession on nitro part as can be seen above. I think it is irrelevant or maybe next-auth library's way to fetch session causes this idk.
Cue
Cue2mo ago
Given that middleware is executed on every request, you’re throwing an exception in the event of an absent session. You almost always want to conditionally throw exceptions based on the context of a request. That is, you may want to restrict session checking on api routes only, therefore you’ll want to check if the middleware is executing on an api route or protected route, thus throwing exceptions in that context only.
Taylan
TaylanOP2mo ago
yeah, when i check the path, even for "/ipx//img/small_logo.png" or "/api/auth/session?callbackUrl=http:%2F%2Flocalhost:3000%2F", this server/middleware/auth.ts is called and some of them returns null. I guess i should specify endpoints to be checked precisely
Want results from more Discord servers?
Add your server