如何在 Next.js 13 中间件中从 localStorage 检索数据?

问题描述 投票:0回答:1

我是 Next.js 的新手,我对使用 Next.js 中间件实现基于角色的身份验证感兴趣。在我的场景中,用户成功登录后,我从数据库中检索他们的角色,并使用 Redux 将其存储在 localStorage 中。为了启用基于角色的路由,我需要从中间件访问用户的角色。但是,我在访问 localStorage 时遇到了困难。

我不知道如何从 nextJS 中间件访问 localStorage。如果您有任何建议或想法,请分享。

提前致谢

next.js middleware
1个回答
0
投票

这有效

import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest) {
  
  // Check if the request is coming from the browser
  if (typeof window !== 'undefined') {
    const data = localStorage.getItem('user_Data')
  }

}

请记住,访问服务器端的本地存储可能并不总是必要或可取的,因为它通常用于客户端存储。确保此方法符合您的特定要求和安全考虑因素

© www.soinside.com 2019 - 2024. All rights reserved.