Next.js Discord

Discord Forum

get pathname in server component

We can get the pathname using next/headers but there is one problem here. It only works when we use next/link but whenever we reload the page it doesn't work and we get null value when accessing next-url from headers:
const headersList = headers();
const pathname = headersList.get("next-url");


I tried creating a middleware in app/middleware.ts:
// /middleware.ts
import { NextResponse } from "next/server";

export function middleware(request: Request) {
  // Store current request url in a custom header, which you can read later
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-url", request.url);

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


And access it one of my component which is showing me null value while getting this x-url from headers.

Is there any way I can access pathname in server components?

13 Replies

that means either we have to pass the params at the page level to the child component by props drilling or use client directive for that to get the pathname ?
but my middleware is not working...is there anything wrong i am doing ? Like i created a middleware at app/middleware.ts then i just used next/headers in a child component to get pathname which I have set in the middleware. Although, I haven't used that middleware anywhere
yeah...Well, I guess I will have to do something from the backend
Surely somewhere inside NextJS (the library) would the code know what path has invoked which HTML/JSX code
Can't help but wonder if this is a flaw in the lib (maybe on React's end but in a lib nonetheless)
@GetPsyched I might sound dumb here but shouldn't the server have a way to know what path has invoked what function?
Yes, that is known as middleware + headers. BUT: you only know what was the pathname of the first request, all subsequent requests inside the same layout won’t be caught because the layout is static. There are no flaws here, everything works as expected.
Hmm
Makes sense