Nest JS: Create a new Controller

Creating a new Controller in the nest JS app. How to create a Controller in nest JS?

Controllers in the nest js are basically responsible to handle the incoming requests from the client and also return responses to them.

Let’s create an auth Controller in our newly created nest js app:

Creating a new module in Nest JS – Manual way

As an example, here we are creating a controller for the auth functionality of our app.

  • In the src folder create folder named auth
  • Inside the auth folder we can create the module file : auth.controller.ts
    • Add basic boilerplate code for the auth controller
    import { Controller } from "@nestjs/common";
    
    @Controller()
    export class AuthController{}

    Adding the controller to the module

    app.module.ts

    import { Module } from '@nestjs/common'
    import { AuthController } from './auth.controller';
    import { AuthService } from './auth.service';
    @Module({
        controllers: [AuthController],
        providers: [AuthService]
        
    })
    export class AuthModule { }
    nest js : Adding the controller to the module

    Dependency injection: Connecting Provider to the controller

    import { Controller } from "@nestjs/common";
    import { AuthService } from "./auth.service";
    
    @Controller()
    export class AuthController{
        constructor(private authService: AuthService) {}
    }

    Creating Basic Routes – Using Nest JS Controller

    For the auth we are creating basic routes for the login and sign up. As of now just returning a sample text when the route is hit.

    import { Controller, Post } from "@nestjs/common";
    import { AuthService } from "./auth.service";
    
    @Controller('auth')
    export class AuthController{
        constructor(private authService: AuthService) {}
        @Post('signup')
        signup() {
            return "Im sign up"
        }
        @Post('login')
        login() {
            return "Im login"
        }
    }

    Result: (testing routes using POSTMAN)

    SignUp POST Route:

    Login POST Route:

    Related:

    About the Author: smartcoder

    You might like

    Leave a Reply

    Your email address will not be published. Required fields are marked *