Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js 13 current URL

In SSR when I am using Next.js App Router, How can I get full URL of the current page?

I cannot use window.location.href as window is not defined and with useRouter() I cannot get full URL

like image 866
WebMaster Avatar asked Feb 06 '26 13:02

WebMaster


2 Answers

Create a middleware.ts (or .js) in the root of your project. (https://nextjs.org/docs/app/building-your-application/routing/middleware)

import { NextResponse } from 'next/server';

export function middleware(request: Request) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-url', request.url);

  return NextResponse.next({
    request: {
      headers: requestHeaders
    }
  });
}

then use headers in your layout or page. (https://nextjs.org/docs/app/api-reference/functions/headers#headers)

const requestUrl = headers().get('x-url')
like image 72
arvi0731 Avatar answered Feb 09 '26 09:02

arvi0731


I realise this is not a solution applicable to all use cases or a straightforward answer to the question, but you can use the spread operator to get all url params, regardless of how many params there are. So for example:

/app
  - page.tsx
  - layout.tsx
  /[...slug]
    - page.tsx

In your /[...slug]

const DetailPage = async ({ params }) => {

  console.log(params.slug)

  return (
    <div>...</div>
  )
}

So www.website.com/hello/there/how/are/you will return ['hello', 'there', 'how', 'are', 'you'].

And you could then re-construct your url if you know your baseUrl (which I assume you will)

like image 23
BleddP Avatar answered Feb 09 '26 07:02

BleddP