Core Concepts / Guards

Guards

Control access to routes based on conditions like authentication and roles.

Guards determine whether a request should be handled by the route handler. They are the recommended way to implement authentication and authorization in MiiaJS.

CanActivate interface

A guard is a class that implements the CanActivate interface:

typescript
import type { CanActivate, RequestContext } from '@miiajs/core'

class AuthGuard implements CanActivate {
  canActivate(ctx: RequestContext): boolean | Promise<boolean> {
    const token = ctx.req.headers.get('authorization')
    return !!token
  }
}
  • Return true to allow the request
  • Return false to reject with 403 Forbidden
  • Throw an HttpException for a custom error response

Applying guards

Per route

typescript
import { UseGuard } from '@miiajs/core'

@Controller('/items')
class ItemController {
  @Delete('/:id')
  @UseGuard(AuthGuard)
  remove(ctx: RequestContext) {
    return { deleted: true }
  }
}

Per controller

typescript
@Controller('/admin')
@UseGuard(AuthGuard)
class AdminController {
  @Get('/dashboard')
  dashboard() {
    return { stats: {} }
  }
}

Global

typescript
const app = new Miia()
  .useGuard(AuthGuard)
  .register(AppModule)

Global guards are constructed together with every other singleton provider, so their field initializers run before any onInit(), and they receive the lifecycle hooks onInit() / onReady() / onShutdown() / onDestroy() like any provider.

A global guard is checked against module boundaries from the root.

Guards with DI

Guards can use dependency injection. Assigning ctx.user needs a user field on RequestContext, declared once with module augmentation:

typescript
@Injectable()
class AuthGuard implements CanActivate {
  private tokenService = inject(TokenService)

  async canActivate(ctx: RequestContext): Promise<boolean> {
    const header = ctx.req.headers.get('authorization')
    if (!header?.startsWith('Bearer ')) {
      throw new UnauthorizedException()
    }

    const user = await this.tokenService.verify(header.slice(7))
    if (!user) throw new UnauthorizedException()

    ctx.user = user
    return true
  }
}

A guard used straight in @UseGuard() belongs to no module: TokenService must be visible from the module of every controller that uses AuthGuard - see Guards and modules.

Parameterized guards

Create guard factories for reusable logic:

typescript
function Roles(...roles: string[]) {
  class RolesGuard implements CanActivate {
    canActivate(ctx: RequestContext) {
      return ctx.user !== undefined && roles.includes(ctx.user.role)
    }
  }
  return RolesGuard
}

Combine multiple guards:

typescript
@Delete('/:id')
@UseGuard(AuthGuard, Roles('admin'))
remove(ctx: RequestContext) {
  return { deleted: true }
}

Guards execute in order. If AuthGuard fails, Roles is never called.

Guards and modules

Guards follow the module boundaries one of two ways, depending on whether a module declares them.

A guard a module declares

A guard listed in providers is a provider of that module. Its own inject() calls are checked from that module, and a controller in another module uses it like any other provider - the guard's module exports it, and the controller's module imports that module:

typescript
@Module({ providers: [AdminGuard, TokenService], exports: [AdminGuard] })
class AdminModule {}

@Module({ imports: [AdminModule], controllers: [ReportsController] }) // @UseGuard(AdminGuard)
class ReportsModule {}

Without the export or the import, startup fails:

ReportsController (ReportsModule) uses AdminGuard (AdminModule):
  - add AdminGuard to AdminModule `exports`
  - add AdminModule to ReportsModule `imports`

A declared guard can be overridden in tests; one no module declares cannot.

A guard no module declares

A class put straight into @UseGuard() - your own, AuthGuard(JwtAuth) from @miiajs/auth, the guard @RateLimit() installs - belongs to no module. The app builds one instance of it and checks what it injects from the module of every controller that uses it, so the same guard on the controllers of two modules has to see its dependencies from both:

AuthGuard(JwtAuth) (guard of UsersController in UsersModule) injects JwtAuth (AuthModule):
  - add JwtAuth to AuthModule `exports`
  - add AuthModule to UsersModule `imports`

What guards across the app depend on - the auth provider, the rate-limit options - is usually exported by a global module, so every controller module sees it without an import (see the auth setup).

Only the guard's own inject() calls are checked this way: what it reaches through another guard no module declares, injected into it, is not checked against the modules that use it. inject(Resolver) in such a guard returns the resolver of the root, whichever controller uses the guard.

Global guards

A global guard is checked from the root, which sees what the modules passed to app.register() export and what global modules export. A guard no module declares must see what it injects from there:

RateLimitGuard (global guard, checked from the root) injects RateLimitOptions (RateLimitModule in AppModule), which is not global:
  - make it global: RateLimitModule.configure(options, { global: true })
  - or pass RateLimitModule to app.register()

A guard declared in a module must be exported to the root:

typescript
@Module({ providers: [ApiKeyGuard], exports: [ApiKeyGuard] })
class AppModule {}

const app = new Miia().register(AppModule).useGuard(ApiKeyGuard)

A guard that is both global and on a controller is checked from both sides. A guard registered with app.provide() has no module either, but it is visible to every module, and what it injects is checked from the root.

Skipping guards

Use @SkipGuard() to exclude specific guards at compile time. The guard middleware is not added to the route pipeline at all - zero runtime overhead:

typescript
import { SkipGuard } from '@miiajs/core'

@Controller('/posts')
@UseGuard(AuthGuard)
class PostController {
  @Get('/')
  @SkipGuard(AuthGuard)  // AuthGuard is not applied to this route
  list() { return [] }

  @Get('/:id')            // AuthGuard applies normally
  findOne(ctx: RequestContext) { ... }
}

@SkipGuard works with direct guard classes, guards built by @miiajs/auth's AuthGuard(...) factory (skip them by naming the factory - see Skipping), and global guards registered via app.useGuard(). Multiple guards can be skipped: @SkipGuard(GuardA, GuardB). Naming a factory removes every guard it built on that route - global, controller and method level alike - so @SkipGuard(AuthGuard) next to @UseGuard(AuthGuard(ApiKeyAuth)) leaves the route without auth. To skip just one of them, name that guard class - see Skipping.

typescript
@Injectable()
class GlobalAuth implements CanActivate {
  canActivate(_ctx: RequestContext) { return false }
}

const app = new Miia().useGuard(GlobalAuth).register(AppModule)

@Controller('/webhooks')
class WebhookController {
  @Post('/stripe')
  @SkipGuard(GlobalAuth) // bypass the app-level guard for this endpoint
  stripe(ctx: RequestContext) {
    return { received: true }
  }
}

Declaring rejection codes

A guard rejects with whatever status its logic produces - 401 from an auth check, 403 from a role check, 429 from a rate limiter. Nothing can infer that from canActivate(), so the guard class states it with the GUARD_RESPONSES symbol from @miiajs/core:

typescript
import { GUARD_RESPONSES, UnauthorizedException } from '@miiajs/core'
import type { CanActivate, RequestContext } from '@miiajs/core'

class JwtAuthGuard implements CanActivate {
  static [GUARD_RESPONSES] = [401]

  canActivate(ctx: RequestContext) {
    const header = ctx.req.headers.get('authorization')
    if (!header?.startsWith('Bearer ')) throw new UnauthorizedException()
    return true
  }
}

The marker is documentation-only: @miiajs/swagger reads it when it builds the OpenAPI document and adds those responses to every route the guard protects. It has no effect on the request pipeline, and a guard without the marker contributes no responses to the spec.

Each entry is a status code or an object with a description:

typescript
import {
  ForbiddenException,
  GUARD_RESPONSES,
  UnauthorizedException,
  type GuardResponseDeclaration,
} from '@miiajs/core'

class RolesGuard implements CanActivate {
  static [GUARD_RESPONSES]: GuardResponseDeclaration[] = [
    { status: 401, description: 'Not authenticated' },
    { status: 403, description: 'Role mismatch' },
  ]

  canActivate(ctx: RequestContext) {
    if (!ctx.user) throw new UnauthorizedException()
    if (ctx.user.role !== 'admin') throw new ForbiddenException()
    return true
  }
}

Guards shipped by MiiaJS packages already carry their codes: AuthGuard from @miiajs/auth declares 401, and the guards in @miiajs/rate-limit declare 429. Installing those packages is enough - you write GUARD_RESPONSES only on your own guards.

Codes are collected from all three layers on a route - global, controller, and method guards. @SkipGuard(...) removes a guard's codes along with the guard itself, and so does @SkipRateLimit(). An explicit @ApiResponse for the same status always wins over the guard's declaration.

Guard execution order

Global guards (app.useGuard(), filtered by @SkipGuard)
  -> Controller guards (@UseGuard on class)
  -> Controller middleware (@Use on class)
  -> Route guards (@UseGuard on method)
  -> Route middleware (@Use on method)
  -> Route schemas (params -> query -> body)
  -> Route handler

Guards and route middleware share one pipeline, so a controller's @Use middleware runs before the method's guards. Global guards run only on a matched route; global middleware from app.use() wraps all of it - see Middleware → Execution order.

Edit this page on GitHub