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.
Error: No router instance found. you should only use "next/router" inside the client side of your app.
Thanks.
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.
const router = useRouter();
useEffect(() => {
router.push('/projects');
},[])
return null
may be this work
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.