location is not defined error in react + next js?

Viewed 13403

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"
    }
  };
};
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();

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().
Related