How to get page URL or hostname in NextJs Project?

Raju Ahammad picture Raju Ahammad · Dec 8, 2020 · Viewed 13.3k times · Source

I want to get the page's full URL or site hostname like the image below on Static Site Generator.

I will try with window.location.hostname, but it doesn't work.

The error: window not defined.

enter image description here

Answer

Aadil Mehraj picture Aadil Mehraj · Dec 8, 2020

The place where you are accessing the window make sure you add a check so that code is executed only on the browser and no during SSG"

if (typeof window !== 'undefined') {
   const hostname = window.location.hostname;
}

Update: If you have specified basePath in next.config.js:

module.exports = {
  basePath: 'https://www.example.com/docs',
}

Then using useRouter, you can access the base path:

import { useRouter } from 'next/router'

function Component() {
   const router = useRouter();
   
   console.log({ basePath: router.basePath}); 
   // { basePath: 'https://www.example.com/docs' }

   ...
}

But if you have a relative base path then you can use the first approach