@opble/mastra-auth0
v0.0.2
Published
Auth0 JWT middleware for Mastra servers.
Maintainers
Readme
@opble/mastra-auth0
Auth0 JWT middleware for Mastra servers. Protects your API routes by enforcing a valid Auth0 Bearer token on every request.
Installation
npm install @opble/mastra-auth0Usage
Set the required environment variables:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://your-api-identifierThen register the middleware on your Mastra server:
import { Mastra } from 'mastra';
import { createAuth0Middleware } from '@opble/mastra-auth0';
export const mastra = new Mastra({
server: {
middleware: [
{
path: '/api/*',
handler: createAuth0Middleware() as any,
},
],
},
});Note: The
as anycast is required because@mastra/corevendors its own copy of Hono's types internally, causing a structural type mismatch at the assignment site. The middleware itself is fully type-safe — only the assignment into Mastra's config needs the cast.
That's it. Any request to /api/* without a valid Authorization: Bearer <token> header will receive a 401 response.
Environment variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| AUTH0_DOMAIN | Yes | — | Your Auth0 tenant domain, e.g. your-tenant.auth0.com |
| AUTH0_AUDIENCE | Yes | — | API Identifier registered in your Auth0 dashboard |
| AUTH0_ENABLED | No | true | Set to false to disable auth (useful in local development) |
Options
All options are optional and override their corresponding environment variable:
createAuth0Middleware({
domain: 'your-tenant.auth0.com', // overrides AUTH0_DOMAIN
audience: 'https://your-api', // overrides AUTH0_AUDIENCE
enabled: true, // overrides AUTH0_ENABLED
contextKey: 'auth0User', // key used to store JWT payload in Hono context
getToken: (c) => c.req.header('x-token'), // custom token extraction
onSuccess: async (c, payload) => { // called after successful verification
c.set('MASTRA_RESOURCE_ID_KEY', payload.sub as string);
},
onError: async (c, err) => { // custom error response
return c.json({ error: 'Unauthorized' }, 401);
},
})License
UNLICENSED
