Next.js(App Router)如何在客户端组件获取rewrites的destination值
在Next.js App Router中获取重写后的实际路由
核心原因
客户端组件的usePathname()返回的是浏览器地址栏显示的原始请求路径——因为Next.js的rewrite是服务端内部处理的,客户端完全不知道重写逻辑,所以无法直接拿到重写后的目标路由。
解决方案
1. 服务端组件传值(最直接)
利用服务端组件能访问重写后内部路由的特性,在服务端获取实际路径,再通过props传给客户端组件:
示例代码:
- 服务端页面组件(
app/[any-alias]/page.tsx):
import ClientComponent from './ClientComponent'; import { usePathname } from 'next/navigation'; export default function AliasPage() { // 服务端的usePathname()返回重写后的内部路由,比如"/my-alias" const actualPathname = usePathname(); return <ClientComponent actualPathname={actualPathname} />; }
- 客户端组件(
ClientComponent.tsx):
'use client'; export default function ClientComponent({ actualPathname }: { actualPathname: string }) { // 直接使用服务端传来的实际路由 return <div>实际路由:{actualPathname}</div>; }
2. 从路由参数直接构造
如果你的重写规则是把子域名的[any-alias]映射到内部路由的/[any-alias],可以直接从服务端组件的params里提取参数,构造实际路径:
import ClientComponent from './ClientComponent'; export default function AliasPage({ params }: { params: { anyAlias: string } }) { const actualPathname = `/${params.anyAlias}`; return <ClientComponent actualPathname={actualPathname} />; }
3. 利用Middleware注入自定义信息(复杂场景)
如果需要在多个组件中共享实际路由,可在middleware.ts中把重写后的路径注入到请求头或响应头,再在服务端组件中读取后传递:
middleware.ts:
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { // 获取重写后的目标路由(nextUrl.pathname就是内部路由) const actualPathname = request.nextUrl.pathname; // 注入自定义响应头 const response = NextResponse.next(); response.headers.set('X-Actual-Pathname', actualPathname); return response; } export const config = { matcher: ['/:path*'], // 匹配所有路由 };
- 服务端组件中读取并传递:
import { headers } from 'next/headers'; import ClientComponent from './ClientComponent'; export default function Page() { const actualPathname = headers().get('X-Actual-Pathname') || ''; return <ClientComponent actualPathname={actualPathname} />; }
内容的提问来源于stack exchange,提问作者Hung Duong Phi
相关产品推荐
相关产品推荐

