dcangulo / nextjs-subdomain-example

https://stackoverflow.com/a/63544520/9375533

Home Page:https://stackoverflow.com/a/63544520/9375533

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Multiple _document, _app, _error pages

phibersoft opened this issue · comments

commented

Hi,
Thank you very much for this example you made, I was looking for such an architecture.

But I have a problem, I have to open separate _document pages for subdomains. Do you know any way you can do this?

Example :
(Directory List)

  • pages
    -admin
    -__document.tsx
    - index.tsx
    -main
    - _document.tsx
    - index.tsx

@phibersoft

I'm not that familiar with _document as I haven't been able to use it that much.

If I understood correctly, you want a different _document for admin and main app?

Can we do something like this in _document.jsx?

import Document, { Html, Head, Main, NextScript } from 'next/document';
import Admin from './your-admin-component';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);

    return { ...initialProps };
  }

  render() {
    const subdomain = window.location.hostname.split('.')[0];

    return (
      subdomain === 'admin' ? (
        <Html>
          <Head />
          <body>
            <Admin />
            <NextScript />
          </body>
        </Html>
      ) : (
        <Html>
          <Head />
          <body>
            <Main />
            <NextScript />
          </body>
        </Html>
      )
    );
  }
}

Haven't tried the example but I thought something like that. Basically it just renders different component based on the subdomain from the URL.

commented

Thank you for the answer. I will use this and try it, if I find a positive way I will inform :)