Authentication in MERN Stack: Passport, JWT, Sessions, and Cookies
1. Passport.js
- A flexible Node.js middleware for authentication.
- Used in the backend (Node + Express) to verify credentials.
- Supports session-based and token-based (JWT) authentication.
- Common Strategies:
- passport-local For username/password login
- passport-jwt For JWT-based login
- passport-google-oauth20 For OAuth logins
2. Session-based Authentication
- User logs in server creates a session ID stores it on the server.
- Session ID is sent to the client in a cookie.
- On future requests, server matches the session ID authenticates the user.
- Tools: express-session + passport
- Pros: Secure and easy to revoke.
- Cons: Less scalable for distributed systems.
3. JWT (JSON Web Token)
- User logs in receives a signed token from the server.
- Token is stored on the client (localStorage or cookie).
- Future requests include the token in headers.
- Server verifies token for authentication.
- Stateless: No need to store anything on the server.
- Pros: Great for APIs, mobile apps.
- Cons: Token revocation is harder.
4. Cookies
- Small pieces of data stored on the clients browser.
- Store session IDs (for session-based auth) or JWTs (token-based).
- Use HTTP-only and Secure flags for better security.
Summary Table:
| Concept | Stored on | Type | Use with Passport? | Best For |
|-----------------|-----------|------------|---------------------|--------------------------|
| passport.js | | Library | Yes | All auth methods |
| Session-based | Server | Stateful | Yes | Traditional web apps |
| JWT | Client | Stateless | Yes (with strategy) | APIs, SPAs, mobile apps |
| Cookies | Client | Storage | Yes | Storing session or JWT |
Example Use Case:
- Backend: Node + Express + MongoDB
- Auth: passport-local + express-session or passport-jwt
- Frontend: React uses cookies or headers to send auth data to backend