You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13中如何在React服务端组件获取动态路由路径?

在Next.js 13服务端组件中获取URL的方法

在Next.js 13的App Router体系下,服务端组件无法使用客户端专属的usePathname,但可以通过以下两种方式获取URL相关信息:

1. 直接获取动态路由参数与查询参数

对于动态路由页面(比如src/app/[id]/page.tsx),服务端组件可以直接从props中解构出params和searchParams,无需额外API:

// src/app/[id]/page.tsx
export default function Page({ params, searchParams }: {
  params: { id: string };
  searchParams: Record<string, string | string[]>;
}) {
  // 提取动态路由中的[id]参数
  const dynamicId = params.id;
  // 提取URL中的查询参数(例如?username=xxx)
  const userName = searchParams.username;

  return (
    <div>
      <p>动态路由ID:{dynamicId}</p>
      <p>查询参数username:{userName}</p>
    </div>
  );
}

2. 获取完整URL或路径名

如果需要完整的URL或者纯路径信息,可以使用Next.js提供的headers()函数,从请求头中提取关键信息后拼接:

// src/app/[id]/page.tsx
import { headers } from 'next/headers';

export default function Page() {
  const headerList = headers();
  // 获取请求的域名(例如localhost:3000或生产环境域名)
  const host = headerList.get('host');
  // 获取当前请求的完整路径(包含查询参数,Next.js内部请求头)
  const pathname = headerList.get('next-url');
  // 根据运行环境判断协议(生产环境默认https,开发环境http)
  const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
  // 拼接得到完整URL
  const fullUrl = `${protocol}://${host}${pathname}`;

  return (
    <div>
      <p>当前路径:{pathname}</p>
      <p>完整URL:{fullUrl}</p>
    </div>
  );
}

注意事项

  • headers()是服务端组件专属API,仅能在服务端组件中调用,无法在客户端组件或Server Actions外使用。
  • next-url是Next.js内部维护的请求头,仅在App Router的服务端组件环境中有效,包含当前请求的完整路径及查询参数。

内容的提问来源于stack exchange,提问作者Evanss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:12:15