我的应用程序在开发模式下运行良好,但是当我尝试构建时出现此错误。
▲ Next.js 14.1.3
- Environments: .env
Creating an optimized production build ...
✓ Compiled successfully
✓ Linting and checking validity of types
✓ Collecting page data
Generating static pages (0/13) [ ]TypeError: Cannot read properties of undefined (reading 'data')
at u (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\.next\server\chunks\923.js:1:10734)
at i (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\.next\server\chunks\309.js:1:7174)
at em (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:131226)
at C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:142926
at Array.toJSON (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:146504)
at stringify (<anonymous>)
at eR (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:134889)
at eP (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:135332)
at AsyncLocalStorage.run (node:async_hooks:346:14)
at Timeout._onTimeout (C:\Users\kuzey\Desktop\Desktop\ForMe\WEBFOLDERS\Projects\x\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:12:146956)
Error occurred prerendering page "/register". Read more: https://nextjs.org/docs/messages/prerender-error
编辑:我发现了问题所在,但仍然无法修复。
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
const AuthLayout = async ({ children }: { children: React.ReactNode }) => {
// const session = await auth();
// if (session) {
// redirect('/home');
// }
return (
// ...
);
};
export default AuthLayout;
如果我评论这些行,一切都会完美。
我认为,因为这个
auth()
函数需要浏览器特定功能(如 cookies 或 loacalStorage),所以它在构建期间不会按预期工作,因为代码是在 Node.js 环境中执行的。实际上不在浏览器中。因此我们只需要对客户端进行条件检查。尝试以下操作:
if (typeof window !== "undefined") {
// Execute client-specific code here
const session = await auth();
if (session) {
redirect('/home');
}
}