Get URL Pathname in Next.js
1 min readOct 16, 2023
To Get Full URL of current page in Next.js you face some challenges regarding Next.js Server-side Rendering (SSR) behavior .
- If you try to handle it in Client side you can get full URL pathname easily for example using e.g. “window.location.href” but on Server Side “window” of “window.location.href” will be undefined and will cause problem in rendering since client side rendered content will be different than server side rendered content.
- If you try to handle it in Server side you can use some env variable for example and access it by “process.env.EXAMPLE” but again in client side “process.env.EXAMPLE” will be undefined.
One of best solutions to solve this is to get base url in server side and pass it to client side using “getServerSideProps()” and then in client side add pathname e.g. use “import { usePathname } from ‘next/navigation” to the base url that you pass from server side
Example Code:
import { usePathname } from 'next/navigation'
export default function Slug({pageUrl}) {
const pageFullUrl = pageUrl + usePathname();
if (!pageFullUrl) {
return;
}
// remain code ...
}
export async function getServerSideProps(context) {
const pageUrl = process.env.SITE_URL;
return {
props: { pageUrl }
}
}