2

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

KillerDogs
  • 31
  • 1
  • 1
  • 3
  • Possible duplicate: https://stackoverflow.com/questions/58173809/next-js-redirect-from-to-another-page – Packa Aug 12 '21 at 23:34

2 Answers2

6

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')
   }
 });
Packa
  • 173
  • 14
1

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

swk23C8
  • 314
  • 3
  • 10
Awyssa
  • 116
  • 6