yogurtsyum
yogurtsyum

Reputation: 348

How to redirect before rendering page in Next.js?

I am wondering if I can redirect a user before rendering a page in Next.js?

Right now I have this:

import { useRouter } from 'next/router';

export default function RedirectPage() {
    const router = useRouter();
    router.push('/projects');

    return (
        <div><h1>hi</h1></div>
    )
}

With this error: Error: No router instance found. you should only use "next/router" inside the client side of your app.

Thanks.

Upvotes: 0

Views: 4118

Answers (3)

Tilak Madichetti
Tilak Madichetti

Reputation: 4346

Use the Router class to redirect

import Router from "next/Router"

export default function RedirectPage() {

    Router.push({
       pathname: '/projects'
    })

    return (
        <>Redirecting ....</>
    )
}

This way you dont have to make an instance

Upvotes: 0

Vibhav
Vibhav

Reputation: 321

const router = useRouter();

useEffect(() => {
    router.push('/projects');
},[])

return null

may be this work

Upvotes: 0

B.R.
B.R.

Reputation: 56

You could do it with getServerSideProps by having a 'redirect' property on the returned object.

export default function RedirectPage() {
    return (
        <div><h1>hi</h1></div>
    )
}

export async function getServerSideProps(ctx) {
  return {
    redirect: {
      destination: '/projects',
      permanent: false,
    },
  }
}

I can't say if this will render the page on server or not, but the user will be redirected and not be shown the content of the redirect page.

Upvotes: 3

Related Questions