Authenticated routes on MERN stack

(Niranjan) #1

I’m using the following stack -

  • React front end created from a create-react-app, includes react-router v4
  • Mongo + Express nodejs backend
  • express-session
  • passportjs
  • Proxied web requests from webpack dev server to my nodejs server (as mentioned in this article)

I have implemented a login + register form with passportjs + express-session on the backend (no redux). All pages in my web app can be be viewed only be logged in users - if they do not have a valid session, then they must be redirected to the login page.

Please help me understand the following -
(a) While rendering a page, how to check if the user’s session is valid and then proceed to render the page? I believe we can store authenticated states in state variable but on page refresh, how to check logged in status?
(b) In passport.authenticate() on the server, how to send login success/registration success back to the front end, and then let the front end handle the redirects (I’m using react-router).

I’m not interested in using any 3rd party auth services like Auth0 or Stormpath.

It would be helpful to have a boilerplate code that uses the same stack.