unkey
  • BlogRead product updates and insights
  • Case studiesPractical results from real deployments
  • ChangelogTrack what shipped, improved, and fixed
  • GlossaryClear definitions for API terms
PricingDocs
Discord
LoginSign Up
  • BlogRead product updates and insights
  • Case studiesPractical results from real deployments
  • ChangelogTrack what shipped, improved, and fixed
  • GlossaryClear definitions for API terms
PricingDocsDiscord
LoginSign Up
  1. Glossary
  2. /JWT

What a JWT Is

Explore with AI
Open in ChatGPTOpen in ClaudeOpen in Perplexity

TL;DR

A JSON Web Token (JWT) is a compact string made of a header, a payload, and a signature. Sign it on the server, send it over HTTPS, and verify the signature and claims before trusting it.

Header

algtyp

Payload

subexpissaud

Signature

HMACRSAECDSA

A JSON Web Token (JWT) is a compact, URL-safe way to carry claims between two parties. This free tutorial shows how to use a JWT for API authentication: how the three parts fit together, how to sign a token, how to verify it, and the mistakes that make tokens easy to forge.

The examples use HMAC-SHA256 (HS256) and Node's built-in crypto module so you can learn JWT without a framework. A production service should call a maintained JWT library, then apply the same checks shown here.

Token structure

A JWT is three base64url segments separated by periods: header, payload, and signature. Base64url is encoding, not encryption. Anyone who has the token can read the header and the payload. The signature is what makes those claims trustworthy.

Header. Names the media type and the signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

HS256 means HMAC-SHA256 with a shared secret. RS256 and ES256 use a private key to sign and a public key to verify. Choose the algorithm in server code. Do not read alg from an untrusted token and then follow it.

Payload. A JSON object of claims. Registered names stay short so the token stays small:

  • iss is the issuer.
  • sub is the subject, usually a stable user or client id.
  • aud is the audience this token was issued for.
  • exp is the expiration time, in seconds since the Unix epoch.
  • nbf is the time before which the token is not valid.
  • iat is the time the token was issued.
  • jti is a unique id for this token.
{
  "iss": "https://api.example.com",
  "sub": "user_123",
  "aud": "https://api.example.com",
  "iat": 1730000000,
  "exp": 1730000900
}

Put only what the recipient needs. The token is sent on every request, and its contents are readable.

Signature. Covers the encoded header, a period, and the encoded payload. For HS256, the server computes HMAC-SHA256 with its secret and appends the base64url digest. If either earlier segment changes, verification fails.

Signing a JWT

Signing creates the token. Use a secret with at least 256 bits of randomness for HS256, and keep that secret on the server. JWT_SECRET in this example must be set in the environment. Do not commit a real secret.

import { createHmac } from 'node:crypto';

const secret = process.env.JWT_SECRET;

function base64url(value) {
  return Buffer.from(value).toString('base64url');
}

function signJwt(payload) {
  if (!secret) {
    throw new Error('JWT_SECRET is not set');
  }

  const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
  const body = base64url(JSON.stringify(payload));
  const data = `${header}.${body}`;
  const signature = createHmac('sha256', secret).update(data).digest('base64url');

  return `${data}.${signature}`;
}

const now = Math.floor(Date.now() / 1000);

const token = signJwt({
  iss: 'https://api.example.com',
  sub: 'user_123',
  aud: 'https://api.example.com',
  iat: now,
  exp: now + 15 * 60,
});

Fifteen minutes is a reasonable access-token lifetime when you cannot revoke the token early. The return value is the encoded header, the encoded payload, and the signature, joined by periods.

Verifying a JWT

Verification is the step that makes a token safe to trust. Recompute the signature with the key and algorithm you expect, compare it, and only then read the claims.

import { createHmac, timingSafeEqual } from 'node:crypto';

const secret = process.env.JWT_SECRET;

function verifyJwt(token, expected) {
  if (!secret) {
    throw new Error('JWT_SECRET is not set');
  }

  const parts = token.split('.');
  if (parts.length !== 3) {
    throw new Error('Malformed token');
  }

  const [headerPart, bodyPart, signature] = parts;
  const data = `${headerPart}.${bodyPart}`;
  const expectedSignature = createHmac('sha256', secret).update(data).digest('base64url');
  const actualBuffer = Buffer.from(signature);
  const expectedBuffer = Buffer.from(expectedSignature);

  if (
    actualBuffer.length !== expectedBuffer.length ||
    !timingSafeEqual(actualBuffer, expectedBuffer)
  ) {
    throw new Error('Invalid signature');
  }

  const header = JSON.parse(Buffer.from(headerPart, 'base64url').toString('utf8'));
  if (header.alg !== 'HS256') {
    throw new Error('Unexpected algorithm');
  }

  const payload = JSON.parse(Buffer.from(bodyPart, 'base64url').toString('utf8'));
  const now = Math.floor(Date.now() / 1000);

  if (typeof payload.exp !== 'number' || now >= payload.exp) {
    throw new Error('Token expired');
  }

  if (typeof payload.nbf === 'number' && now < payload.nbf) {
    throw new Error('Token is not active yet');
  }

  if (payload.iss !== expected.issuer || payload.aud !== expected.audience) {
    throw new Error('Unexpected issuer or audience');
  }

  return payload;
}

This example expects aud to be a string. The spec also allows an array of audiences. Accept the token only when your service is one of those values.

timingSafeEqual throws when the buffer lengths differ, so compare the lengths first. A normal string comparison can leak information through timing.

Call it with the issuer and audience you intended when you signed the token:

const claims = verifyJwt(token, {
  issuer: 'https://api.example.com',
  audience: 'https://api.example.com',
});

claims.sub is the caller. Use it only after verifyJwt returns.

How to use a JWT

  1. The client authenticates over HTTPS, for example with a password or another factor.
  2. The issuer builds a small set of claims, including sub, iss, aud, iat, and a short exp.
  3. The issuer signs those claims. Use a shared secret for HS256 when the same service signs and verifies. Use a private key for RS256 or ES256 when many services verify and only the issuer should create tokens.
  4. The issuer returns the token.
  5. The client sends it on later requests in the Authorization header.
  6. The API verifies the signature with the pinned algorithm, then checks exp, nbf, iss, and aud.
  7. Only after those checks pass does the API treat sub as the caller.
  8. When the token expires, the client authenticates again, or exchanges a separate refresh credential for a new access token.
POST /login HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "email": "ada@example.com",
  "password": "correct-horse-battery-staple"
}
HTTP/1.1 200 OK
Content-Type: application/json

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.signature"
}
GET /orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.signature

The password above is a placeholder. Send it only on the login request, over TLS, and do not copy it into the token.

In a browser, keep the token in memory, or send it in a cookie marked HttpOnly, Secure, and SameSite. localStorage is readable by any script on the page, so one cross-site scripting bug leaks every token stored there.

A signed JWT stays valid until exp. There is no logout switch inside the signature. Keep access tokens short, often a few minutes. If you must revoke one token early, give it a jti and keep a revocation list that every verifier checks.

Common mistakes

  • Treating the payload as private. Base64url is reversible. JSON Web Encryption (JWE) is a separate standard for hiding claims. Signing does not hide them.
  • Decoding the middle segment and skipping the signature. Anyone can write the header and payload.
  • Trusting the alg header. Pin HS256, RS256, or ES256 in server code, and reject none and every other value.
  • Accepting a different algorithm than the one you sign with. If you issue RS256 tokens, reject HS256. A caller can otherwise switch the header to HS256 and sign with the public key, which verifiers already hold.
  • Omitting exp, or setting it days away on a token you cannot revoke.
  • Skipping iss and aud when more than one service accepts tokens from the same issuer.
  • Putting passwords, API secrets, or large objects in the payload.
  • Committing the HMAC secret or the private key, or shipping the secret to the client.
  • Comparing signatures with ordinary string equality.
  • Sending the token over plain HTTP, where anything on the path can copy a bearer credential.

Questions & Answers about JWT

Authenticate the caller, sign a small set of claims with a server-side key, and return the token. The client sends that token on later requests, usually in the Authorization header as a Bearer token. The API verifies the signature and checks exp, iss, and aud before it trusts the subject.

On this page

  1. Token structure
  2. Signing a JWT
  3. Verifying a JWT
  4. How to use a JWT
  5. Common mistakes

Turn your API stack into one workflow. Start for free, integrate in minutes, and scale when you need to.

Start for free
unkey

Build better APIs faster

© 2026 Unkey Inc. All rights reserved.

SOC 2 Type II Certified

Company

  • About
  • Careers
  • Status Page
  • Roadmap

Resources

  • Blog
  • Case Studies
  • Changelog
  • Docs
  • Glossary
  • Feature Request
  • Archive

Connect

  • X (Twitter)
  • Discord
  • Book a Call

Legal

  • Terms of Service
  • Privacy Policy
  • Trust Center