Next.js Discord

Discord Forum

How to obtain the pathname in the server componen

Unanswered
Air Penguin posted this in #help-forum
Open in Discord
I know the general way to handle this issue in nextjs is to set the header in the middleware and then obtain this value through the headers where needed;
like this:
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// the following code is taken from : https://nextjs.org/docs/advanced-features/middleware#setting-headers
export function middleware(request: NextRequest) {
  return NextResponse.next({
     request: {
        // New request headers
        'x-pathname': request.nextUrl.pathname,
     },
  });
}

// the following code has been copied from https://nextjs.org/docs/advanced-features/middleware#matcher
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}

// app/some/where/page.tsx
import { headers } from 'next/headers';

export default async function Page() {
  const pathname = headers.get('x-pathname');
   
  return <>{/*... your page code */}</>
}


However, my page will be deployed with a CDN. I also know that I can set up lambda or Function on AWS. Apart from these, are there any other ways to achieve this?

9 Replies

umm, the pathname is just "some/where", I don't see any usecase to get the pathname in server component
its obvious because that specific function is beong executed
Thank you for your reply.
I have a server component that is used to detect whether the visiting user is a bot and report events. The event parameter will carry the url of the current page.
This is pseudo-code.
I placed this component in the root layout
export function CheckIsBot() {
    if (userProperty.isBot) {
        const headerStore = headers();
        const currentUrl = headerStore.get('x-next-pathname');
        fetch(`https://xxxx/api/report`, {
            method: 'POST',
            body: JSON.stringify({
                ts: Date.now(),
                currentUrl
            }),
            headers: {
                ...
||            }
        });
    }
}
Whiteleg shrimp
I did something very similar few months ago but instead of the request in NextResponse.next, we used response.headers.set("X-Pathname", pathname)
Also, the headers object should be invoked and awaited, may be that is the issue
Can't you fetch in middleware
@Anay-208 | Ping in replies Can't you fetch in middleware
Sure, I can be there, but I'm considering that if a CDN is added, it actually won't be able to reach the middleware, and thus won't be able to handle any headers and responses
@Whiteleg shrimp Also, the headers object should be invoked and awaited, may be that is the issue
Sorry, I didn't make it clear that I'm still using version 14