0

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!

Ronchi
  • 1
  • 1
  • What does your `/api/auth/user` endpoint look like? – juliomalves Aug 10 '21 at 06:12
  • @juliomalves NodeJS App: `router.get('/auth/user', middleware.isAuthenticated, (req, res) => { res.status(200).json(req.user); })` – Ronchi Aug 10 '21 at 09:47
  • Need to provide more details, what's in `middleware.isAuthenticated`? Please add the code to your question. – juliomalves Aug 10 '21 at 10:18
  • @juliomalves `exports.isAuthenticated = (req, res, next) => { if (!req.user) { return res.status(401).send('You must login first!'); } next(); };` It's just a checker whether or not a user is authenticated – Ronchi Aug 10 '21 at 11:15
  • Exactly, which means that check is not passing, as it's returning a `401` response. Where does `req.user` come from? – juliomalves Aug 10 '21 at 11:20

0 Answers0