Search code examples
reactjsnext.jsnext-router

Can I use Next.js Link to navigate from slug page to the default one?


So I have the default page and some 'slug' dynamic pages, the urls look like this:

default page locally: localhost:3000/doc/default
slug page locally: localhost:3000/doc/[slug]

default page in production: default.com/doc
slug page in production: [slug].default.com/doc

The link I need should be inside the slug pages and lead to the default one. So far I tried getting the basePath from nextRouter to use as a href. But that returns the slug url ([slug].default.com/doc.

Can I use the Next.js Link component and point it to /doc/default? It works locally, but I don't want to push it to dev/prod just to test if it works.


Solution

  • 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!