Next.js项目出现location is not defined错误,未直接使用location/window
解决Next.js中
ReferenceError: location is not defined错误 报错信息
⨯ node_modules/next/dist/client/performance-relayer.js (20:20) @ location ⨯ ReferenceError: location is not defined at __webpack_require__ (/media/<PATH>/.next/server/webpack-runtime.js:33:43) at __webpack_require__ (/media/<PATH>/.next/server/webpack-runtime.js:33:43) at __webpack_require__ (/media/<PATH>/.next/server/webpack-runtime.js:33:43) at eval (dashboard/layout.tsx:14:69) at (ssr)/./app/(withlayout)/dashboard/layout.tsx (/media/<PATH>/.next/server/app/(withlayout)/dashboard/page.js:226:1) at __webpack_require__ (/media/<PATH>/.next/server/webpack-runtime.js:33:43) null
涉及组件代码
"use client"; import { FaHome } from 'react-icons/fa' import { BsFolder, BsGrid1X2 } from 'react-icons/bs' import {cn} from "@/lib/cn"; import Link from "next/link"; import { usePathname } from 'next/navigation'; import {router} from "next/client"; const layout = ({ children }) => { const pathname = usePathname(); } return ( <div className='bg-[#18191b] min-h-screen w-full'> <div className='w-full flex mt-16'> <div className='sidebar w-[300px] p-5 h-[calc(100vh-70px)] fixed'> <div className='px-2 py-2 flex justify-start gap-5 items-center mb-3'> <img className='w-[40px] h-[40px] rounded-full' src="https://svgshare.com/i/7aS.svg" alt="image" /> <div className='flex justify-center flex-col items-start'> <span className='text-[#e0dddd] font-bold text-md'>User's Name</span> <span className='text-[#c4c0c0] text-sm'>Free</span> </div> </div> <ul className='px-4 flex flex-col gap-2'> <li> <Link href='/' className={`text-[#e0dddd] px-2 py-2 flex justify-start items-center gap-2 ${pathname === '/' ? 'bg-[#ffffff26]' : ''} rounded-[4px]`} > <span className='text-xl'><FaHome /></span> <span className='font-medium'>Home</span> </Link> </li> <li> <Link href='/projects' className={`text-[#e0dddd] px-2 py-2 flex justify-start items-center gap-2 ${pathname === '/projects' ? 'bg-[#ffffff26]' : ''} rounded-[4px]`} > <span className='text-xl'><BsFolder /></span> <span className='font-medium'>Projects</span> </Link> </li> <li> <Link href='/templates' className={`text-[#e0dddd] px-2 py-2 flex justify-start items-center gap-2 ${pathname === '/templates' ? 'bg-[#ffffff26]' : ''} rounded-[4px]`} > <span className='text-xl'><BsGrid1X2 /></span> <span className='font-medium'>Templates</span> </Link> </li> </ul> </div> <div className='ml-[300px] w-[calc(100%-300px)]'> <div className='py-4 pr-4'> <main className={cn("grid place-items-center")}>{children}</main> </div> </div> </div> </div> ) } export default layout
解决方案
- 移除未使用的
router导入:代码中导入了import {router} from "next/client";但未实际使用,该导入会触发Next.js内部依赖location对象的逻辑,而服务端渲染时location不存在,直接删除这行代码即可。 - 确认客户端组件标识:确保
"use client";是文件第一行有效代码,保证组件在客户端环境执行,避免服务端访问浏览器专属API。 - 清理缓存并重启服务:执行以下命令清理Next.js缓存后重启开发服务器,避免旧代码残留:
rm -rf .next npm run dev
内容的提问来源于stack exchange,提问作者MD Jahid Hasan
相关产品推荐
相关产品推荐

