在Next.js 13 App Router的SSR环境中如何获取当前页面完整URL?
在Next.js 13 App Router的SSR场景中获取完整URL
1. 服务器组件(Server Components)中获取
在服务器组件里,直接通过Next.js提供的headers()函数提取请求头信息,拼接出完整URL:
import { headers } from 'next/headers'; export default function ServerComponent() { const headersList = headers(); // 部署在反向代理(如Vercel、Nginx)时用x-forwarded-proto获取实际协议,本地开发默认http const protocol = headersList.get('x-forwarded-proto') || 'http'; const host = headersList.get('host'); // next-url头包含当前页面的路径和查询参数(如/about?name=test) const pathname = headersList.get('next-url') || ''; const fullUrl = `${protocol}://${host}${pathname}`; return <div>完整URL:{fullUrl}</div>; }
2. 客户端组件(Client Components)中获取
客户端组件在SSR阶段无法直接访问window,可以通过以下两种方式处理:
方法一:结合导航API与客户端生命周期
'use client'; import { usePathname, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; export default function ClientComponent() { const pathname = usePathname(); const searchParams = useSearchParams(); const [fullUrl, setFullUrl] = useState(''); useEffect(() => { const origin = window.location.origin; const queryString = searchParams.toString() ? `?${searchParams.toString()}` : ''; setFullUrl(`${origin}${pathname}${queryString}`); }, [pathname, searchParams]); return <div>完整URL:{fullUrl}</div>; }
方法二:从服务器组件传递URL(SSR场景推荐)
如果需要在客户端组件的SSR渲染阶段就拿到完整URL,可先在父级服务器组件中获取URL,再通过props传递:
// 父级服务器组件 import { headers } from 'next/headers'; import ClientComponent from './ClientComponent'; export default function ParentServerComponent() { const headersList = headers(); const protocol = headersList.get('x-forwarded-proto') || 'http'; const host = headersList.get('host'); const pathname = headersList.get('next-url') || ''; const fullUrl = `${protocol}://${host}${pathname}`; return <ClientComponent fullUrl={fullUrl} />; }
'use client'; export default function ClientComponent({ fullUrl }) { return <div>完整URL:{fullUrl}</div>; }
这种方式能让客户端组件在SSR渲染时直接拿到完整URL,无需等待客户端 hydration。
内容的提问来源于stack exchange,提问作者A.A
相关产品推荐
相关产品推荐

