'Redirect page to url Next.JS

I have a simple web page running next.js, the page just returns the "Hello World" element and I would like it to redirect me to another URL (youtube) instead.

It is basically a redirect page when loading.

My simple page:

function Home() {
    return <div>Hello World</div>
}

export default Home

I even tried the js window.location function, but to no avail



Solution 1:[1]

In next.js you can redirect after the page is loaded using Router ex :

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}

Or with Hooks :

import React, { useEffect } from "react";
...
useEffect(() => {
   const {pathname} = Router
   if(pathname == '/' ){
       Router.push('/hello-nextjs')
   }
 });

Solution 2:[2]

In order for the page to redirect while server-side rendering, you can put this at the bottom of your export function in your /pages/file and set an if conditional.

So for example, if that page doesn't exist, it will redirect to something else.

This way you don't have to play around with route.push.

if (!pageData) {
    res.statusCode = 301;
    res.setHeader("location", "/page-you-want-to-redirect-to");
    res.end();
    return {props: {notFound: true}};
}

export default Page

Thanks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Packa
Solution 2 swk23C8