7

I'm using the experimental appDir in Next.js 13, and want to get the URL path of the request. I need this info to set the searchparams before I do the redirection. I want to get the request path on the server side.

There is a question with similar to this. How to get current pathname in app directory with Next 13? However it concerns with getting pathname on the client side.

I have tried looking into the Layout option and it has props of only children and params. I will not be able to reconstruct the URL with that info. I would like to know where the request is coming from on the server side. How can I achieve this?

Progman
  • 16,827
  • 6
  • 33
  • 48
p2hari
  • 494
  • 6
  • 16
  • 1
    The linked [thread](https://stackoverflow.com/questions/74584091/how-to-get-the-current-pathname-in-the-app-directory-of-next-js-13) has been updated to answer this question. – Youssouf Oumar Jul 26 '23 at 09:49

4 Answers4

4

Nextjs13 app dir doesn't have a nice API for this yet. It'll be nice if the props passed down the segment.

For now, you can use children.props.childProp.segment to get the path of your route on the server.

khuezy
  • 157
  • 1
  • 9
2

You can pass params to the function and can access to the dynamic route in this case i assume your dynamic route is [id]

export default function Page({params}) {
  return (
    <>
      <div className={styles.container}>
        <h1>Page for {params.id}</h1>
      </div>
    </>
  )
}
1

You probably might want to use searchParams

export default function Page({ params, searchParams }) {
Aziz
  • 859
  • 6
  • 16
0

You can use a middleware file to achieve this.

    // middleware.ts
    import { NextResponse } from 'next/server';
    
    export function middleware(request: Request) {
    
      // get the URL from request header
      const requestHeaders = new Headers(request.headers);
      requestHeaders.set('x-url', request.url);
    
      // pass the header to the layout
      return NextResponse.next({
        request: {
          headers: requestHeaders,
        }
      });
    }

To get it in layout:

    // app/layout.tsx
    import { headers } from 'next/headers';
    
    export default function RootLayout() {
      const headersList = headers();
      // read the custom x-url header
      const header_url = headersList.get('x-url') || "";
    }

Warning: Doing this will turn off the Server-Side Generation and will trigger Server-Side Rendering because functions like cookies(), headers() are dynamic. They can also result in Cache Miss!

Reference: https://github.com/vercel/next.js/issues/43704#issuecomment-1411186664

You can read the complete issue here: https://github.com/vercel/next.js/issues/43704

Farasat Ali
  • 398
  • 3
  • 6