How to link same page with two urls in nextjs

Viewed 3123

I want to show the city name in the url before page name if the user is searching for a specific city, and if the user is not searching for a specific city then I want to show the normal url. How can we achieve this in Next Js.

Ex.

     http://localhost:3000/Delhi/furniture
     http://localhost:3000/furniture

Both the urls should point to same page.

I tried with next/link component.

<Link href='/furniture' as={config.city ? config.city + '/furniture': 'furniture'}><a>Furniture</a></Link>

Link has two props href and as. Using as we can show different url than the actual url but if you directly hit the url which is changed by 'as' prop it will show 404 page not found. I could not find any porp or feature using which I can achieve the above.

1 Answers

You could use rewrites in your next.config.js to map the paths containing a city to the furniture route.

// next.config.js

module.exports = {
    async rewrites() {
        return [
            {
                source: '/:city/furniture',
                destination: '/furniture'
            }
        ];
    }
}

You can also add regex path matching to allow matching only certain values for :city.

Related