Reactjs: Show logged in or log in accordingly to session

Viewed 32

I am trying to get better in react and I would like to do it everything correctly which is why I am asking for your opinions and help.

I am building a project in NextJS and I have a layout component which contains components which are rendered multiple times such as header, footer etc.

I this header, I have a "Sign in" and "Sign out" button. I'd like it to only show one of them accordingly to your session status.

enter image description here

I use a sessionid which contains some more info in the database and this sessionid is stored in a httponly cookie.

enter image description here

It is stored in the database with data:

  • id
  • sessionid
  • userid
  • expires

Would you add or remove anything to this?


So my question is:

How would you check for a session and then render x accordingly? Would you just send an api call each request that checks the session or? Should I maybe use useContext and create a provider which can then send the session with the provider?

I'm quite lost on how to do it the best way so the flow is smooth as f*ck.

1 Answers

It depends how strict you want to be with it.

One option would be to simply check the existence of the cookie and adjust according to that. You can use js-cookie for that.

The better option, in my opinion, is to verify the cookie with your backend. You should set up an endpoint that simply verifies / parses the cookie and returns something like the user_id, or ismply a boolean indicating whether the user is logged in.

Given that you are using Next, you can add this call to your App's getInitialProps() like this:

  App.getInitialProps = async () => {

  let loggedIn;

  try {
    ({ data: {loggedIn} } = await axios.get('/api/v1/auth/checkCookie'));
  } catch (err) {
    console.log('Error checkingCookie', err.message );
  }

  return {
    loggedIn,
  }
}

Your loggedIn variable will then be available in the props of your App, like:

function App({currentUser}) {
if (currentUser) {
    return <div>Logged In</div>
} else {
    return <div>Logged Out</div>
}
}
Related