Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next JS Use query parameter as variable in rewrite

Using Next JS I want to redirect requests on path /home?id=123qwert to the new destination path of /home/123qwert

I'm having issues with extracting the query parameter from the source to be used again in the destination.

Here is my current implementation:

    async rewrites() {
        return [
            /**
             * My source URL -> /home?id=123qwerty
             * My new destination -> /home/123qwerty
             */
            {
                source: '/home?id=:cmsId*',
                destination: '/home/:cmsId*'
            }
        ];
    }

I have a dynamic page setup for home as /home/[id].js

I keep getting the following error:

Reason: Unexpected MODIFIER at 5, expected END

  /home?id=:cmsId*
       ^

`source` parse failed for route {"source":"/home?id=:cmsId*","destination":"/home/:cmsId*"}
like image 378
Kris Stadler Avatar asked May 02 '26 07:05

Kris Stadler


1 Answers

You can use query matching using the has field to match a rewrite by query values, with the beforeFiles syntax so the match happens before the filesystem check.

async rewrites() {
    return {
        beforeFiles: [
            {
                 source: '/home',
                 has: [
                     {
                         type: 'query',
                         key: 'id',
                         value: '(?<cmsId>.*)' // Named capture group to match anything on the value
                     }
                 ],
                 destination: '/home/:cmsId'
             }
         ]
    };
}
like image 158
juliomalves Avatar answered May 04 '26 20:05

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!