Menu
CoddyTech

Registering a Controller

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 3 of 24.

A controller’s decorators describe its routes, but Nest also needs to know that the controller belongs to the application. A module lists its controllers in a controllers array.

@Module({controllers: [BooksController]})
export class BooksModule {}

An import makes the class name available in this file. The controllers array registers it with Nest. Both are needed. Your task tracker already imports TasksModule in AppModule. Add a separate controller alongside that module without removing the existing imports: one module can import other modules and register its own controllers.

challenge icon

Challenge

Easy

Continue your task tracker. A new file, src/health.controller.ts, supplies HealthController. In src/app.module.ts, import that class and register it in AppModule’s controllers array. Keep TasksModule in imports.

Try it: GET /health returns 200 and {"ready":true}. GET /tasks still returns the three tasks. GET /missing remains 404.

Try it yourself

import { Module } from '@nestjs/common';
import { TasksModule } from './tasks/tasks.module';

@Module({
    imports: [TasksModule],
})
export class AppModule {}

All lessons in TypeScript and NestJS

Practice on your own: Express playground