Reputation: 136
I want to redirect an user to an Error page if I don't find a code query
param
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function Home(props){
const router = useRouter();
useEffect(() => {
if(!props.code){
console.log('No code found');
router.push('/error');
}
});
// call an api passing the code
return (
<>
<div>Something</div>
</>
)
}
export async function getServerSideProps(context) {
context.res.setHeader('Cache-Control', 'No-Cache');
return {
props: { code: context.query.code || null }
}
}
If an user come to this page with the url localhost:3000/
it should be redirected to localhost:3000/error
, but if the user come with a specific query param localhost:3000/?code=1234
the user must not be redirected.
The problem is when I test this component going to the URL without the code
param, I'm correctly redirect to the error page (localhost:3000/error
), but after this, if I enter the url localhost:3000/?code=1234
, I'm also redirect to the error page.
When I try this in an anonymous window, I'm correctly redirected when going to localhost:3000/?code=1234
after gone to localhost:3000/
(and then to the error page)
How can I stop this behaivour?
Upvotes: 2
Views: 5093
Reputation: 50338
Since you're using getServerSideProps
and have access to the query params there, you can redirect on the server-side directly and avoid having to even mount the Home
component.
export async function getServerSideProps(context) {
if (!context.query.code) {
return {
redirect: {
destination: '/error',
permanent: false
}
}
}
return {
props: { code: context.query.code }
}
}
Upvotes: 1
Reputation: 8091
I believe that your useEffect
code should run only once when the component is mounted in the browser.
useEffect(() => {
if(!props.code){
console.log('No code found');
router.push('/error');
}
},[]);
Or alternatively, you could redirect immediately inside getServerSideProps
export const getServerSideProps = async (context) => {
const { res } = context;
// if there is no code do the redirect
res.writeHead(301, { location: "https://google.com" } );
res.end();
}
Upvotes: 2