Blog>
Snippets

Redirects and Rewrites with Route Manifest

Demonstrate how to define redirects and rewrites within your routes manifest, leveraging new file-based routing configurations.
// In a next.config.js or routes-manifest.json
module.exports = {
  async redirects() {
    return [
      {
        source: '/old-route', // The old route you want to redirect from
        destination: '/new-route', // The new route you want to redirect to
        permanent: false, // This is not a permanent redirect, set true for 301 permanent redirect
      },
    ];
  },
  async rewrites() {
    return [
      {
        source: '/rewrite-me', // This is the virtual path that gets rewritten
        destination: '/actual-path', // The actual path to which we rewrite
      },
      {
        source: '/api/:path*', // Matches all routes starting with /api/
        destination: 'https://external-api.example.com/:path*', // Rewrite to an external API
      },
    ];
  },
};
This code defines a `next.config.js` or `routes-manifest.json` configuration for Next.js with two functions: `redirects` and `rewrites`. The `redirects` function returns an array of objects with `source`, `destination`, and `permanent` properties to configure route redirections. The `rewrites` function includes an array of rewrite rules, specifying a `source` path that is rewritten to a `destination` path. One rewrite rule demonstrates internal rewriting, while the other demonstrates rewriting to an external API.