Login and Signup System
Part of the MERN Stack Roadmap
In short
Authentication is in almost every MERN job task and interview. This project builds it properly once: hashed passwords, short access tokens, refresh tokens in cookies, protected pages, roles and secure headers. You will reuse it in every app after this.
Build complete authentication for a MERN app: signup, login, logout, refresh tokens in httpOnly cookies, protected pages, roles and secure headers.

Think of it like this
The office ID card system
On day one at an office in Bengaluru, HR checks your documents and issues an ID card (signup). Every morning the gate scans the card (access token). The card needs renewing now and then at the HR desk, which keeps a long-term record (refresh token). Leaving the company means the card is cancelled (logout).
Watch it happen
Login, then a silent refresh
POST /auth/login
1/6Email and password over HTTPS.
The big ideas
What you need to know
Signup
Validate input, check the email is unused, hash with bcrypt in a pre-save hook, and never return the hash.
Two tokens
A short access token for every request, a longer refresh token only for /api/auth/refresh, stored hashed in MongoDB so you can revoke it.
Rotate on refresh
Each refresh issues a new refresh token and invalidates the old one. Reuse of an old one is a sign of theft, so log the user out everywhere.
Harden the edges
Helmet for headers, rate limiting on /login and /signup, the same error for wrong email or password, and CORS limited to your frontend.
How it works
Build order
- 1
User model
name, email (unique, lowercase), password (select: false), role, refreshTokenHash.
- 2
Auth routes
signup, login, logout, refresh and me, with zod validation.
- 3
Middleware
requireAuth reads the cookie, requireRole("admin") checks the role.
- 4
React side
AuthContext, an Axios instance with withCredentials and a 401 interceptor, ProtectedRoute.
- 5
Security pass
helmet(), express-rate-limit on auth routes, secure cookies in production, tests with Supertest.
See it in code
Walk through the code
1// client/src/api/http.js2import axios from "axios";3 4export const http = axios.create({ baseURL: "/api", withCredentials: true });5 6let refreshing = null;7 8http.interceptors.response.use(9 (res) => res,10 async (error) => {11 const original = error.config;12 const isAuthCall = original.url.startsWith("/auth/");13 if (error.response?.status !== 401 || original._retry || isAuthCall) {14 return Promise.reject(error);15 }16 original._retry = true;17 try {18 refreshing = refreshing || http.post("/auth/refresh");19 await refreshing;20 return http(original);21 } catch (refreshError) {22 window.location.assign("/login");23 return Promise.reject(refreshError);24 } finally {25 refreshing = null;26 }27 }28);1/5withCredentials makes Axios send cookies. baseURL keeps every call relative to /api.
One Axios instance that silently refreshes an expired session and retries the request.
Save yourself the pain
Common mistakes
Oops
Making the access token valid for 30 days to avoid building refresh.
Do this instead
Keep access tokens short, such as 15 minutes, and use a refresh token you can revoke on the server.
Oops
Telling users "No account with this email" on login.
Do this instead
Use one message for both cases, such as "Wrong email or password", so attackers cannot discover registered emails.
Oops
Retrying the refresh request itself when it returns 401.
Do this instead
Skip the interceptor for /auth/ routes, or you create an infinite loop.
Your mission
Ship complete auth
Quick check
Why store a hash of the refresh token in MongoDB instead of only in the cookie?
Go deeper
- 1Include forgot-password with an emailed reset link that expires.
- 2Rate limit login attempts and validate every input.
- 3Write down the full auth flow in your README with a diagram.
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.