Usage

Protecting Routes

Authenticate incoming HTTP requests using the apiKey middleware or ctx.simpleAuth.

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:

  1. SimpleAuthMiddleware (router middleware): Instantiates SimpleAuth and attaches it to every HTTP request context as ctx.simpleAuth. It does not block requests on its own.
  2. ApiKeyMiddleware (apiKey named middleware): Calls ctx.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:

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"

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:

app/controllers/reports_controller.ts
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:

app/middleware/api_key_middleware.ts
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.