1. Introduction & use cases
A JSON Web Token (JWT) is a compact, signed string with three Base64URL parts: header, payload (claims such as user id and expiry) and signature. The server signs the token at login; afterwards the client sends it in the Authorization: Bearer … header and the server verifies the signature – no session lookup needed.
JWTs are signed, not encrypted: anyone can read the payload, so never put secrets in it. Keep access tokens short-lived and use refresh tokens to get new ones.
Where it is used
- Authentication for REST and GraphQL APIs
- Mobile apps and SPAs talking to an API
- Service-to-service calls
- ID tokens in OpenID Connect / OAuth 2.0 logins
2. Prerequisites
| You need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| A REST API | See the Express.js guide |
| HTTPS in production | Tokens must never travel over plain HTTP |
3. Local setup
1Install packages
jsonwebtokensigns/verifies tokens,bcrypthashes passwords,cookie-parserreads the refresh cookie.BASHmkdir jwt-auth && cd jwt-auth npm init -y && npm pkg set type=module npm install express jsonwebtoken bcrypt cookie-parser2Create strong secrets
Generate two random secrets (access and refresh) and put them in
.env.BASHnode -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
4. Create & run a project
1Register and login
Hash passwords with bcrypt; on login return a short-lived access token and set a long-lived refresh token in an httpOnly cookie.
server.jsimport express from 'express'; import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; import cookieParser from 'cookie-parser'; const app = express(); app.use(express.json(), cookieParser()); const users = new Map(); // use a database in real apps const { JWT_SECRET, JWT_REFRESH_SECRET } = process.env; const accessToken = (u) => jwt.sign({ sub: u.id, role: u.role }, JWT_SECRET, { expiresIn: '15m', algorithm: 'HS256' }); const refreshToken = (u) => jwt.sign({ sub: u.id }, JWT_REFRESH_SECRET, { expiresIn: '7d', algorithm: 'HS256' }); app.post('/auth/register', async (req, res) => { const { email, password } = req.body; if (!email || !password || password.length < 8) return res.status(400).json({ error: 'email and 8+ char password required' }); if (users.has(email)) return res.status(409).json({ error: 'already registered' }); users.set(email, { id: String(users.size + 1), email, role: 'user', hash: await bcrypt.hash(password, 12) }); res.status(201).json({ ok: true }); }); app.post('/auth/login', async (req, res) => { const u = users.get(req.body.email); if (!u || !(await bcrypt.compare(req.body.password ?? '', u.hash))) return res.status(401).json({ error: 'invalid credentials' }); res.cookie('refresh', refreshToken(u), { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', path: '/auth/refresh' }); res.json({ accessToken: accessToken(u) }); });2Protect routes with middleware
Always pass the allowed
algorithmswhen verifying.JSfunction auth(req, res, next) { const [type, token] = (req.headers.authorization ?? '').split(' '); if (type !== 'Bearer' || !token) return res.status(401).json({ error: 'missing token' }); try { req.user = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); next(); } catch { res.status(401).json({ error: 'invalid or expired token' }); } } app.get('/me', auth, (req, res) => res.json({ userId: req.user.sub, role: req.user.role }));3Refresh the access token
The browser sends the cookie automatically to
/auth/refresh.JSapp.post('/auth/refresh', (req, res) => { try { const { sub } = jwt.verify(req.cookies.refresh, JWT_REFRESH_SECRET, { algorithms: ['HS256'] }); const u = [...users.values()].find((x) => x.id === sub); if (!u) throw new Error(); res.json({ accessToken: accessToken(u) }); } catch { res.status(401).json({ error: 'login again' }); } }); app.listen(3000, () => console.log('Auth API on http://localhost:3000'));4Try it
Register, log in, then call the protected route with the token.
BASHnode --env-file=.env server.js curl -X POST localhost:3000/auth/register -H 'Content-Type: application/json' -d '{"email":"a@example.com","password":"secret123"}' TOKEN=$(curl -s -X POST localhost:3000/auth/login -H 'Content-Type: application/json' -d '{"email":"a@example.com","password":"secret123"}' | node -pe 'JSON.parse(require("fs").readFileSync(0)).accessToken') curl localhost:3000/me -H "Authorization: Bearer $TOKEN"
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Use long random secrets (64 bytes) and different secrets for access and refresh tokens. Rotating a secret logs everyone out – plan for it.
PORT=3000
JWT_SECRET=paste-64-random-bytes-hex
JWT_REFRESH_SECRET=paste-another-64-random-bytes-hex
NODE_ENV=developmentKey dependencies
| Package / tool | Used for |
|---|---|
jsonwebtoken (or jose) | Sign and verify JWTs |
bcrypt / argon2 | Password hashing |
cookie-parser | Read the httpOnly refresh cookie |
express-rate-limit | Slow down password guessing on /auth/login |
Folder structure
jwt-auth/
├── src/
│ ├── middleware/auth.js
│ ├── routes/auth.js # register, login, refresh, logout
│ └── server.js
└── .env # secretsEssential commands
| Command | What it does |
|---|---|
node -e "…randomBytes(64)…" | Generate a secret |
curl -H "Authorization: Bearer TOKEN" URL | Call a protected route |
jwt.io debugger | Decode a token to inspect claims (never paste production tokens into third-party sites) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| HTTPS everywhere | Tokens are bearer credentials |
| Secrets | Stored in the server/secret manager, not in Git |
| Rate limiting | On login, register and refresh |
| Clock sync | NTP on servers so exp checks are correct |
Deployment steps
1Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP2Install Node.js on the server
Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/jwt-auth cd /var/www/jwt-auth npm ci --omit=dev nano .env # production values4Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo npm install -g pm2 pm2 start server.js --name jwt-auth --node-args="--env-file=.env" pm2 startup # run the command it prints pm2 save pm2 logs jwt-auth # live logs pm2 restart jwt-auth # after each deploy5Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Open only the ports you need
Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status8Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com9Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run10Production hardening
Trust the proxy (for secure cookies and rate limiting), limit login attempts and keep tokens out of logs.
JSapp.set('trust proxy', 1); import rateLimit from 'express-rate-limit'; app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, limit: 20 }));
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
JsonWebTokenError: invalid signature
The token was signed with a different secret (e.g. env not loaded or different between servers). Use the same secret on all instances.
TokenExpiredError: jwt expired
Expected after 15 minutes. The client should call /auth/refresh and retry; if that fails, log in again.
Refresh cookie is not sent
Cookie path, sameSite, secure and CORS credentials must match. Cross-site front-ends need sameSite: 'none' + secure and credentials: 'include'.
Users stay logged in after a password change
JWTs cannot be revoked by default. Keep access tokens short and store refresh tokens (or a token version) server-side so you can revoke them.
Storing tokens in localStorage got stolen by XSS
Prefer httpOnly cookies for refresh tokens, keep access tokens in memory, and fix XSS with output escaping and a Content-Security-Policy.
Best practices
- Short access tokens (5–15 min), rotating refresh tokens.
- Always specify allowed algorithms when verifying.
- Do not put personal or secret data in the payload.
- Hash passwords with bcrypt/argon2, never store them plain.
- Consider a managed identity provider (OAuth 2.0/OIDC) for larger apps.