В серверных компонентах нельзя использовать хуки. Поэтому, чтобы получить текущий URL, надо использовать middleware, который запишет текущий URL в headers:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
// Добавляем новый заголовок x-current-path, который получим в компоненте
const headers = new Headers(request.headers);
headers.set("x-current-path", request.nextUrl.pathname);
return NextResponse.next({ headers });
}
export const config = {
matcher: [
// Сопоставим со всеми маршрутами кроме статических файлов и API
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};
Пример компонента, который получает объект с заголовками через функцию headers:
import { headers } from "next/headers";
export default async function Sidebar() {
const headerList = headers();
const pathname = headerList.get("x-current-path");
// ...etc
}
https://www.propelauth.com/post/getting-url-in-next-server-components