0
0
NestJSframework~5 mins

First NestJS application

Choose your learning style9 modes available
Introduction

NestJS helps you build server apps easily using familiar patterns. It organizes your code so it's clear and simple to manage.

You want to create a backend server for a website or app.
You need a structured way to handle requests and responses.
You want to use TypeScript with a framework that supports modular code.
You want to build APIs that are easy to maintain and test.
Syntax
NestJS
import { Module } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

@Controller()
class AppController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

bootstrap();

@Controller() marks a class to handle incoming requests.

@Get() marks a method to respond to GET requests.

Examples
This example shows a controller with a route prefix 'greet'. The GET request to '/greet' returns 'Hi there!'.
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('greet')
class GreetController {
  @Get()
  sayHi(): string {
    return 'Hi there!';
  }
}
A simple module with no controllers yet. Modules group related parts of your app.
NestJS
import { Module } from '@nestjs/common';

@Module({
  controllers: [],
})
class EmptyModule {}
Sample Program

This is a complete NestJS app. It creates a server listening on port 3000. When you visit http://localhost:3000, it shows 'Hello World!'.

NestJS
import { Module } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

@Controller()
class AppController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Application is running on: http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Use npm run start or node dist/main.js to run your NestJS app after building.

Controllers handle routes; modules organize controllers and providers.

Port 3000 is the default, but you can change it in app.listen().

Summary

NestJS uses controllers and modules to organize backend code.

Controllers respond to HTTP requests with simple methods.

The bootstrap function starts the server and listens for requests.