isJWT
Checks if a string is a valid JSON Web Token (JWT). A valid JWT has three parts separated by dots and each part must be a valid Base64Url string.
1/**
2 * Checks if a string is a valid JSON Web Token (JWT).
3 *
4 * A valid JWT has three parts separated by dots and each part must be a valid Base64Url string.
5 *
6 * @param token - The string to check.
7 * @returns True if the string is a valid JWT, false otherwise.
8 */
9export function isJWT(token: string): boolean {
10 if (typeof token !== 'string') return false;
11
12 const parts = token.split('.');
13 if (parts.length !== 3) return false;
14
15 const base64urlRegex = /^[A-Za-z0-9\-_]+$/;
16 return parts.every(part => base64urlRegex.test(part));
17}
Structure-Aware Validation
Verifies the presence of all three required parts of a JWT (header, payload, signature), ensuring the basic token format is correct.
Base64Url Safety Check
Ensures each segment strictly adheres to Base64Url encoding standards — critical for safe transmission in URLs and HTTP headers.
Lightweight & Dependency-Free
Provides efficient validation without relying on JWT libraries, making it suitable for pre-checks or fast filters.
Fail-Safe by Design
Returns
false
for any malformed input or non-string value, reducing the risk of unhandled errors during validation.
Tests | Examples
1test('valid JWT structure', () => {
2 const token =
3 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' + '.' +
4 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ' + '.' +
5 'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
6 expect(isJWT(token)).toBe(true);
7});
8
9test('invalid JWT - wrong number of parts', () => {
10 expect(isJWT('one.two')).toBe(false);
11 expect(isJWT('one.two.three.four')).toBe(false);
12});
13
14test('invalid JWT - non-base64url characters', () => {
15 const token = 'eyJ@#$.eyJzdWIiOiIxMjM0.NzkwIiwiaWF0IjoxNTE2MjM5MDIyfQ';
16 expect(isJWT(token)).toBe(false);
17});
18
19test('non-string input returns false', () => {
20 expect(isJWT(null as any)).toBe(false);
21 expect(isJWT(undefined as any)).toBe(false);
22 expect(isJWT(123 as any)).toBe(false);
23});
Common Use Cases
API Token Validation
Quickly check the format of incoming JWT tokens in request headers before deeper parsing or authentication.
Client-Side Session Checks
Validate stored JWT tokens in
localStorage
or cookies to ensure they're not malformed before usage.Pre-Decode Safety Filter
Prevent
atob()
or JSON parse errors by ensuring a string is properly formatted as a JWT before decoding.Form or Input Sanitization
Validate JWTs submitted by users (e.g., via debugging tools or support portals) before processing them.