Reputation: 492
I am currently coding an authentication system in my next js app that is using app router. My app has a login and user dashboard route. When user logged in successfully(with the correct username and password).I save the user data in session storage. So when a user tries to go to the dashboard page, I want to check if user is logged in or not(data existence in session storage) . I think I can do it in the dashboard component file too but because there are more routes like dashboard which need to be protected , I think it is better to check it in middleware . So how can I access session storage in middleware to check user is logged in or not . Allow user to access route or not . I tried to access session storage to check user authentication status but I got an error which says sessionStorage is not defined . I think it is because middleware process is in server-side and session storage is in client side. So how can I do this ? Any idea ?
Upvotes: 1
Views: 5232
Reputation: 49671
the best way is to use the cookies using cookies-next. cookies are attached on every request automatically
If you insist on using sessionStorage
, nextjs13 app directory has RootLayout
file. you can either check here if the user authenticated or you can create a context provider for authentication and check the authentication inside useEffect
. if user is not authenticated, you can redirect the user to login
page.
Upvotes: 0