Search code examples
next.jsurl-routing

How to combine a static string with a dynamic slug in Next.js dynamic routes?


I've tried to check through the official documentation, various issues, and inside SO previous questions, but I can't find confirmation if it's possible to create a dynamic route in Next.js that contains a constant or a string combined with a slug. For example?

pages/
  something-[slug].jsx

Is it possible or not? I'm inclined to think not because of the examples I've tried to build, but possibly I'm missing something.


Solution

  • While Next.js doesn't provide built-in support for partial dynamic routes (like something-[slug]), you can work around it by setting up an actual dynamic route and use rewrites to map the incoming URL (in the format you want) to that route.

    For instance, you could setup a dynamic route under /pages/something/[slug].jsx, then configure a rewrites rule in next.config.js as follows.

    // next.config.js
    
    module.exports = {
        async rewrites() {
            return [
                {
                    source: '/something-:slug',
                    destination: '/something/:slug'
                }
            ];
        }
    }