Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

location is not defined error in react + next js?

I am trying to send some text on basic of hosted url (where my build is deployed).but i am getting this error ReferenceError: location is not defined here is my code

https://codesandbox.io/s/laughing-mendel-pf54l?file=/pages/index.js

export const getStaticProps = async ({ preview = false, previewData = {} }) => {
  return {
    revalidate: 200,
    props: {
      //req.host
      name: location.hostname == "www.google.com" ? "Hello" : "ccccc"
    }
  };
};
like image 248
user944513 Avatar asked Jan 21 '21 01:01

user944513


People also ask

Why is window undefined in next JS?

This is because, Next. js is server-side rendered, and it runs the component code in the server, sends the HTML to the browser, and the HTML gets hydrated in the browser.

How do you fix ReferenceError window is not defined?

To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.

Can I use window in next JS?

js React app. Bookmark this question.


Video Answer


2 Answers

Can you show your imports, because it could be that you are importing router from 'next/client'

Assuming that you are using functional-based component

You need to import router as follows:

import {useRouter} from "next/router";

in your function body:

const router = useRouter();
like image 135
Ismoil Shokirov Avatar answered Oct 23 '22 11:10

Ismoil Shokirov


getStaticProps() is executed at build time in Node.js, which has no location global object – Location is part of the browser API. Additionally, because the code is executed at build time, the URL is not yet known.

  1. Change getStaticProps to getServerSideProps (see documentation). This will mean the function is called at runtime, separately for each request.
  2. From the context object passed to getServerSideProps, pull out the Node.js http.IncomingMessage object.
  3. On this object, look for the Host header.
export const getServerSideProps = async ({ req }) => {
  return {
    props: {
      name: req.headers.host === "www.google.com" ? "Hello" : "ccccc"
    }
  };
};

Note:

  • I also changed == to ===, as it's generally advised to use the latter. The former can produce some unexpected results because of silent type conversions.
  • I also removed revalidate, as this is not applicable to getServerSideProps().
like image 36
Blieque Avatar answered Oct 23 '22 11:10

Blieque