In any web application, managing URLs effectively is crucial for user experience and SEO. Next.js provides powerful tools, namely redirects and rewrites, to control how incoming requests are handled and what content is served. Understanding the difference between these two mechanisms will allow you to build more robust and user-friendly applications.
Redirects are primarily for informing the browser that a resource has moved to a new location. When a redirect occurs, the browser receives a status code (like 301 for permanent or 302 for temporary) and is instructed to make a new request to the specified URL. This means the original URL is no longer considered the authoritative source for the content.
Redirects are configured in the next.config.js file within the redirects array. Each redirect object needs a source (the incoming path) and a destination (the new path). You can also specify a statusCode (defaults to 307).
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
statusCode: 301,
},
{
source: '/users/:id',
destination: '/profile/:id',
statusCode: 302,
},
];
},
};In this example, requests to /old-page will be permanently redirected to /new-page. Requests to /users/123 will be temporarily redirected to /profile/123. The :id is a path parameter that gets passed along.
graph TD;
A[Browser Request to /old-page] --> B{Next.js Config};
B --> C[Redirect Rule Found];
C --> D[Send 301 Status Code];
D --> E[Browser Requests /new-page];
E --> F[Next.js Serves /new-page];