Next.js Discord

Discord Forum

Can i use getServerSession() inside middleware ?

Unanswered
Southeastern blueberry bee posted this in #help-forum
Open in Discord
Southeastern blueberry beeOP
instead of using this getServerSession() nextauth function for each protected page i want to use it once on middleware and do all my match filters inside it is it possible, i asked it because on all online docs i've see there is using getServerSession inside SC usesession inside CC but why dont do the session checking into middleware isn't recommended in next ?

2 Replies

well no, since getServerSession() uses headers() and cookies() under the hood. and there you can't use headers() and cookies() in the middleware
One way to do it is to use the withAuth middleware like so
https://next-auth.js.org/configuration/nextjs#middleware