I am working on Reactjs and using nextjs framework, I am working on "Login Logout" module and i just want that if user already logged in ( email set in cookie) then he should redirect to "dashboard" page,How can i do this ? I tried with following code but not working for me, giving me error ",Here is my current code
cookies returned from getServerSideProps Reason: undefined cannot be serialized as JSON
export async function getServerSideProps(context: { req: { headers: { cookies: any; }; }; }) {
const cookies = context.req.headers.cookies;
if (cookies && cookies.email) {
// email is present in cookies, so redirect to /dashboard
return {
redirect: {
destination: "/dashboard",
statusCode: 302, // temporary redirect
},
props: {},
};
}
return {
props: {
cookies,
},
};
}
CodePudding user response:
When returning props.cookies
from getServerSideProps
, you are potentially returning the cookies as undefined
. Use ''
as the default value if missing.
You can do this:
return {
props: {
cookies: cookies || '',
},
};
CodePudding user response:
You need to parse the cookies and you can get the cookies on the request you don't need the header
const cookies = JSON.parse(context.req.cookies);
if(cookies.email !== undefined)...