0
0
NestjsConceptBeginner · 3 min read

What is Controller in NestJS: Definition and Usage

In NestJS, a controller is a class responsible for handling incoming HTTP requests and returning responses. It acts like a traffic manager, directing requests to the right service or logic inside your app.
⚙️

How It Works

Think of a NestJS controller as a receptionist in an office. When someone (a client) sends a request, the receptionist listens and decides what to do with it. The controller receives the request, understands what is needed, and then calls the right service or function to handle the task.

Controllers use decorators like @Controller() to define the route path and @Get(), @Post(), etc., to specify how to respond to different HTTP methods. This setup helps organize your app by separating the request handling from the business logic.

💻

Example

This example shows a simple NestJS controller that responds to a GET request at the root path with a welcome message.

typescript
import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  getHello(): string {
    return 'Hello from NestJS controller!';
  }
}
Output
Hello from NestJS controller!
🎯

When to Use

Use controllers whenever you need to handle HTTP requests in your NestJS app. They are perfect for building APIs, web apps, or any server-side logic that responds to client requests.

For example, if you build a blog, controllers handle requests like fetching posts, creating new posts, or deleting posts. They keep your app organized by separating how requests are received from how data is processed.

Key Points

  • Controllers handle incoming HTTP requests and send responses.
  • They use decorators to define routes and HTTP methods.
  • Controllers separate request handling from business logic.
  • They keep your application organized and maintainable.

Key Takeaways

Controllers in NestJS manage incoming HTTP requests and responses.
Use decorators like @Controller and @Get to define routes and methods.
Controllers help keep your app organized by separating concerns.
They are essential for building APIs and server-side applications.