Skip to content

How to Fix JWT Malformed Token Error

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix JWT Malformed Token Error. We cover key concepts, practical examples, and best practices.

The Problem

Your server receives:

{
  "error": "JsonWebTokenError",
  "message": "jwt malformed"
}

Or:

MalformedToken: The token provided is not a valid JWT

The token string does not have the correct JWT structure (three dot-separated segments: header.payload.signature).

Quick Fix

1. Check the token format

A valid JWT has three parts separated by dots:

header.payload.signature
// Validate JWT format
function isValidJwtFormat(token) {
  if (typeof token !== 'string') return false
  const parts = token.split('.')
  return parts.length === 3
}

console.log(isValidJwtFormat('abc.def.ghi'))  // true
console.log(isValidJwtFormat('abc.def'))      // false
console.log(isValidJwtFormat('abc.def.ghi.jkl'))  // false

2. Strip the Bearer prefix

The most common cause — keeping the "Bearer " prefix:

// Wrong — includes "Bearer " prefix
const authHeader = req.headers.authorization
// authHeader = "Bearer eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjF9.signature"
jwt.verify(authHeader, SECRET)
// Error: jwt malformed

// Right — strip the prefix
const authHeader = req.headers.authorization
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : authHeader
jwt.verify(token, SECRET)

3. Check for whitespace or newlines

The token may contain extra whitespace:

// Wrong — token with newline or spaces
const token = ' eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjF9.signature\n'
jwt.verify(token, SECRET)  // malformed

// Right — trim the token
const cleanToken = token.trim()
jwt.verify(cleanToken, SECRET)

4. Verify base64 encoding

The token parts must be valid base64url encoded:

function isValidBase64(str) {
  try {
    return btoa(atob(str)) === str
  } catch (e) {
    return false
  }
}

const parts = token.split('.')
console.log(parts.every(isValidBase64))  // should be true

5. Handle URL-encoded tokens

Tokens in query strings may be URL-encoded:

// URL-encoded JWT contains %2E instead of dots
const urlEncodedToken = 'eyJhbGciOiJIUzI1NiJ9%2EeyJleHAiOjF9%2Esignature'

// Wrong — fails because dots are %2E
jwt.verify(urlEncodedToken, SECRET)

// Right — decode first
const token = decodeURIComponent(urlEncodedToken)
jwt.verify(token, SECRET)

6. Check for incomplete token transmission

The token may be truncated by logging frameworks or middleware:

// Log the token length for debugging
console.log('Token length:', token.length)
console.log('Token starts with:', token.substring(0, 20))
console.log('Token ends with:', token.substring(token.length - 20))

Prevention

  • Always strip the "Bearer " prefix before verification.
  • Trim the token to remove whitespace.
  • Validate JWT format before attempting to decode.
  • Log token length (not the token itself) for debugging.
  • Use a consistent method for extracting tokens from requests.
  • Test token handling with both valid and invalid formats in your test suite.

Common Mistakes with token malformed

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world JWT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What does a valid JWT look like?

A valid JWT is three base64url-encoded strings separated by dots, like: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjF9.signature. The first part is the header, the second is the payload, and the third is the signature.

Can a JWT have more or fewer than three parts?

No. A valid JWT always has exactly three dot-separated segments. If you see a different number, the token is malformed or it is not a JWT at all.

What is the most common cause of "jwt malformed"?

The most common cause is not removing the "Bearer " prefix from the Authorization header before passing the token to the JWT library. Always strip the prefix first.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro