or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# JWT Decode

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: jwt-decode

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install jwt-decode`

10

11

## Core Imports

12

13

```typescript

14

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

15

```

16

17

For CommonJS:

18

19

```javascript

20

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

21

```

22

23

For browser script tag:

24

25

```html

26

<script type="module">

27

import { jwtDecode } from "./path/to/jwt-decode.js";

28

// Use jwtDecode...

29

</script>

30

```

31

32

## Basic Usage

33

34

```typescript

35

import { jwtDecode } from "jwt-decode";

36

37

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

38

39

// Decode JWT payload (default behavior)

40

const payload = jwtDecode(token);

41

console.log(payload);

42

// { foo: "bar", exp: 1393286893, iat: 1393268893 }

43

44

// Decode JWT header

45

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

46

console.log(header);

47

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

48

49

// Use with TypeScript type safety

50

interface CustomPayload {

51

foo: string;

52

exp: number;

53

iat: number;

54

}

55

const typedPayload = jwtDecode<CustomPayload>(token);

56

```

57

58

## Architecture

59

60

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

61

62

- **Token Parsing Pipeline**: Splits JWT tokens into header/payload parts → decodes base64url → parses JSON

63

- **Type Safety**: Generic type system allows compile-time checking of custom JWT structures

64

- **Error Handling**: Single `InvalidTokenError` class with descriptive messages for all failure modes

65

- **Zero Dependencies**: Pure JavaScript implementation using native browser/Node.js APIs (atob, JSON.parse)

66

- **Universal Compatibility**: Works in browsers, Node.js, and edge runtimes without polyfills

67

68

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

69

70

## Capabilities

71

72

### JWT Decoding

73

74

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

75

76

```typescript { .api }

77

/**

78

* Decode JWT header when header option is true

79

* @param token - JWT token string to decode

80

* @param options - Options with header: true to decode header

81

* @returns Decoded header object with generic type T (defaults to JwtHeader)

82

* @throws InvalidTokenError for invalid tokens

83

*/

84

function jwtDecode<T = JwtHeader>(

85

token: string,

86

options: JwtDecodeOptions & { header: true }

87

): T;

88

89

/**

90

* Decode JWT payload (default behavior)

91

* @param token - JWT token string to decode

92

* @param options - Optional configuration object

93

* @returns Decoded payload object with generic type T (defaults to JwtPayload)

94

* @throws InvalidTokenError for invalid tokens

95

*/

96

function jwtDecode<T = JwtPayload>(token: string, options?: JwtDecodeOptions): T;

97

```

98

99

**Usage Examples:**

100

101

```typescript

102

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

103

104

// Basic payload decoding

105

const payload = jwtDecode(token);

106

107

// Header decoding

108

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

109

110

// Custom type with payload

111

interface UserPayload extends JwtPayload {

112

userId: string;

113

roles: string[];

114

}

115

const userPayload = jwtDecode<UserPayload>(token);

116

117

// Custom type with header

118

interface CustomHeader extends JwtHeader {

119

kid: string;

120

}

121

const customHeader = jwtDecode<CustomHeader>(token, { header: true });

122

```

123

124

### Error Handling

125

126

Custom error class for JWT decoding failures.

127

128

```typescript { .api }

129

/**

130

* Custom error thrown when JWT decoding fails

131

*/

132

class InvalidTokenError extends Error {

133

name: "InvalidTokenError";

134

}

135

```

136

137

**Common error scenarios:**

138

139

- Token is not a string: `"Invalid token specified: must be a string"`

140

- Missing token parts: `"Invalid token specified: missing part #1"` or `"Invalid token specified: missing part #2"`

141

- Invalid base64 encoding: `"Invalid token specified: invalid base64 for part #N"`

142

- Invalid JSON: `"Invalid token specified: invalid json for part #N"`

143

144

**Usage Example:**

145

146

```typescript

147

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

148

149

try {

150

const payload = jwtDecode(invalidToken);

151

} catch (error) {

152

if (error instanceof InvalidTokenError) {

153

console.error("JWT decoding failed:", error.message);

154

}

155

}

156

```

157

158

## Types

159

160

### Configuration Options

161

162

```typescript { .api }

163

interface JwtDecodeOptions {

164

/** When true, decodes JWT header instead of payload */

165

header?: boolean;

166

}

167

```

168

169

### Standard JWT Header

170

171

```typescript { .api }

172

interface JwtHeader {

173

/** Token type, typically "JWT" */

174

typ?: string;

175

/** Signing algorithm (e.g., "HS256", "RS256") */

176

alg?: string;

177

/** Key ID for key identification */

178

kid?: string;

179

}

180

```

181

182

### Standard JWT Payload

183

184

```typescript { .api }

185

interface JwtPayload {

186

/** Issuer claim - identifies the principal that issued the JWT */

187

iss?: string;

188

/** Subject claim - identifies the principal that is the subject of the JWT */

189

sub?: string;

190

/** Audience claim - identifies the recipients that the JWT is intended for */

191

aud?: string[] | string;

192

/** Expiration time claim - identifies the expiration time (Unix timestamp) */

193

exp?: number;

194

/** Not before claim - identifies the time before which the JWT must not be accepted (Unix timestamp) */

195

nbf?: number;

196

/** Issued at claim - identifies the time at which the JWT was issued (Unix timestamp) */

197

iat?: number;

198

/** JWT ID claim - provides a unique identifier for the JWT */

199

jti?: string;

200

}

201

```

202

203

## Important Notes

204

205

- **No Validation**: This library only decodes JWT tokens - it does not validate signatures, expiration, or other security aspects

206

- **Client-Side Focus**: Designed primarily for browser applications where JWT inspection is needed

207

- **Zero Dependencies**: No runtime dependencies for minimal bundle size

208

- **Unicode Support**: Handles UTF-8 encoded content in JWT tokens

209

- **Type Safety**: Full TypeScript support with generic types for custom payload/header structures

210

- **Multiple Formats**: Supports CommonJS, ES modules, and browser script tag imports