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"
}
};
};
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.
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.
js React app. Bookmark this question.
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.
getStaticProps
to getServerSideProps
(see documentation). This will mean the function is called at runtime, separately for each request.context
object passed to getServerSideProps
, pull out the Node.js http.IncomingMessage
object.Host
header.export const getServerSideProps = async ({ req }) => {
return {
props: {
name: req.headers.host === "www.google.com" ? "Hello" : "ccccc"
}
};
};
Note:
==
to ===
, as it's generally advised to use the latter. The former can produce some unexpected results because of silent type conversions.revalidate
, as this is not applicable to getServerSideProps()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With