在 Next.js 的服务端组件中获取当前请求的路径

如果希望在 Next.js 的服务端组件(Server Component)中获取当前请求的路径(pathname),但又不想使用 API 路由或客户端组件(Client Component),可以通过使用 Middleware 来实现。

使用 Middleware 获取当前路径

可以在 Next.js 的 Middleware 中拦截请求,并将当前路径添加到请求头中,然后在服务端组件中读取该请求头,从而获取当前路径。

1. 创建 Middleware

在项目的根目录下创建一个 middleware.ts 文件:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-current-path', request.nextUrl.pathname);

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

上述 Middleware 会将当前请求的路径添加到请求头中的 x-current-path 字段。(Medium)

2. 在服务端组件中读取路径

在服务端组件中,可以使用 headers() 方法读取请求头,从而获取当前路径:(propelauth.com)

import { headers } from 'next/headers';
export default async function Getsuffix(layer : number):Promise<string>{
  const headerList = await headers();
  const pathname = headerList.get('x-current-path') || '/';
  // 解析路径后缀
  const segments = pathname.split('/');
  const titleSuffix = segments[layer] || '';
  return (
    titleSuffix
  );
}
添加新评论