I'm trying to figure out a way to have some code run on initial page load for each request. I want to be able to identify the request domain and redirect to a specific part of the website based on it.
From what I can understand I could add getInitialProps to a custom _app page but that would disable all optimization from next. Also _app doesn't seem to support getServerSideProps which I considered as an alternative.
Another way I thought about doing it was to have getServerSideProps in each page of the website with the check I have to do, but this would make every page rerender on server side for each new request, disabling rendering at build time even for pure static pages.
Is there any other solution I can adopt?
EDIT
Basically I need the request object so that I can do something like this:
export const getServerSideProps: GetServerSideProps = async ({
req
}) => {
if (req.headers.host === 'something') {
return {
redirect: {
permanent: false,
destination: "/"
}
}
}
I would put solutions to this in the order below:
You can use Next.js redirects in your next.config.js file.
module.exports = {
async redirects() {
return [
{
source: '/(.+)',
has: [
{
type: 'header',
key: 'host',
value: 'something'
}
],
permanent: false,
destination: '/'
}
]
}
}
This rule will match any path that's not /, and redirect if it contains the desired host header value.