KillerDogs
KillerDogs

Reputation: 31

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

Upvotes: 2

Views: 13601

Answers (2)

Awyssa
Awyssa

Reputation: 336

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

Upvotes: 1

Packa
Packa

Reputation: 183

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')
   }
 });

Upvotes: 7

Related Questions