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.
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).
Nextjs-redirect library should do what you want
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(
<>
</>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With