Next.js服务端获取完整路径:替代window.location.pathname的方案
问题描述
我的应用路由格式为/m/{locale}/{page}。客户端使用window.location.pathname可正常返回/m/en/contacts,但在服务端的_document.tsx中无法访问window对象。尝试在getInitialProps(ctx: DocumentContext)中使用ctx.req?.url和ctx.asPath,仅返回/contacts,丢失了/m/{locale}前缀,请问有无简洁可行的解决方法?
解决方法
- 拼接完整请求URL提取完整路径:
在_document.tsx的getInitialProps方法中,通过请求头信息拼接出完整的请求URL,再用URL对象解析出带前缀的完整路径:import Document, { DocumentContext } from 'next/document'; class MyDocument extends Document { static async getInitialProps(ctx: DocumentContext) { const initialProps = await Document.getInitialProps(ctx); if (ctx.req) { // 构建完整请求URL const protocol = ctx.req.headers['x-forwarded-proto'] || 'http'; const host = ctx.req.headers.host || ''; const fullUrl = `${protocol}://${host}${ctx.req.url}`; // 解析出带前缀的完整路径 const fullPathname = new URL(fullUrl).pathname; // 此处fullPathname即为/m/en/contacts,可按需使用 } return initialProps; } } export default MyDocument; - 检查反向代理配置(若使用):
如果你的应用部署时用了Nginx等反向代理,要确保代理规则保留完整请求路径。比如Nginx配置中需保证proxy_pass传递完整路径,同时添加proxy_set_header X-Forwarded-Proto $scheme;这类头信息,避免服务端收到的URL被截断。 - 核对Next.js路由配置:
若使用了多语言(i18n)或自定义路由,检查next.config.js中的basePath、i18n配置,确保/m/{locale}前缀未被配置规则覆盖,保证服务端能正确解析完整路由。
内容的提问来源于stack exchange,提问作者Ignas Damunskis
相关产品推荐
相关产品推荐

