NextJS redirects not redirecting urls after define in next.config.js file

Viewed 6569

I tried to define redirects in my NextJS app. but it is not working.

This is how I tried to do it in my next.config.js file:

const withImages = require('next-images')
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");

module.exports = withPlugins(
    [
        [optimizedImages, {
            inlineImageLimit: 512
        }]
    ],
    {
        async redirects() {
            return [
                {
                    source: "/sales/guest/form",
                    destination: "/",
                    permanent: true
                }
            ]
        },
        env:{
            testEnvVar: 'vallll'
        }
    }
);

This is the documentation of how to do it: https://nextjs.org/docs/api-reference/next.config.js/redirects

4 Answers

For redirects and rewrites to work properly in NextJs, you also need to ensure one more thing:

If you are using trailingSlash: true then your source paths must end with a slash.

{
    source: '/old/:id/',  // Notice the slash at the end
    destination: '/new/:id',
},

Any other plugins or configurations that interfere with routing also need to be taken into account.

you can add all you imports and also const definitions to first array parameter like this

const withPlugins = require('next-compose-plugins');
const css = require('@zeit/next-css');
const less = require('@zeit/next-less');

const nextConfig = {
  target: 'serverless',
  webpack(config, { isServer, webpack }) {
   // al your config
      
    return config;
  },
};

const redirects = {
  async redirects() {
    return [
      {
        source: '/old/blogs/:slug*',
        destination: 'whatever your new rewrite url',
        permanent: true,
      },
    ];
  },
};
module.exports = withPlugins(
  [
    [css],
    [less],
    [redirects], // you can directly drop your redirect rules here 
  ],
  nextConfig
);

For anyone who has this problem, try restarting the server. The config file will be reloaded then.

What NextJS Version are you on? Redirects are supported from 9.5 upwards

Related