I'm using NextJS for my frontend and NodeJS(Express) for the back. I tried using the getServerSideProps
to check and pre-render whether user is authenticated or not but it doesn't work. I tried adding credentials: 'include'
but it didn't work either
export async function getServerSideProps(context) {
const response = await fetch('http://localhost:3000/api/auth/user', {
method: 'GET',
credentials: 'include',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
});
if (response.status === 401) {
return {
props: { data: null },
};
}
const result = await response.json();
return {
props: {
data: result,
},
};
}
Error:
- url: 'http://localhost:3000/api/auth/user',
- status: 401,
- statusText: 'Unauthorized',
- headers: Headers { [Symbol(map)]: [Object: null prototype] },
- counter: 0
I know client-side using the useEffect()
might do the trick but I don't want to see the state change once it's done rendering.
For example: in my navbar, if the user is authenticated it should display the username
, if not then just 'login'. But every time I refresh it will display 'login' first then after a few seconds it will change into username
(assuming the user was logged in).
Is there any other way?
Thanks!