TGViewer
Заметки про React Заметки про React @ru_react_notes · 3.43K subscribers
Post #443 3.59K
Получение текущего URL в серверных компонентах в Next.js

В серверных компонентах нельзя использовать хуки. Поэтому, чтобы получить текущий 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
Propelauth Getting the Current URL in Next.js Server Components You are writing a server component using the new(ish) App Router in Next.js, when you realize you need to get the current URL’s path. This could be for a sidebar, navbar, or even just breadcrumbs at the top of your page. Should be pretty easy, a quick Google…
  • 👍 20
  • 👎 7
  • ❤ 1
More from @ru_react_notes
  1. Jun 24, 2025Реактивность – это легко Стандартный useContext заставляет обновляться все компоненты-потр…
  2. Jun 17, 2025Остерегайтесь скрытых проблем при работе с search params Типо-безопасность — это только ве…
  3. Jun 4, 2025Почему Error Boundary, а не просто try/catch для компонентов В React нельзя использовать t…
  4. May 29, 2025Анонс TypeScript Native Вышла превью версия TypeScript написанная на Go. Ее можно установи…
  5. May 27, 2025Управление фокусом в React с помощью flushSync Установить фокус на инпуте сразу в React мо…
  6. May 15, 2025TanStack DB TanStack представила новую библиотеку – TanStack DB – реактивный клиентский ст…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →