Protecting Routes
Once your API key is configured, you can protect individual routes, route groups, or invoke authentication manually inside controllers and middleware using ctx.simpleAuth.
How Middleware Works
During Installation, two middleware entries are registered in start/kernel.ts:
SimpleAuthMiddleware(router middleware): InstantiatesSimpleAuthand attaches it to every HTTP request context asctx.simpleAuth. It does not block requests on its own.ApiKeyMiddleware(apiKeynamed middleware): Callsctx.simpleAuth.authenticate()to verify the incoming API key header before allowing the request to proceed.
Using the apiKey Middleware
Import the middleware collection from #start/kernel and attach middleware.apiKey() to any route or route group in start/routes.ts:
import router from '@adonisjs/core/services/router';
import { middleware } from '#start/kernel';
// Protect a single route
router
.get('/webhooks/sync', async () => {
return { status: 'ok' };
})
.use(middleware.apiKey());
// Protect a group of routes
router
.group(() => {
router.get('/users', '#controllers/users_controller.index');
router.post('/users', '#controllers/users_controller.store');
})
.prefix('/api/v1')
.use(middleware.apiKey());
Making Authenticated Requests
Clients must include the configured header (x-api-key by default) with the exact API key value:
curl -X GET http://localhost:3333/api/v1/users \
-H "x-api-key: oat_YWI.dXNlcl9zZWVkX2V4YW1wbGVfNDBfY2hhcnNfMTIzNDU2Nzg5MDEyMzQ1Ng"
const response = await fetch('http://localhost:3333/api/v1/users', {
headers: {
'x-api-key': process.env.API_KEY!,
},
});
Manual Authentication via ctx.simpleAuth
Because SimpleAuthMiddleware augments HttpContext with ctx.simpleAuth, you can call ctx.simpleAuth.authenticate() directly inside a controller action or custom middleware:
import type { HttpContext } from '@adonisjs/core/http';
export default class ReportsController {
async handle({ simpleAuth, response }: HttpContext) {
// Throws SimpleAuthException (401) if the API key is missing or invalid
simpleAuth.authenticate();
return response.ok({ generated: true });
}
}
Customizing the Published Middleware
Because app/middleware/api_key_middleware.ts lives in your application codebase, you have full control over its behavior. For example, you can add logging or custom headers after authentication succeeds:
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
export default class ApiKeyMiddleware {
async handle(ctx: HttpContext, next: NextFn) {
ctx.simpleAuth.authenticate();
ctx.logger.debug('Request authenticated via API key');
return next();
}
}
To learn how authentication failures are formatted and how to translate error messages, see Error Handling & i18n.
