In this tutorial, we will learn how to build a full stack React.js + Express Authentication & Authorization example. The back-end server uses Node.js Express with jsonwebtoken for JWT authentication and Sequelize for interacting with MySQL database. The front-end will be created with React, React Router, Axios. We’ll also use Bootstrap and perform Form validation.
Related Posts:
– React + Node.js + Express + MySQL example: Build a CRUD App
– Node.js + MongoDB: User Authentication & Authorization with JWT
– Node.js + PostgreSQL: User Authentication & Authorization with JWT
Run both projects in one place:
How to integrate React with Node.js Express on same Server/Port
Dockerize:
– Docker Compose: React, Node.js, MySQL example
Contents
JWT (JSON Web Token)
Comparing with Session-based Authentication that need to store Session on Cookie, the big advantage of Token-based Authentication is that we store the JSON Web Token (JWT) on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.
There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: header.payload.signature
.
The Client typically attaches JWT in x-access-token header:
x-access-token: [header].[payload].[signature]
For more details, you can visit:
In-depth Introduction to JWT-JSON Web Token
React Express Authentication example
It will be a full stack, with Node.js Express for back-end and React.js for front-end. The access is verified by JWT Authentication.
- User can signup new account, login with username & password.
- Authorization by the role of the User (admin, moderator, user)
Let’s see the screenshots of our system:
– Anyone can access a public page before logging in:
– A new User can signup:
– Form Signup validation will be like this:
– After signup is successful, User can login:
– After login, App directs the User to Profile page:
– UI for Moderator login (the navigation bar will change by authorities):
– If a User who doesn’t have Admin role tries to access Admin/Moderator Board page:
Demo Video
This is full React + Node.js Express JWT Authentication & Authorization demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User):
Flow for User Registration and User Login
The diagram shows flow of User Registration, User Login and Authorization process.
There are 2 endpoints for authentication:
api/auth/signup
for User Registrationapi/auth/signin
for User Login
If Client wants to send request to protected data/endpoints, it add legal JWT to HTTP x-access-token Header.
Back-end with Node.js Express & Sequelize
Overview
Our Node.js Express Application can be summarized in the diagram below:
Via Express routes, HTTP request that matches a route will be checked by CORS Middleware before coming to Security layer.
Security layer includes:
- JWT Authentication Middleware: verify SignUp, verify token
- Authorization Middleware: check User’s roles with record in database
If these middlewares throw any error, a message will be sent as HTTP response.
Controllers interact with MySQL Database via Sequelize and send HTTP response (token, user information, data based on roles…) to client.
Technology
- Express 4.18.2
- bcryptjs 2.4.3
- jsonwebtoken 9.0.0
- Sequelize 6.32.1
- MySQL
Project Structure
This is directory structure for our Node.js Express application:
– config
- configure MySQL database & Sequelize
- configure Auth Key
– routes
- auth.routes.js: POST signup & signin
- user.routes.js: GET public & protected resources
– middlewares
- verifySignUp.js: check duplicate Username or Email
- authJwt.js: verify Token, check User roles in database
– controllers
- auth.controller.js: handle signup & signin actions
- user.controller.js: return public & protected content
– models for Sequelize Models
- user.model.js
- role.model.js
– server.js: import and initialize neccesary modules and routes, listen for connections.
Implementation
You can find step by step to implement this Node.js App in the post:
Node.js – JWT Authentication & Authorization with JSONWebToken example
For MongoDB database:
Node.js + MongoDB: User Authentication & Authorization with JWT
Or PostgreSQL database:
Node.js + PostgreSQL: User Authentication & Authorization with JWT
Front-end with React, React Router
Overview
Let’s look at the diagram below.
– The App
component is a container with React Router (BrowserRouter
). Basing on the state, the navbar can display its items.
– Login
& Register
components have form for data submission (with support of react-validation
library). They call methods from auth.service
to make login/register request.
– auth.service
methods use axios
to make HTTP requests. Its also store or get JWT from Browser Local Storage inside these methods.
– Home
component is public for all visitor.
– Profile
component displays user information after the login action is successful.
– BoardUser
, BoardModerator
, BoardAdmin
components will be displayed by state user.roles
. In these components, we use user.service
to access protected resources from Web API.
– user.service
uses auth-header()
helper function to add JWT to HTTP header. auth-header()
returns an object containing the JWT of the currently logged in user from Local Storage.
If you want to use HttpOnly Cookie for storing JWT, please visit:
React.js Login & Registration example – JWT & HttpOnly Cookie
Technology
We’re gonna use these modules:
- React 18/17
- react-router-dom 6
- axios 0.27.2
- react-validation 3.0.7
- Bootstrap 4
- validator 13.7.0
Project Structure
This is folders & files structure for this React application:
With the explanation in diagram above, you can understand the project structure easily.
Implementation
You can find step by step to implement this React App in the post:
React JWT Authentication (without Redux) example
Typescript version: React Typescript JWT Authentication (without Redux) example
Using Hooks:
React Hooks: JWT Authentication (without Redux) example
Or Redux:
React Redux: JWT Authentication & Authorization example
Or Hooks + Redux:
React Hooks + Redux: JWT Authentication & Authorization example
Source Code
The complete source code for this tutorial can be found at React + Express Login example Github.
Conclusion
Now we have an overview of React & Express Authentication example along with flow for login and registration.
We also take a look at Node.js Express server architecture for JWT Authentication using jsonwebtoken & Sequelize, as well as React.js project structure for building a front-end app working with JWT.
Next tutorials will show you more details about how to implement this interesting system:
– Back-end
– Front-end
This React Client also works well with back-end in the post:
– Node.js + MongoDB: User Authentication & Authorization with JWT
– Node.js + PostgreSQL: User Authentication & Authorization with JWT
You will want to know how to run both projects in one place:
How to integrate React with Node.js Express on same Server/Port
This Node.js server also works well with front-end in the post:
– React Typescript: JWT Authentication (without Redux) example
– React Redux: JWT Authentication & Authorization example
– React Hooks: JWT Authentication (without Redux) example
– React Hooks + Redux: JWT Authentication & Authorization example
Happy learning, see you again!
Further Reading
- https://www.npmjs.com/package/jsonwebtoken
- React Component
- In-depth Introduction to JWT-JSON Web Token
Dockerize:
– Docker Compose: React, Node.js, MySQL example
Great Tutorial.
Could you plz share Repo Link.
Hi, in the backend and frontend tutorials I mentioned above.
Saved as a favorite tutorial!
Man the source code would really be beneficial. I got lost in clicking link after link.
Hi, it is because we have several React front-ends that all work with all Nodejs back-ends.
People can choose appropriate code they need basing on the tutorials.
good explanation and easy to understand. could I get zip file of above project.Thank you
Hi, you can get Github source code in the tutorials at Conclusion section 🙂
Thanks!
how can i restrict Access to login page if user is already logged ?
Still reading, but based on how comprehensive the tutorial is, with all the different options… I must say thank you!
Thanks for this React tutorial!
If some one needs to be updated with most up-to-date Javascript technologies after
that he must be go to see this site and be up to date all the time.
Hi, I do believe this is an excellent fullstack tutorial. You will be rich and continue to guide others.
Thanks! It works well!
can you please tell me how do I use jwt authentication with your tutorial app?
Hi, you can look at the way we implement the process:
user.routes
=>user.controller
=>user.model
.so i have to add this user.routes ,user.controller ,user.modul in tutorial app?
and one more question .. when after I login how to transfer on the tutorial app page
It Works very well.
the react part is very clear and well detailed. i ll change it to use react Hooks. but i learn something new Today in the backend part,”SEQUELIZE”.
in my projects , i often use knex+objection , but today , i learn how to use Sequelize.
Great Tutorial!!!
THANK YOU so Much.
Can you add the social login option?
Thanks
U don’t post the project? github?
Hi, you can find source code for back-end and front-end in the embedded tutorials (Conclusion section).
Hello – your node, express, jwt, mongo, and react tutorials work great. However, when I push the app to Heroku, I get a network error when I try to login or create an account. Any suggestions?
Hi, please take a look at the CORS configuration 🙂
I personally find this article to be perfect. The system architecture overview is an excellent presentation for this.
It would be really helpful if you could provide the source code.. In the conclusion section of article, all i see is the links to other articles.
Hi, because each tutorials has a different explanation and code from others, for example: React vs React Redux. So I think that user should read the article before getting the source code.