Reputation: 115
I want to render dynamic next.js pages with custom content / style based on the domain which requests the page. Basically run one next.js app under multiple domains.
I know that I have to do some sort of custom routing, but don't know exactly how and how I can pass the host information to the requested page, so it fetches the matching data from a database.
Upvotes: 2
Views: 5381
Reputation: 4747
Here’s an example of hosting multiple domains on the same Next.js site (while maintaining multiple languages and static site generation/SSG), using Next.js’ i18n system:
https://github.com/tomsoderlund/nextjs-multi-domain-locale
Upvotes: 2
Reputation: 2428
You should be able to verify this in your pages/_app.jsx
file static getInitialProps(context)
method and use the context
to verify where the request is coming from then return a flag to the component.
Example:
// pages/_app.js
import app from 'next/app';
export default class MyApp extends app {
static getInitialProps({ Component, router, ctx }) {
let pageProps = app.getInitialProps({ Component, router, ctx });
if (ctx.req.headers.host.match(/localhost/)) {
pageProps = {
...pageProps,
renderFrom: 'mydomain',
}
}
return { pageProps };
}
render() {
const { Component, pageProps } = this.props;
return (
<section id="app">
<Component {...pageProps} />
</section>
);
}
}
Note that I call app.getInitialProps
to mimic the next/app
component behaviour as in the source code here
In your pages/index.js
you will have access to props.renderFrom
and there you can display data.
// pages/index.js
import React from 'react'
const Home = props => (
<div>
Rendering content for domain: {props.renderFrom}
</div>
)
export default Home
Since you're verifying where the request comes from in _app.js
this property will be available in all your containers (pages) so you can have the same routing for your application and just render data differently.
Tip: You could also use next-routes
to manage the routing for the application, it's better than the out next comes with, and in here you have a custom server where you can manage your traffic as well.
Hopefully this helps you and points you in the right direction.
Upvotes: 13