Skip to content

NestJS Backend Architecture Choices: When a Spring Developer Meets Node.js

Interactive Diagram

μƒˆ νƒ­ β†—

When building a Backend with Node.js, you may start with Express and then find yourself wondering how to define the structure as the project grows. For a team accustomed to Spring-based Backend development, NestJS is a very natural choice. This article covers the reasons for choosing NestJS as a Backend Framework and the architectural patterns applied in practice.

When evaluating Backend Frameworks for Node.js v16.15.x stable and later, NestJS had clear strengths.

  • OOP + FP combination: You can use familiar Spring concepts such as Dependency Injection, Module separation, and the Decorator pattern as-is.
  • Built-in TypeScript support: It provides type safety and IDE support, which are difficult to handle in Pure JavaScript, at the framework level.
  • Automatic boilerplate generation with the CLI: nest generate resource generates a REST API’s Controller, Service, DTO, and Entity all at once, and even auto-imports them into AppModule.

NestJS module graph: the application module imports users, orders and chat modules, with feature modules 1 and 2 under orders and feature module 3 under chat Source: NestJS docs, Modules, Kamil Mysliwiec and NestJS contributors, MIT

  • Initial evaluation: https://github.com/{organization}/backend-nestjs-poc
  • Feature validation: https://github.com/{organization}/backend-nestjs-validation
    • ORM: TypeORM, Prisma
    • ODM: Mongoose
    • Redis-based Cache and Queue usage

The CLI is powerful for initial framework setup and defining a standard structure, but when adding APIs within an already-provided framework, there is no need to use it. There are often cases where it is faster to copy and modify an existing module structure.

Terminal window
npm i -g @nestjs/cli

Running nest generate resource automatically generates a REST API + CRUD endpoint.

  • Directorysrc/
    • Directoryusers/
      • Directorydto/
        • create-user.dto.ts
        • update-user.dto.ts
      • Directoryentities/
        • user.entity.ts
        • user.provider.ts
      • users.controller.ts
      • users.module.ts
      • users.service.ts

The module, controller, service, dto, and entity are generated all at once and automatically imported into AppModule.

Generate a Nest element.
Schematics available on @nestjs/schematics collection:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ name β”‚ alias β”‚ description β”‚
β”‚ application β”‚ application β”‚ Generate a new application workspace β”‚
β”‚ class β”‚ cl β”‚ Generate a new class β”‚
β”‚ controller β”‚ co β”‚ Generate a controller declaration β”‚
β”‚ decorator β”‚ d β”‚ Generate a custom decorator β”‚
β”‚ filter β”‚ f β”‚ Generate a filter declaration β”‚
β”‚ gateway β”‚ ga β”‚ Generate a gateway declaration β”‚
β”‚ guard β”‚ gu β”‚ Generate a guard declaration β”‚
β”‚ interceptor β”‚ in β”‚ Generate an interceptor declaration β”‚
β”‚ interface β”‚ interface β”‚ Generate an interface β”‚
β”‚ middleware β”‚ mi β”‚ Generate a middleware declaration β”‚
β”‚ module β”‚ mo β”‚ Generate a module declaration β”‚
β”‚ pipe β”‚ pi β”‚ Generate a pipe declaration β”‚
β”‚ provider β”‚ pr β”‚ Generate a provider declaration β”‚
β”‚ resolver β”‚ r β”‚ Generate a GraphQL resolver declaration β”‚
β”‚ service β”‚ s β”‚ Generate a service declaration β”‚
β”‚ library β”‚ lib β”‚ Generate a new library within a monorepo β”‚
β”‚ sub-app β”‚ app β”‚ Generate a new application within a monorepo β”‚
β”‚ resource β”‚ res β”‚ Generate a new CRUD resource β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Separating Configuration: Managing .env Files by Environment

Section titled β€œSeparating Configuration: Managing .env Files by Environment”

NestJS provides framework-level configuration management through the @nestjs/config package. Internally, it uses dotenv and is accessed through process.env.

  • Directoryconfig/
    • .dev.env
    • .stg.env
    • .prd.env
    • .local.env
Dockerfile
ENV NODE_ENV=dev
app.module.ts
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath:
'config/' +
(process.env.NODE_ENV === 'prd'
? '.prd.env'
: process.env.NODE_ENV === 'stg'
? '.stg.env'
: process.env.NODE_ENV === 'dev'
? '.dev.env'
: '.local.env'),
}),
// ...
],
})
export class AppModule {}

This determines the environment at container build time, so there is no need to change configuration at runtime.

Logger Configuration: Winston + Access Logging Middleware

Section titled β€œLogger Configuration: Winston + Access Logging Middleware”

NestJS provides a built-in logger in @nestjs/common, but in practice, use Winston and implement Access Logging Middleware separately to record every request and response in a structured form.

Applying LoggerModule and WinstonMiddleware (app.module.ts)

Section titled β€œApplying LoggerModule and WinstonMiddleware (app.module.ts)”
app.module.ts
import { LoggerModule, WinstonMiddleware } from 'common-modules';
@Module({
imports: [
LoggerModule,
// ...
],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WinstonMiddleware).forRoutes('*');
}
}

Separate common modules into their own repository and reuse them across multiple Backend projects.

Swagger / OpenAPI: Automatic API Documentation Generation

Section titled β€œSwagger / OpenAPI: Automatic API Documentation Generation”

NestJS automatically generates Swagger/OpenAPI documentation based on Decorators. Adding metadata to Controllers and DTOs updates the API documentation in real time.

main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
const config = new DocumentBuilder()
.setTitle('Backend API')
.setDescription('Backend REST API documentation')
.setVersion('1.0')
.addTag('users')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

Accessing the /api endpoint displays Swagger UI, where you can inspect all endpoints, DTOs, and response schemas.

import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ description: 'user name', example: 'noisonnoiton' })
name: string;
@ApiProperty({ description: 'email', example: 'user@example.com' })
email: string;
}

This metadata can be used not only for Swagger documentation but also as validation decorators.

  • Reduce CLI dependence: Use the CLI only to define the initial structure; afterwards, it is often faster to copy and modify files manually.
  • Separate common modules: Split shared functionality such as Logger, Auth, and Config into separate packages and reuse them across multiple projects.
  • Determine environment variables at container build time: Runtime configuration changes are risky and difficult to debug.
  • Swagger is essential: Because API documentation always stays in sync with code, the cost of maintaining separate documentation disappears.

For how the actual Database connection was selected on top of this architecture, continue to Node.js ORM Comparison: TypeORM, Sequelize, Prisma. Redis usage patterns are covered in NestJS Redis Patterns.