英文:
Nextjs 13 build : location is not defined
问题
我已经设置了一个通过localstorage进行身份验证检查的Next.js应用程序,代码如下:
'use client'
const router = useRouter();
const [auth, setAuth] = useState<string | null>(null);
const checkAuth = () => {
return localStorage.getItem('auth');
}
useEffect(() => {
setAuth(checkAuth());
}, []);
if (!auth) {
router.push('/admin/login');
return;
}
return <div>...</div>;
问题是,当我构建项目时,出现以下错误:
ReferenceError: location is not defined
at AdminPage (admin/page.tsx:260:16)
请注意,我还尝试在访问localstorage之前检查window对象是否未定义,但错误仍然相同。
是否有其他方法可以检查localstorage中的auth项,以防止未连接的用户访问此页面,并将其重定向到登录页面?
英文:
I have set up an authentication checking via localstorage on a nextjs app like so :
'use client'
const router = useRouter();
const [auth, setAuth] = useState<string | null>(null);
const checkAuth = () => {
return localStorage.getItem('auth');
}
useEffect(() => {
setAuth(checkAuth());
}, []);
if (!auth) {
router.push('/admin/login');
return;
}
return <div>...</div>
The issue is that when I build the project I get the following error :
ReferenceError: location is not defined
at AdminPage (admin/page.tsx:260:16)
Note that I have also tried checking if the window object is undefined before accessing localstorage but the error is still the same.
Is there another way to check the auth item from localstorage to prevent unconnected users from accessing this page and redirect them to the login page?
答案1
得分: 2
你需要在客户端组件中使用"use client"指令。
将"use client"
放在包含该组件的文件的第一行。
英文:
You need to use “use client” directive for client side components.
Put "use client"
as the first line in the file containing this component.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论