https://supertokens.com/ logo
Title
o

Ollie.

12/20/2022, 4:43 AM
Is there anyway to check if a user is logged in using NextJS's Middleware?
n

nkshah2

12/20/2022, 4:43 AM
Hi @Ollie.
Is this for the frontend routes or the api routes?
o

Ollie.

12/20/2022, 4:43 AM
Hey!
Frontend routes
n

nkshah2

12/20/2022, 4:44 AM
You just need to check if the current user is logged in correct? Or do you want some other information as well
o

Ollie.

12/20/2022, 4:44 AM
At the moment, check that the user is logged.
n

nkshah2

12/20/2022, 4:45 AM
What auth recipe are you using?
o

Ollie.

12/20/2022, 4:45 AM
Social and email + password
n

nkshah2

12/20/2022, 4:45 AM
Also are you using the pre built UI or your own?
o

Ollie.

12/20/2022, 4:46 AM
Prebuilt UI
sorry
no
custom UI
had a mind blank then
o

Ollie.

12/20/2022, 4:53 AM
Im not sure you fully understand what im trying to do, Im trying to protect routes with NextJS Middleware
n

nkshah2

12/20/2022, 4:58 AM
await SuperTokens.doesSessionExist()
This would return false if a session does not exist
Which would be true if the user isnt logged in
o

Ollie.

12/20/2022, 4:59 AM
And yeah, I guess something like this would work fine, but the Middleware runs before the request is completed which seems more secure and alot easier to implement for heaps of pages
n

nkshah2

12/20/2022, 5:01 AM
Right so the snippet on that page has more code than just checking for session, but I meant to just use
SuperTokens.doesSessionExist()
in your middleware
o

Ollie.

12/20/2022, 5:02 AM
What would be more secure? adding the code in my image to every page or checking for a session using middleware?
n

nkshah2

12/20/2022, 5:04 AM
In essence they would have the same effect so in terms of security it shouldnt matter. Adding it to the middleware would make it easier to apply across all your pages if thats what you need If its for selected pages then I would recommended the code in the image you sent