or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jwt-decode

Decode JWT tokens, mostly useful for browser applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jwt-decode@4.0.x

To install, run

npx @tessl/cli install tessl/npm-jwt-decode@4.0.0

index.mddocs/

JWT Decode

JWT Decode is a browser-focused TypeScript/JavaScript library for decoding JSON Web Tokens (JWT). It extracts header and payload information from well-formed JWT tokens without validation, making it ideal for client-side applications that need to inspect JWT claims and metadata.

Package Information

  • Package Name: jwt-decode
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install jwt-decode

Core Imports

import { jwtDecode, InvalidTokenError, JwtHeader, JwtPayload, JwtDecodeOptions } from "jwt-decode";

For CommonJS:

const { jwtDecode, InvalidTokenError, JwtHeader, JwtPayload, JwtDecodeOptions } = require("jwt-decode");

For browser script tag:

<script type="module">
  import { jwtDecode } from "./path/to/jwt-decode.js";
  // Use jwtDecode...
</script>

Basic Usage

import { jwtDecode } from "jwt-decode";

const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEzOTMyODY4OTMsImlhdCI6MTM5MzI2ODg5M30.4-iaDojEVl0pJQMjrbM1EzUIfAZgsbK_kgnVyVxFSVo";

// Decode JWT payload (default behavior)
const payload = jwtDecode(token);
console.log(payload);
// { foo: "bar", exp: 1393286893, iat: 1393268893 }

// Decode JWT header
const header = jwtDecode(token, { header: true });
console.log(header);
// { typ: "JWT", alg: "HS256" }

// Use with TypeScript type safety
interface CustomPayload {
  foo: string;
  exp: number;
  iat: number;
}
const typedPayload = jwtDecode<CustomPayload>(token);

Architecture

JWT Decode follows a simple, focused architecture designed for client-side JWT inspection:

  • Token Parsing Pipeline: Splits JWT tokens into header/payload parts → decodes base64url → parses JSON
  • Type Safety: Generic type system allows compile-time checking of custom JWT structures
  • Error Handling: Single InvalidTokenError class with descriptive messages for all failure modes
  • Zero Dependencies: Pure JavaScript implementation using native browser/Node.js APIs (atob, JSON.parse)
  • Universal Compatibility: Works in browsers, Node.js, and edge runtimes without polyfills

The library intentionally focuses only on decoding - it does not validate signatures, check expiration, or perform any security operations, keeping it lightweight and focused.

Capabilities

JWT Decoding

Main function for decoding JWT tokens with support for both header and payload extraction.

/**
 * Decode JWT header when header option is true
 * @param token - JWT token string to decode
 * @param options - Options with header: true to decode header
 * @returns Decoded header object with generic type T (defaults to JwtHeader)
 * @throws InvalidTokenError for invalid tokens
 */
function jwtDecode<T = JwtHeader>(
  token: string,
  options: JwtDecodeOptions & { header: true }
): T;

/**
 * Decode JWT payload (default behavior)
 * @param token - JWT token string to decode
 * @param options - Optional configuration object
 * @returns Decoded payload object with generic type T (defaults to JwtPayload)
 * @throws InvalidTokenError for invalid tokens
 */
function jwtDecode<T = JwtPayload>(token: string, options?: JwtDecodeOptions): T;

Usage Examples:

import { jwtDecode, JwtPayload, JwtHeader } from "jwt-decode";

// Basic payload decoding
const payload = jwtDecode(token);

// Header decoding
const header = jwtDecode(token, { header: true });

// Custom type with payload
interface UserPayload extends JwtPayload {
  userId: string;
  roles: string[];
}
const userPayload = jwtDecode<UserPayload>(token);

// Custom type with header
interface CustomHeader extends JwtHeader {
  kid: string;
}
const customHeader = jwtDecode<CustomHeader>(token, { header: true });

Error Handling

Custom error class for JWT decoding failures.

/**
 * Custom error thrown when JWT decoding fails
 */
class InvalidTokenError extends Error {
  name: "InvalidTokenError";
}

Common error scenarios:

  • Token is not a string: "Invalid token specified: must be a string"
  • Missing token parts: "Invalid token specified: missing part #1" or "Invalid token specified: missing part #2"
  • Invalid base64 encoding: "Invalid token specified: invalid base64 for part #N"
  • Invalid JSON: "Invalid token specified: invalid json for part #N"

Usage Example:

import { jwtDecode, InvalidTokenError } from "jwt-decode";

try {
  const payload = jwtDecode(invalidToken);
} catch (error) {
  if (error instanceof InvalidTokenError) {
    console.error("JWT decoding failed:", error.message);
  }
}

Types

Configuration Options

interface JwtDecodeOptions {
  /** When true, decodes JWT header instead of payload */
  header?: boolean;
}

Standard JWT Header

interface JwtHeader {
  /** Token type, typically "JWT" */
  typ?: string;
  /** Signing algorithm (e.g., "HS256", "RS256") */
  alg?: string;
  /** Key ID for key identification */
  kid?: string;
}

Standard JWT Payload

interface JwtPayload {
  /** Issuer claim - identifies the principal that issued the JWT */
  iss?: string;
  /** Subject claim - identifies the principal that is the subject of the JWT */
  sub?: string;
  /** Audience claim - identifies the recipients that the JWT is intended for */
  aud?: string[] | string;
  /** Expiration time claim - identifies the expiration time (Unix timestamp) */
  exp?: number;
  /** Not before claim - identifies the time before which the JWT must not be accepted (Unix timestamp) */
  nbf?: number;
  /** Issued at claim - identifies the time at which the JWT was issued (Unix timestamp) */
  iat?: number;
  /** JWT ID claim - provides a unique identifier for the JWT */
  jti?: string;
}

Important Notes

  • No Validation: This library only decodes JWT tokens - it does not validate signatures, expiration, or other security aspects
  • Client-Side Focus: Designed primarily for browser applications where JWT inspection is needed
  • Zero Dependencies: No runtime dependencies for minimal bundle size
  • Unicode Support: Handles UTF-8 encoded content in JWT tokens
  • Type Safety: Full TypeScript support with generic types for custom payload/header structures
  • Multiple Formats: Supports CommonJS, ES modules, and browser script tag imports