Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tackle redirect to an external url in NextJS?

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.

like image 444
Gilson Viana Avatar asked Oct 13 '20 19:10

Gilson Viana


3 Answers

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).

like image 155
w. Patrick Gale Avatar answered Oct 17 '22 08:10

w. Patrick Gale


Nextjs-redirect library should do what you want

like image 26
Lyuboslav Alexandrov Avatar answered Oct 17 '22 07:10

Lyuboslav Alexandrov


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(
        <>
        </>
    )
}
like image 31
Rashmi Abbigeri Avatar answered Oct 17 '22 06:10

Rashmi Abbigeri