const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;
const ALGORITHM = 'HS256';
const ACCESS_TTL = '15m';
class AuthError extends Error {
constructor(message, status = 401) {
super(message);
this.name = 'AuthError';
this.status = status;
}
}
function signAccessToken(user) {
return jwt.sign(
{ role: user.role },
SECRET,
{ subject: String(user.id), algorithm: ALGORITHM, expiresIn: ACCESS_TTL }
);
}
function verifyAccessToken(token) {
try {
return jwt.verify(token, SECRET, { algorithms: [ALGORITHM] });
} catch (err) {
if (err.name === 'TokenExpiredError') {
throw new AuthError('Access token expired', 401);
}
throw new AuthError('Invalid access token', 401);
}
}
module.exports = { signAccessToken, verifyAccessToken, AuthError };
const { verifyAccessToken, AuthError } = require('./tokenService');
function extractBearer(header) {
if (typeof header !== 'string') return null;
const parts = header.split(' ');
if (parts.length !== 2 || parts[0] !== 'Bearer') return null;
return parts[1];
}
function requireAuth(req, res, next) {
const token = extractBearer(req.headers.authorization);
if (!token) {
return next(new AuthError('Missing bearer token', 401));
}
try {
const payload = verifyAccessToken(token);
req.user = { id: payload.sub, role: payload.role };
return next();
} catch (err) {
return next(err);
}
}
function requireRole(role) {
return function (req, res, next) {
if (!req.user) {
return next(new AuthError('Not authenticated', 401));
}
if (req.user.role !== role) {
return next(new AuthError('Insufficient privileges', 403));
}
return next();
};
}
module.exports = { requireAuth, requireRole };
const express = require('express');
const { signAccessToken, AuthError } = require('./tokenService');
const { requireAuth, requireRole } = require('./authenticate');
const { findByCredentials } = require('./userStore');
const router = express.Router();
router.post('/login', async (req, res, next) => {
try {
const { email, password } = req.body;
const user = await findByCredentials(email, password);
if (!user) throw new AuthError('Invalid email or password', 401);
res.json({ accessToken: signAccessToken(user) });
} catch (err) {
next(err);
}
});
// Every route below this line requires a valid token.
router.use(requireAuth);
router.get('/me', (req, res) => {
res.json({ id: req.user.id, role: req.user.role });
});
router.delete('/users/:id', requireRole('admin'), (req, res) => {
res.status(204).end();
});
router.use((err, req, res, next) => {
if (err.name === 'AuthError') {
return res.status(err.status).json({ error: err.message });
}
next(err);
});
module.exports = router;
This snippet shows how a stateless authentication layer is wired into an Express application using JSON Web Tokens. Rather than looking up a session on every request, the server trusts a signed token supplied by the client, verifies its signature, and attaches the decoded identity to req.user so downstream handlers can act on it without repeating the verification logic.
The token service centralises everything related to signing and verifying. signAccessToken embeds a sub claim plus a role, sets a short expiry, and pins the algorithm to HS256 so a caller cannot downgrade to none. verifyAccessToken mirrors those constraints by passing algorithms explicitly to jwt.verify, which is a common pitfall: without it, a forged token declaring alg: none could pass. Errors from the jsonwebtoken library are normalised into an AuthError carrying an HTTP status, so the middleware never has to branch on library-specific error classes.
In authenticate middleware, the requireAuth function extracts the bearer token from the Authorization header, rejecting anything that does not match the Bearer <token> shape before touching the crypto. On success it constructs a lean req.user object containing only the id and role — deliberately not the full decoded payload — which keeps handlers from depending on incidental claims. The companion requireRole is a higher-order guard: it returns a middleware closure so routes can declare requireRole('admin') inline, and it assumes requireAuth already ran, returning 401 versus 403 to distinguish "not logged in" from "logged in but not allowed".
The routes tab ties it together. Public routes like POST /login issue a token, while router.use(requireAuth) applies authentication to every route declared after it, so /me and the admin route are protected without per-route repetition. This ordering matters: middleware placement is how Express scopes protection.
The trade-off of this stateless design is that tokens cannot be revoked before they expire, which is why the expiry is kept short and why a refresh-token flow usually accompanies it. It suits APIs where horizontal scaling makes server-side sessions awkward.
Related snips
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
import axios, { AxiosError } from 'axios'
import { v4 as uuidv4 } from 'uuid'
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api/v1',
timeout: 15000,
Axios API client with interceptors
Share this code
Here's the card — post it anywhere.