Let's walk through authentication and authorization in a MERN stack application (MongoDB, Express.js, React, Node.js). These are critical for securing your app and controlling user access.
π Authentication vs. Authorization
-
Authentication: Proves who the user is (e.g., logging in).
-
Authorization: Controls what that authenticated user can do (e.g., admin vs. regular user access).
⚙️ How It Works in the MERN Stack
1. React (Frontend)
-
Users enter credentials via a login form.
-
On submit, React sends a POST request to an Express.js backend.
-
If the credentials are valid, the server returns a JWT (JSON Web Token).
-
The JWT is stored client-side (e.g.,
localStorage
,sessionStorage
, or httpOnly cookies for better security). -
For all protected routes, React sends this JWT in the
Authorization
header of future requests.
2. Express.js + Node.js (Backend)
Login Endpoint
-
Backend receives login credentials.
-
Looks up the user in MongoDB.
-
Compares hashed passwords using
bcrypt
. -
If valid, creates a JWT using
jsonwebtoken
and sends it back.
Middleware to Protect Routes
-
You create a middleware function to validate JWTs and attach user data to
req
.
Protected Route
3. MongoDB (Database)
You store user data like this:
π Authorization (Role-Based Access)
Add another middleware to check roles:
✅ Best Practices
-
Always hash passwords before saving (
bcrypt
is the go-to). -
Use httpOnly cookies for token storage if security is a concern (helps prevent XSS).
-
Set JWT expiration times and rotate/refresh tokens if needed.
-
Sanitize inputs to prevent injection attacks.
-
Protect all sensitive routes with both authentication and authorization.