#Rewrite rule
1 messages · Page 1 of 1 (latest)
Hi @sharp plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can use the rewrites function in your next.config.js file to handle URL rewriting. This can be useful when you want to pass parameters in your API request.
Here's how you can do it:
- If none of the parameters are used in the
destination, they will be passed in the query by default.
module.exports = {
async rewrites() {
return [
{
source: '/old-about/:path*',
destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
},
]
},
}
- If a parameter is used in the
destination, none of the parameters will be automatically passed in the query.
module.exports = {
async rewrites() {
return [
{
source: '/docs/:path*',
destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
},
]
},
}
- You can still pass the parameters manually in the query if one is already used in the
destinationby specifying the query in thedestination.
module.exports = {
async rewrites() {
return [
{
source: '/:first/:second',
destination: '/:first?second=:second',
// Since the :first parameter is used in the destination the :second parameter
// will not automatically be added in the query although we can manually add it
// as shown above
},
]
},
}
Remember, static pages from Automatic Static Optimization or prerendering params from rewrites will be parsed on the client after hydration and provided in the query.
For more details, you can refer to the Next.js documentation on rewrites (https://nextjs.org/docs/pages/api-reference/next-config-js/rewrites).