Is it possible to get the hostname inside getStaticProps?
export async function getStaticProps(context) {
// get the hostname
const hostname = ?????
}
It's not possible to get the hostname inside getStaticProps as the props generated there are static and do not contain information on the request in any way. To get the hostname, you will have to use getServerSideProps or get the hostname on the client side in the page's component. Here is an example of getting the hostname in getServerSideProps:
export const getServerSideProps: GetServerSideProps<{ host: string; }> = async (context) => {
return {
props: { host: context.req.headers.host || null }
};
};
Here is an example of getting the hostname on the client side component using Location:
function Home() {
// window can be undefined when static generated, however it will be updated when the page is hydrated
const hostname = typeof window !== 'undefined' ? window.location.hostname : '';
}
export default Home;
create function :
export const hostname = "https://urldomain.com"
and import everywhere
import {hostname} from "./hostname";
export async function getStaticProps(context) {
// get the hostname
console.log(hostname)
}