How to tackle redirect to an external url in NextJS?

The latest version of Next.js has this built in using the next.config.js script (see https://nextjs.org/docs/api-reference/next.config.js/redirects). No need for additional plugins.

To test, copy the NextJs sample app:

npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn-starter/tree/master/learn-starter"

Add a next.config.js file to the root folder with the following code:

// this simply tests the redirecting of the root path (source)
module.exports = {
  async redirects() {
    return [
      {
        source: "https://stackoverflow.com/",
        destination: 'https://stackoverflow.com/posts/66662033',
        permanent: false,
        basePath: false
      },
    ]
  },
};

When you start the app npm run dev and visit localhost:3000, it should redirect to the destination URL specified in the next.config.js script (https://stackoverflow.com/posts/66662033).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)