Migrating from Vanilla Node.js Express to NestJS: A Step-by-Step Guide

If you've been working with a vanilla Node.js Express project and want to use the power and features of NestJS, this step-by-step guide will help you migrate your code smoothly. 

Step 1: Setting up NestJS

First, install the NestJS CLI globally by running the following command:

npm install -g @nestjs/cli
Then, generate a new NestJS project using the CLI:
nest new project-name
Step 2: Migrating Express Routes

Identify your existing Express routes and controllers. Create corresponding controllers in NestJS using decorators. Move the route handling logic from Express to the newly created controllers. For example, let's migrate a simple "Hello World" route.
// Express Route
app.get('/hello', (req, res) => {
  res.send('Hello World');
});
// NestJS Controller
import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
  @Get('/hello')
  getHello(): string {
    return 'Hello World';
  }
}
Step 3: Dependency Injection and Provider

Identify any external dependencies in your Express project. Define providers in NestJS to handle these dependencies. Utilize NestJS's dependency injection system to inject dependencies into controllers and services. Here's an example:
// Express Example
const userService = new UserService();

app.get('/users', (req, res) => {
  const users = userService.getUsers();
  res.json(users);
});
// NestJS Example
import { Controller, Get } from '@nestjs/common';
import { UserService } from './user.service';

@Controller()
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('/users')
  getUsers() {
    return this.userService.getUsers();
  }
}
Step 4: Middleware and Interceptors
Identify any middleware functions used in your Express project. Convert these middleware functions to NestJS middleware or global interceptors. Here's an example of migrating middleware:

// Express Middleware
app.use((req, res, next) => {
  console.log('Request received');
  next();
});
// NestJS Middleware
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Request received');
    next();
  }
}
Conclusion
    By following this step-by-step guide, you can seamlessly transition your vanilla Node.js Express project to NestJS, taking advantage of its modular structure, dependency injection, powerful decorators, and integrated features. NestJS provides a solid foundation for building scalable and maintainable Node.js applications.

Happy coding with NestJS!