Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get page URL or hostname in NextJs Project?

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

like image 343
Raju Ahammad Avatar asked Dec 08 '20 12:12

Raju Ahammad


People also ask

How do I find my NextJs hostname?

If you deployed your Next. js app with now the apiURL will be something like https://your-app.now.sh/api/job.js . However, if you are running the app locally the apiURL will be http://localhost:8000/api/job.js instead. Save this answer.

How do I get the host URL in React?

Use the window object to get the current URL in React, e.g. window. location. href returns a string containing the whole URL. If you need to access the path, use window.

What is getInitialProps in next JS?

Learn more about incrementally adopting app/ . getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. getInitialProps will disable Automatic Static Optimization.

Can I use Express with NextJs?

js doesn't replace Express and you can use them together. Next. js uses some Node. js features, mainly for front-end development, while ExpressJS is used only for back-end development.


1 Answers

If you want the hostname inside getInitialProps on server side, still you can get it from req

Home.getInitialProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }
like image 183
Prabhu Avatar answered Sep 20 '22 12:09

Prabhu