URL Redirects and Rewrites in Next.js
Introduction
In Next.js, URL redirects and rewrites are essential for optimizing user experience and maintaining SEO. This lesson covers the definitions, implementations, and best practices for managing redirects and rewrites in Next.js applications.
Key Concepts
Definitions
- Redirects: A method to send users from one URL to another.
- Rewrites: A way to map an incoming request URL to a different destination without changing the URL shown in the browser.
Redirects
Redirects in Next.js can be implemented globally or on a per-page basis.
Global Redirects
module.exports = {
async redirects() {
return [
{
source: '/old-path',
destination: '/new-path',
permanent: true, // 301 redirect
},
]
},
}
Conditional Redirects
module.exports = {
async redirects() {
return [
{
source: '/old-path',
has: [
{
type: 'query',
key: 'ref',
value: '123',
},
],
destination: '/new-path',
permanent: false, // 302 redirect
},
]
},
}
Rewrites
Rewrites allow you to modify the URL path while keeping the original URL in the browser address bar. This is useful for server-side rendering and API routes.
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://external-api.com/:path*', // Proxy to external API
},
]
},
}
Best Practices
- Use permanent redirects (301) for moved content.
- Keep your redirects and rewrites organized and documented.
- Monitor and analyze redirect performance and user flow.
- Test all redirects and rewrites thoroughly before deploying.
FAQ
What is the difference between a redirect and a rewrite?
Redirects change the URL in the browser, while rewrites do not. Rewrites map a request to a different resource without altering the URL in the address bar.
Can I use both redirects and rewrites in the same Next.js application?
Yes, you can use both simultaneously and configure them based on your application needs.
How do I test my redirects and rewrites?
You can test them locally by running your Next.js application and accessing the specified URLs. Tools like Postman can help verify API redirects.