Next.js 13 构建:未定义位置

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

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 :

&#39;use client&#39;

const router = useRouter();
const [auth, setAuth] = useState&lt;string | null&gt;(null);

const checkAuth = () =&gt; {
	return localStorage.getItem(&#39;auth&#39;);
}

useEffect(() =&gt; {
		setAuth(checkAuth());
	}, []);

if (!auth) {
		router.push(&#39;/admin/login&#39;);
		return;
	}

return &lt;div&gt;...&lt;/div&gt;

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 &quot;use client&quot; as the first line in the file containing this component.

huangapple
  • 本文由 发表于 2023年7月27日 17:59:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778589.html
匿名

发表评论

匿名网友

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

确定