如何在中间件中访问 Next.js 中的 sessionStorage

huangapple go评论56阅读模式
英文:

How to access sessionStorage in middleware Nextjs

问题

我目前正在编写一个在我的Next.js应用中使用应用程序路由器的身份验证系统。我的应用程序有一个登录和用户仪表板路由。当用户成功登录(使用正确的用户名和密码)时,我将用户数据保存在会话存储中。因此,当用户尝试访问仪表板页面时,我希望检查用户是否已登录(会话存储中存在数据)。我认为我也可以在仪表板组件文件中执行此操作,但因为还有其他需要受保护的路由,如仪表板,所以我认为最好在中间件中检查它。那么,我如何在中间件中访问会话存储以检查用户是否已登录或不允许用户访问路由?我尝试访问会话存储以检查用户身份验证状态,但出现了一个错误,该错误说sessionStorage未定义。我认为这是因为中间件进程位于服务器端,而会话存储位于客户端。那么我该如何做呢?有什么建议吗?

英文:

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 ?

答案1

得分: 0

最佳方法是使用cookies-next来使用Cookies。Cookies会自动附加在每个请求上。

如果坚持使用sessionStorage,在nextjs13应用程序目录中有一个RootLayout文件。你可以在这里检查用户是否已经验证,或者你可以创建一个身份验证的上下文提供程序,并在useEffect中检查身份验证。如果用户未经身份验证,可以将用户重定向到login页面。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月28日 05:09:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定