DevToolsForYou

JWT Encoder and Decoder in JavaScript / Node.js — Code Examples

JWT Encoder and Decoder in JavaScript / Node.jsUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

The jsonwebtoken package is the standard Node.js JWT library. Use jwt.sign to create tokens and jwt.verify to validate them.

Node.js
// npm install jsonwebtoken
const jwt = require("jsonwebtoken");

const secret = "my-secret-key";
const payload = { userId: 42, name: "Alice", role: "admin" };

// Sign (encode) — HS256 is the default algorithm
const token = jwt.sign(payload, secret, { expiresIn: "1h" });
console.log(token);
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

// Verify and decode
try {
  const decoded = jwt.verify(token, secret);
  console.log(decoded);
  // { userId: 42, name: 'Alice', role: 'admin', iat: ..., exp: ... }
} catch (err) {
  if (err.name === "TokenExpiredError") console.error("Token expired");
  else console.error("Invalid token:", err.message);
}

// Decode without verifying (inspect header/payload only)
const unverified = jwt.decode(token, { complete: true });
console.log(unverified.header); // { alg: 'HS256', typ: 'JWT' }
console.log(unverified.payload);
Notes & gotchas
  • Never use jwt.decode() to authorise requests — it does not verify the signature.
  • For RS256, pass a PEM private key to sign and the matching public key to verify.
  • Store secrets in environment variables, not in source code.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages