Issue short-lived access tokens and rotating opaque refresh tokens, hash stored refresh credentials, validate claims and algorithms, and revoke sessions safely.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
npm install jose argon2
openssl rand -base64 32
export JWT_SECRET='replace-with-generated-secret'
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
import { SignJWT, jwtVerify } from 'jose'; import { randomBytes, createHash } from 'node:crypto';
const key=new TextEncoder().encode(process.env.JWT_SECRET);
export const issueAccess=user=>new SignJWT({role:user.role}).setProtectedHeader({alg:'HS256'}).setSubject(String(user.id)).setIssuer('lapvn-api').setAudience('lapvn-web').setIssuedAt().setExpirationTime('10m').sign(key);
export const verifyAccess=token=>jwtVerify(token,key,{algorithms:['HS256'],issuer:'lapvn-api',audience:'lapvn-web'});
export function refreshCredential(){const raw=randomBytes(32).toString('base64url'); return {raw,hash:createHash('sha256').update(raw).digest('hex')};}
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
node -e "import('./auth.js').then(async m=>{const t=await m.issueAccess({id:1,role:'user'}); console.log(t); console.log((await m.verifyAccess(t)).payload)})"
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
JWT payloads are encoded, not encrypted. Never put passwords or secrets inside them. Store refresh tokens in Secure, HttpOnly, SameSite cookies for browser clients, rotate them on every use, detect replay, and revoke the complete token family after reuse.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.