I am working on a Next.js multisite scoped project and I need to create a set of global variables to use on client and server (during SSR) side.
So far I came to the below solution.
This is how my custom App looks like:
import App from 'next/app'
import multisite from '@utils/multisite';
import MultisiteProvider from '@components/multisite/MultisiteProvider';
function MyApp({
Component,
site,
pageProps
}) {
// Will add site props to every page
const props = { ...pageProps, site };
return (
// Provider will enable a hook to get site props on any child component
<MultisiteProvider site={ site } >
<Component { ...props }/>
</MultisiteProvider>
)
}
MyApp.getInitialProps = async(appContext) => {
// getInitialProps executes on every page access, even on client when using "next/link"
const appProps = await App.getInitialProps(appContext);
let host;
if (appContext.ctx.req) {
// Get host from request during SSR
host = appContext.ctx.req.headers.host;
} else {
// Get host from window on client
host = window.location.host;
}
return {
...appProps,
site: await multisite.resolveSiteProps(host)
};
}
export default MyApp;
I would like to avoid using getInitialProps because it was supposed to disable Automatic Static Optimization in pages without Static Generation (which is my case). As mentioned on docs
The variables for each site are located on a "sites" directory under root folder like this:
/sites
--/siteone.com.us.json
--/siteone.com.br.json
--/sitetwo.com.us.json
And there is a function used to load the right file based on the current request domain.
const resolveSiteProps = async(host) => {
const domain = normalizeDomain(host);
const site = await
import (
/* webpackChunkName: "site-prefs" */
/* webpackMode: "lazy" */
`../sites/${domain}`
);
return {
...site.default,
domain
};
}
It would be nice if I could resolve this variables once during SSR and just use them in the client side.
I am looking for some helpful and elegant ideas to solve this case. Any thoughts?