简体   繁体   中英

Next.js: How can I use getStaticProps/getStaticPaths for sites with multiple domains/hostnames?

I'm building a site with the structure https://[sub.domain.ext]/[language]/articles/[slug] , however it will have different content on different domains (different hostnames).

A typical use case of this would be different subdomains for different language translations of the same content: en.mysite.com, fr.mysite.com, etc.

I don't want to resort to server-side rendering using getServerSideProps (slower performance and unnecessary if content rarely changes). Can I somehow use getStaticProps / getStaticPaths for static site generation?

Here's my current implementation with siteId = 1 hardcoded:

import React from 'react'
import { useRouter } from 'next/router'

import Page from 'components/page/Page'
import Error from 'components/page/Error'
import ArticleList from 'components/articles/ArticleList'

const { runDatabaseFunction } = require('lib/database')
const { getArticlesForSiteAndLanguage } = require('lib/data/articles')

function ArticleListPage ({ site, articles, error }) {
  const { asPath } = useRouter()
  const title = 'News'
  return (
    <Page
      title={title}
      site={site}
      path={asPath}
    >
      <h1>{title}</h1>

      {error && <Error error={error} />}

      <ArticleList
        articles={articles}
      />
    </Page>
  )
}
export default ArticleListPage

export async function getStaticProps ({ params: { siteId = 1, languageCode = 'en' } }) {
  return {
    revalidate: 10,
    props: await runDatabaseFunction(async (pool) => getArticlesForSiteAndLanguage(pool, { siteId, languageCode }))
  }
}

export async function getStaticPaths () {
  return {
    paths: [
      { params: { languageCode: 'en' } } //  '[siteId]' is not part of folder structure
    ],
    fallback: true
  }
}

Update

See also:

A couple of approaches:

1. Using Next.js locale system

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:

The concept:

  • Next.js' i18n locale is used to determine the site .
  • Selecting a language is instead handled via a pseudoLocale prop (pages in a /[pseudoLocale] folder).
  • A redirect from / to /en .

2. Using rewrites in Next.js 10.2

See this conversation and this code repository .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM