Have you tried redirects
?
Next.js has an experimental a feature to redirect pages ahead of time inside its next.config.js
file.
Let's say we'd like to redirect our root path site.com/
to site.com/en-us/
. We could use useRouter
whenever we needed to redirect the user or we could add directly into next.config.js
:
const nextConfig = {
async redirects() {
return [
{
source: '/',
permanent: false,
destination: '/en-us',
},
]
}
}
Now anytime the user navigates to site.com/
he'll be redirected to site.com/en-us/
which will render the page inside pages/en-us/index.(jsx|tsx|mdx)
. It is also possible to use RegEx for matching as described on this issue.
For your use case, would be the the other way around. We'd probably have to use absolute paths, since we're redirecting to another domain. In this case, a subdomain of our root default.com
domain.
// const getSlugs = fs.readdir(path.resolve(...), () => {})
const slugs = ['slug1', 'slug2']
const slugRedirects = slugs.map(slug => ({
source: `/doc/${slug}`,
destination: `https://${slug}.default.com/doc`,
permanent: false
}))
const nextConfig = {
async redirects () {
return [...slugRedirects]
}
}
module.exports = nextConfig
Now, whenever the user navigates to www.default.com/doc/slug1
, either by typing the URL or clicking on a button that points to the pages/doc/[slug]
pages, he will be redirected to slug1.default.com/doc
.
Let me know if that helps. Cheers!