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
}
}
See also:
getStaticProps can only be exported from a page. You can't export it from non-page files.It will not work if you add getStaticProps as a property of the page component. Save this answer.
You should use getStaticProps if: The data required to render the page is available at build time ahead of a user's request. The data comes from a headless CMS. The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance.
getStaticProps(): A method that tells the Next component to populate props and render into a static HTML page at build time. getServerSideProps(): A method that tells the Next component to populate the props and render into a static HTML page at run time.
A couple of approaches:
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:
locale
is used to determine the site.pseudoLocale
prop (pages in a /[pseudoLocale]
folder)./
to /en
.See this conversation and this code repository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With