Node.js Authentication
Authentication in Node.js applications verifies user identity before granting access to protected resources or routes.
Session-Based Authentication
Session-based authentication stores user state on the server, using cookies to identify returning users across requests.
Token-Based Authentication
Token-based approaches, such as JWTs, allow stateless authentication, making them well-suited for APIs and distributed systems.
Securing Routes
Middleware is commonly used to protect routes, checking for valid sessions or tokens before allowing access to sensitive endpoints.
How a Token Login Works Step by Step
- The user signs up. The server hashes the password and stores only the hash.
- At login, the server finds the user and compares the entered password with the stored hash.
- If they match, the server signs a JSON Web Token containing the user ID and an expiry time.
- The client sends this token with later requests, usually in an
Authorization: Bearerheader or an HTTP-only cookie. - Middleware verifies the signature and expiry before the protected route runs.
Express Example With bcrypt and JWT
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const User = require("./models/User"); // Mongoose model
const app = express();
app.use(express.json());
const SECRET = process.env.JWT_SECRET; // never hard-code secrets
app.post("/api/register", async (req, res) => {
const { email, password } = req.body;
const passwordHash = await bcrypt.hash(password, 12);
await User.create({ email, passwordHash });
res.status(201).json({ message: "Registered" });
});
app.post("/api/login", async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
const ok = user && (await bcrypt.compare(password, user.passwordHash));
if (!ok) return res.status(401).json({ message: "Invalid email or password" });
const token = jwt.sign({ sub: user.id }, SECRET, { expiresIn: "15m" });
res.json({ token });
});
function requireAuth(req, res, next) {
const header = req.headers.authorization || "";
const token = header.startsWith("Bearer ") ? header.slice(7) : null;
if (!token) return res.status(401).json({ message: "Login required" });
try {
req.user = jwt.verify(token, SECRET);
next();
} catch {
res.status(401).json({ message: "Invalid or expired token" });
}
}
app.get("/api/profile", requireAuth, async (req, res) => {
const user = await User.findById(req.user.sub).select("-passwordHash");
res.json(user);
});
Notice that the login error message is the same whether the email or the password is wrong. This avoids telling an outsider which emails are registered.
A few other details in this code are worth copying. The secret comes from an environment variable, so it never lands in Git. The cost factor of 12 passed to bcrypt.hash makes each hash deliberately slow to compute, which hurts attackers far more than real users. The profile query uses select("-passwordHash") so the hash is never sent back to the browser. Finally, the token holds only the user ID in the standard sub claim; never put passwords or sensitive personal data in a JWT, because its payload is only encoded, not encrypted.
Sessions or JWT: Picking One
| Need | Better fit |
|---|---|
| Classic server-rendered site on one domain | Sessions with express-session and a store such as Redis or MongoDB |
| Mobile app or API used by many clients | Short-lived JWT access tokens |
| Instant logout on all devices | Sessions, or JWT with a server-side revocation list |
Security Checklist
- Hash passwords with bcrypt or Argon2; never store plain or reversibly encrypted passwords.
- Keep the JWT secret in environment variables or a secrets manager, and make it long and random.
- Use short expiry for access tokens and a refresh token stored in an
httpOnly,secure,sameSitecookie. - Rate-limit the login route, for example with
express-rate-limit, to slow down password guessing. - Validate input with a library such as Joi or Zod before it reaches the database.
- Serve everything over HTTPS and add security headers with
helmet. - Check authorisation too: a logged-in user should only reach their own records.
- Log failed logins and unusual token errors so suspicious activity can be spotted early.