Registry /
aws / middy-middleware-jwt-auth
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
JWTAuthMiddleware
✓ import JWTAuthMiddleware from 'middy-middleware-jwt-auth';
✗ import { JWTAuthMiddleware } from 'middy-middleware-jwt-auth';
The primary middleware is a default export. Using named import will result in undefined or a TypeError.
EncryptionAlgorithms
✓ import { EncryptionAlgorithms } from 'middy-middleware-jwt-auth';
✗ import EncryptionAlgorithms from 'middy-middleware-jwt-auth';
This is a named export enum providing supported JWT encryption algorithms.
IAuthorizedEvent
✓ import { IAuthorizedEvent } from 'middy-middleware-jwt-auth';
✗ import IAuthorizedEvent from 'middy-middleware-jwt-auth';
This TypeScript interface defines the enhanced event object available after the middleware processes a valid JWT, including the `auth` property.
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.
import createHttpError from "http-errors";
import middy from "@middy/core";
import httpErrorHandler from "@middy/http-error-handler";
import httpHeaderNormalizer from "@middy/http-header-normalizer";
import JWTAuthMiddleware, {
EncryptionAlgorithms,
IAuthorizedEvent,
} from "middy-middleware-jwt-auth";
// Define the token payload structure expected from your JWT
interface ITokenPayload {
permissions: string[];
}
// Type guard for the token payload to ensure runtime safety
function isTokenPayload(token: any): token is ITokenPayload {
return (
token != null &&
Array.isArray(token.permissions) &&
token.permissions.every((permission: any) => typeof permission === "string")
);
}
// Your AWS Lambda handler function
const helloWorld = async (event: IAuthorizedEvent<ITokenPayload>) => {
// Access the authenticated payload from event.auth
if (!event.auth || !isTokenPayload(event.auth.payload)) {
throw createHttpError(401, "Unauthorized: Invalid token payload");
}
// Perform authorization check based on permissions in the token
if (event.auth.payload.permissions.indexOf("helloWorld") === -1) {
throw createHttpError(
403,
`User not authorized for helloWorld, only found permissions [${event.auth.payload.permissions.join(", ")}]`,
{
type: "NotAuthorized",
},
);
}
return {
body: JSON.stringify({
data: `Hello world! Here's your token: ${event.auth.token}`,
userId: event.auth.payload.sub // Assuming 'sub' is in your token
}),
statusCode: 200,
};
};
// 'Middyfy' your handler and attach the JWT authorization middleware
export const handler = middy(helloWorld)
.use(httpHeaderNormalizer()) // Ensures Authorization header is consistently cased
.use(httpErrorHandler()) // Catches errors thrown by JWTAuthMiddleware and returns appropriate HTTP responses
.use(
JWTAuthMiddleware({
algorithm: EncryptionAlgorithms.HS256,
credentialsRequired: true, // Set to true to make a missing or invalid token result in a 401
secretOrPublicKey: process.env.JWT_SECRET ?? 'supersecretkey',
// You can also specify an async function for secretOrPublicKey or tokenSource since v6.3.0
// secretOrPublicKey: async (header, payload, done) => { /* fetch secret */ done(null, 'secret'); },
// tokenSource: (event) => event.headers['x-custom-token'],
}),
);
Errors
Common errors & fixes
TypeError: (0, middy_middleware_jwt_auth_1.JWTAuthMiddleware) is not a function
Attempting to import `JWTAuthMiddleware` using a named import syntax when it is a default export.
fixChange the import statement to `import JWTAuthMiddleware from 'middy-middleware-jwt-auth';`
Error: 'jwt malformed' or 'invalid signature'
The provided JWT is not a valid JSON Web Token structure, or its signature does not match the provided `secretOrPublicKey`.
fixVerify 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.
Error: 'No authorization token was found'
The `Authorization` header is missing or empty, and `credentialsRequired` is set to `true` in the middleware options.
fixEnsure the client sends a valid `Authorization: Bearer <token>` header, or if authentication is optional, set `credentialsRequired: false` in the middleware configuration.
TypeError: event.auth is undefined
Attempting to access `event.auth` without checking if a token was present/valid, or when `credentialsRequired` is `false` and no token was provided.
fixAlways 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. Audit
Dependencies
@middy/corerequiredCore middleware engine for AWS Lambda functions, required for this middleware to function.
jsonwebtokenrequiredUnderlying library used for JWT signing and verification, implicitly required by the middleware.