I have a pages/index.tsx
Next.js page whose code looks like this:
import { ApolloProvider } from "@apollo/react-hooks"
import Client from "../db"
import Header from "../components/Header"
export default function Index() {
return <ApolloProvider client={Client}>
<Header langKey={langKey} />
</ApolloProvider>
}
The problem is, langKey
is supposed to be the sub-domain from which the page is accessed (for instance, en.localhost:3000
or fr.localhost:3000
; langKey
would be en
or fr
). How do I retrieve this information from the Next.js context? I tried the Router object, but it doesn't look like it stores any URL information before the first /
.
On the getInitialProps
lifecycle method (doc's here) you can access the request object on the server-side and parse the host header.
Index.getInitialProps = async ({ req }) => {
const subdomain = req.headers.host.split('.')[0];
return { langkey: subdomain };
};
If this information is only needed on the client side you could just as easily parse window.location
somewhere in a lifecycle method with: window.location.host.split('.')[0]
.
Hope that helps!