27

I have in place my next.config.js file with regular redirect rules, all within the same domain and all works fine. But in a specific case, I need to redirect the request from a certain URL (mydomain.com/abc) to a different domain. i.e differentdomain.com

How do I go about creating this rule to redirect to an external link in NextJs?

I appreciate any insight.

Gilson Viana
  • 723
  • 1
  • 8
  • 13
  • 5
    The [docs](https://nextjs.org/docs/api-reference/next/router) say to use `window.location` in those cases rather than `router.push`. If that doesn't help, you'll need to provide code for what you tried so we can help troubleshoot. – Ouroborus Oct 13 '20 at 20:44
  • I've used the `nextjs-redirect` library with a set of custom redirects on my `next.config.js` file. – Gilson Viana Oct 14 '20 at 13:22
  • 2
    External redirect rules are built into next.config.js now (see https://nextjs.org/docs/api-reference/next.config.js/redirects) – w. Patrick Gale Jul 08 '21 at 16:33

3 Answers3

38

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: '/',
        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).

w. Patrick Gale
  • 1,643
  • 13
  • 22
10

Nextjs-redirect library should do what you want

9

You can try using window.location

Here's an example in which upon visiting a page it redirects the user to external url

// pages/redirect

import {useEffect} from 'react'
export default function redirect() {
    useEffect(() => {
        window.location.assign('https://duckduckgo.com/')
    })
    return(
        <>
        </>
    )
}
Rashmi Abbigeri
  • 135
  • 1
  • 3
  • 1
    The problem is, when you return the page, it returns to page/redirect and redirects again to the location – Flavio Oliveira Jul 07 '22 at 11:10
  • …and the much bigger problem is that it works only with JavaScript enabled and will be ignored by search engines etc – Bergi Mar 06 '23 at 20:06