This repository demonstrates how to implement various common use cases related to user authentication and session management using React, Express, and Postgresql (via Sequelize).
The primary use cases that will be covered include:
- Signing in/Signing up and redirecting to a logged in screen
- Refreshing the page with user-specific elements post login
- Remaining signed in after page reload
- Logging out and redirecting to the home page
- Fetching data customized for the signed in user
- Redirecting to the home page when accessing a signed-in user only route
This section will discuss the architectural choices made during the creation of this repository. These include the choice between sessions/cookies vs jwt vs Auth0/Passport, and the pros and cons of each method.
Below are the user story-based milestones to start implementing in your application. Each milestone has a video walkthrough that explains how the code works, and how to bring it into your application.
In the milestones below, I'll assume that you already have a basic React and Express app (with Sequelize) set up that you'd like to add user authentication to. In this demo project, there is a React app at auth-demo-ui and an Express app at auth-demo-api.
In this milestone, we'll cover the basic scaffolding that you'll need in order to set up user registration and login. Read the basic steps below, and watch the video for more explanation.
React
- Install required packages in your React app. Open Terminal, change to your React folder, and run the command below.
npm install react react-dom react-router-dom
-
Look at the LoginForm and SignupForm components, and copy them into your project.
-
Look at the BrowserRouter in App.jsx and adapt to your project.
Express
- Install required packages in your Express app. Open Terminal, change to your Express folder, and run the command below.
npm install bcrypt connect-session-sequelize cors express express-session morgan pg pg-hstore sequelize
-
Look at routes/users.js, and copy that file into your project.
-
Look at server.js, and copy the sections related to cors, sessions, and adding the userRoutes.
React
- Open App.jsx, and look at the UserContext.
- Open components/Main/Main.jsx, and look at the line
useContext(UserContext)
.
React
- Open browser, and look at the cookies.
Express
- Open routes/users.js, and look at req.session. Open server.js, and look how POST /posts uses req.session