I want to load a specific configuration (opening hours, company address,…) based on the subdomain. Thus I want to run a single instance of NextJS for different clients (each client has a subdomain).
I try
export async function getStaticProps() {
const subdomain = /:\/\/([^\/?]+)/.exec(window.location.href)[1].split(".")[0];
const config = mysqlquery(subdomain);
return {
props: {
config,
}
}
}
and I get window is not defined.
First install absoluteUrl then you should request to your local api to find subdomain let see the code:
export async function getStaticProps() {
const req = await
fetch("http://localhost:3000/api/hello");
const dd = await req.json();
console.log("sub", dd);
return {
props: {
aboutData: [],
},
};
}
now in pages/api/hello.js
import absoluteUrl from "next-absolute-url";
export default async function
handler(req,res) {
const { origin } = absoluteUrl(req);
let subdomain = origin.match(/\w+/);
console.log("request ", subdomain);
return res.status(200).json({ subDomain:
subdomain });
}
it will send an array subdomain is the first index of array actually i am not sure about regex that i write you can check if not work write your own regex to determin the subdomain
You can access the url using context.req.headers.referer, being your code as follows:
export async function getStaticProps(context) {
const subdomain = /:\/\/([^\/?]+)/.exec(context.req.headers.referer).split(".")[0];
const config = mysqlquery(subdomain);
return {
props: {
config,
}
}
}