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
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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With