{"id":17808,"library":"middy-middleware-jwt-auth","title":"Middy JWT Authorization Middleware","description":"middy-middleware-jwt-auth is a specialized middleware designed for the Middy.js framework, enabling JSON Web Token (JWT) authorization for AWS Lambda functions. Inspired by `express-jwt`, it simplifies the process of verifying JWTs and injecting the decoded payload into the Lambda `event.auth` object. The current stable version is `6.3.0`. The library follows the Middy.js release cadence, frequently updating to support new major versions of `@middy/core`. Key differentiators include its tight integration with the Middy ecosystem, robust type definitions for TypeScript users, and customizable token extraction and verification options, including support for various encryption algorithms and asynchronous secret retrieval. It aims to provide a reliable and easy-to-use solution for securing serverless API endpoints with JWTs.","status":"active","version":"6.3.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/dbartholomae/middy-middleware-jwt-auth","tags":["javascript","middy","middleware","jwt","json web token","typescript"],"install":[{"cmd":"npm install middy-middleware-jwt-auth","lang":"bash","label":"npm"},{"cmd":"yarn add middy-middleware-jwt-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add middy-middleware-jwt-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core middleware engine for AWS Lambda functions, required for this middleware to function.","package":"@middy/core","optional":false},{"reason":"Underlying library used for JWT signing and verification, implicitly required by the middleware.","package":"jsonwebtoken","optional":false}],"imports":[{"note":"The primary middleware is a default export. Using named import will result in undefined or a TypeError.","wrong":"import { JWTAuthMiddleware } from 'middy-middleware-jwt-auth';","symbol":"JWTAuthMiddleware","correct":"import JWTAuthMiddleware from 'middy-middleware-jwt-auth';"},{"note":"This is a named export enum providing supported JWT encryption algorithms.","wrong":"import EncryptionAlgorithms from 'middy-middleware-jwt-auth';","symbol":"EncryptionAlgorithms","correct":"import { EncryptionAlgorithms } from 'middy-middleware-jwt-auth';"},{"note":"This TypeScript interface defines the enhanced event object available after the middleware processes a valid JWT, including the `auth` property.","wrong":"import IAuthorizedEvent from 'middy-middleware-jwt-auth';","symbol":"IAuthorizedEvent","correct":"import { IAuthorizedEvent } from 'middy-middleware-jwt-auth';"}],"quickstart":{"code":"import createHttpError from \"http-errors\";\nimport middy from \"@middy/core\";\nimport httpErrorHandler from \"@middy/http-error-handler\";\nimport httpHeaderNormalizer from \"@middy/http-header-normalizer\";\nimport JWTAuthMiddleware, {\n  EncryptionAlgorithms,\n  IAuthorizedEvent,\n} from \"middy-middleware-jwt-auth\";\n\n// Define the token payload structure expected from your JWT\ninterface ITokenPayload {\n  permissions: string[];\n}\n\n// Type guard for the token payload to ensure runtime safety\nfunction isTokenPayload(token: any): token is ITokenPayload {\n  return (\n    token != null &&\n    Array.isArray(token.permissions) &&\n    token.permissions.every((permission: any) => typeof permission === \"string\")\n  );\n}\n\n// Your AWS Lambda handler function\nconst helloWorld = async (event: IAuthorizedEvent<ITokenPayload>) => {\n  // Access the authenticated payload from event.auth\n  if (!event.auth || !isTokenPayload(event.auth.payload)) {\n    throw createHttpError(401, \"Unauthorized: Invalid token payload\");\n  }\n\n  // Perform authorization check based on permissions in the token\n  if (event.auth.payload.permissions.indexOf(\"helloWorld\") === -1) {\n    throw createHttpError(\n      403,\n      `User not authorized for helloWorld, only found permissions [${event.auth.payload.permissions.join(\", \")}]`,\n      {\n        type: \"NotAuthorized\",\n      },\n    );\n  }\n\n  return {\n    body: JSON.stringify({\n      data: `Hello world! Here's your token: ${event.auth.token}`,\n      userId: event.auth.payload.sub // Assuming 'sub' is in your token\n    }),\n    statusCode: 200,\n  };\n};\n\n// 'Middyfy' your handler and attach the JWT authorization middleware\nexport const handler = middy(helloWorld)\n  .use(httpHeaderNormalizer()) // Ensures Authorization header is consistently cased\n  .use(httpErrorHandler())    // Catches errors thrown by JWTAuthMiddleware and returns appropriate HTTP responses\n  .use(\n    JWTAuthMiddleware({\n      algorithm: EncryptionAlgorithms.HS256,\n      credentialsRequired: true, // Set to true to make a missing or invalid token result in a 401\n      secretOrPublicKey: process.env.JWT_SECRET ?? 'supersecretkey',\n      // You can also specify an async function for secretOrPublicKey or tokenSource since v6.3.0\n      // secretOrPublicKey: async (header, payload, done) => { /* fetch secret */ done(null, 'secret'); },\n      // tokenSource: (event) => event.headers['x-custom-token'],\n    }),\n  );","lang":"typescript","description":"This quickstart demonstrates how to set up a Middy handler with `middy-middleware-jwt-auth` to enforce JWT authentication, extract the token payload, and perform fine-grained authorization checks based on the decoded token's content."},"warnings":[{"fix":"Consult `https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes` for `jsonwebtoken` v9. Update your `secretOrPublicKey` and other JWT options accordingly.","message":"Version 6.0.0 introduced a breaking change by upgrading its underlying `jsonwebtoken` dependency to version 9. Users must review the migration notes for `jsonwebtoken` v9, as related breaking changes (e.g., in options for `sign` or `verify` methods) now apply to `middy-middleware-jwt-auth`.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Always import `JWTAuthMiddleware` as a default export: `import JWTAuthMiddleware from 'middy-middleware-jwt-auth';`","message":"The `JWTAuthMiddleware` is a default export. Attempting to import it as a named export (e.g., `import { JWTAuthMiddleware } from '...'`) will lead to runtime errors like `TypeError: (0, middy_middleware_jwt_auth_1.JWTAuthMiddleware) is not a function` in CommonJS contexts or `undefined` in ESM.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"To make authentication mandatory, set `credentialsRequired: true` in the middleware options: `JWTAuthMiddleware({ ..., credentialsRequired: true })`.","message":"The middleware's `credentialsRequired` option defaults to `false`. This means if no `Authorization` header is present or the token is invalid, the middleware will proceed without throwing an error, but `event.auth` will be `undefined`. You must explicitly set it to `true` to enforce authentication for a given handler.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When using `secretOrPublicKey` or `tokenSource` as functions, make sure they correctly return a Promise or use the provided callback. Example for `secretOrPublicKey` with a callback: `secretOrPublicKey: (header, payload, done) => { someAsyncFetch().then(secret => done(null, secret)).catch(done); }`.","message":"Since version 6.3.0, `secretOrPublicKey` and `tokenSource` can be asynchronous functions. While this offers flexibility (e.g., fetching secrets from Secrets Manager), ensure your implementation correctly handles promises and callbacks, as incorrect usage might lead to verification failures or unexpected delays.","severity":"gotcha","affected_versions":">=6.3.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Change the import statement to `import JWTAuthMiddleware from 'middy-middleware-jwt-auth';`","cause":"Attempting to import `JWTAuthMiddleware` using a named import syntax when it is a default export.","error":"TypeError: (0, middy_middleware_jwt_auth_1.JWTAuthMiddleware) is not a function"},{"fix":"Verify that the token sent in the `Authorization` header (typically `Bearer <token>`) is correctly formatted and that the `secretOrPublicKey` configured in the middleware matches the key used to sign the token.","cause":"The provided JWT is not a valid JSON Web Token structure, or its signature does not match the provided `secretOrPublicKey`.","error":"Error: 'jwt malformed' or 'invalid signature'"},{"fix":"Ensure the client sends a valid `Authorization: Bearer <token>` header, or if authentication is optional, set `credentialsRequired: false` in the middleware configuration.","cause":"The `Authorization` header is missing or empty, and `credentialsRequired` is set to `true` in the middleware options.","error":"Error: 'No authorization token was found'"},{"fix":"Always check for the existence of `event.auth` before accessing its properties: `if (event.auth && event.auth.payload) { ... }`. Alternatively, ensure `credentialsRequired: true` if the `auth` object is strictly needed.","cause":"Attempting to access `event.auth` without checking if a token was present/valid, or when `credentialsRequired` is `false` and no token was provided.","error":"TypeError: event.auth is undefined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}