API & Authentication

JWT Authentication Setup & Deployment Guide

Stateless login for APIs – hash passwords, issue short-lived access tokens and refresh tokens, protect routes and run it safely in production.

Updated Official documentation ↗

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 needVersion / notes
Node.jsCurrent LTS release
A REST APISee the Express.js guide
HTTPS in productionTokens must never travel over plain HTTP

3. Local setup

  1. 1Install packages

    jsonwebtoken signs/verifies tokens, bcrypt hashes passwords, cookie-parser reads the refresh cookie.

    BASH
    mkdir jwt-auth && cd jwt-auth
    npm init -y && npm pkg set type=module
    npm install express jsonwebtoken bcrypt cookie-parser
  2. 2Create strong secrets

    Generate two random secrets (access and refresh) and put them in .env.

    BASH
    node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

4. Create & run a project

  1. 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.js
    import 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) });
    });
  2. 2Protect routes with middleware

    Always pass the allowed algorithms when verifying.

    JS
    function 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 }));
  3. 3Refresh the access token

    The browser sends the cookie automatically to /auth/refresh.

    JS
    app.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'));
  4. 4Try it

    Register, log in, then call the protected route with the token.

    BASH
    node --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.

.env
PORT=3000
JWT_SECRET=paste-64-random-bytes-hex
JWT_REFRESH_SECRET=paste-another-64-random-bytes-hex
NODE_ENV=development

Key dependencies

Package / toolUsed for
jsonwebtoken (or jose)Sign and verify JWTs
bcrypt / argon2Password hashing
cookie-parserRead the httpOnly refresh cookie
express-rate-limitSlow down password guessing on /auth/login

Folder structure

project structure
jwt-auth/
├── src/
│   ├── middleware/auth.js
│   ├── routes/auth.js     # register, login, refresh, logout
│   └── server.js
└── .env                   # secrets

Essential commands

CommandWhat it does
node -e "…randomBytes(64)…"Generate a secret
curl -H "Authorization: Bearer TOKEN" URLCall a protected route
jwt.io debuggerDecode a token to inspect claims (never paste production tokens into third-party sites)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
HTTPS everywhereTokens are bearer credentials
SecretsStored in the server/secret manager, not in Git
Rate limitingOn login, register and refresh
Clock syncNTP on servers so exp checks are correct

Deployment steps

  1. 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.

    BASH
    ssh 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_IP
  2. 2Install 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.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/jwt-auth
    cd /var/www/jwt-auth
    npm ci --omit=dev
    nano .env   # production values
  4. 4Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo 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 deploy
  5. 5Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        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";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Open 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.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or 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.com
  9. 9Add 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.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  10. 10Production hardening

    Trust the proxy (for secure cookies and rate limiting), limit login attempts and keep tokens out of logs.

    JS
    app.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.

terminal$ curl -X POST localhost:3000/auth/register -d '{...}'{"ok":true}$ curl localhost:3000/me -H "Authorization: Bearer eyJhbGciOi..."{"userId":"1","role":"user"}$ curl localhost:3000/me{"error":"missing token"}
Figure 1: terminal output of the sample JWT Authentication project (section 4).
1Login (bcrypt)2Sign access +refresh3Client sendsBearer4verify() on eachrequest5HTTPS + rotation
Figure 2: production deployment flow (section 6).
jwt-auth/├── src/│ ├── middleware/auth.js│ ├── routes/auth.js # register, login, refresh, logout│ └── server.js└── .env # secrets
Figure 3: project folder structure (section 5).

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.