If your team writes Spring Boot and is about to build something in TypeScript (a new service next to a frontend that's already in TypeScript, a backend for a product that's moving off the JVM, or just a team that wants one language), the Node.js world can look like a pile of small libraries you're expected to assemble yourself. Express, a validation library, a DI container someone picked, a folder structure someone invented. That's the part that usually puts Spring developers off, and it's fair.

Nest is the framework that takes that decision away. Its architecture came from Angular rather than from Spring, but the two ended up close, because they solve the same problem: a container that creates your classes and wires them through constructors, controllers and services in layers, decorators that read like annotations, and first-party modules for configuration, validation, security, scheduling, health checks and OpenAPI. Most of what you know carries over.

This post is the tour I'd give a Spring team on day one: the tools, the structure, each Spring feature and its Nest counterpart with code on both sides, how it ships, and the differences that will actually bite.

The short version

Spring Boot Nest
Spring Initializr, Maven or Gradle nest new, npm
@Service, @Component @Injectable() classes, listed in a module
@Configuration + @Bean a factory provider (useFactory)
@Qualifier an injection token and @Inject()
@PostConstruct, @PreDestroy onModuleInit(), onApplicationShutdown()
@RestController, @GetMapping @Controller(), @Get()
Servlet filters, HandlerInterceptor middleware, guards, interceptors
Bean Validation a validation pipe, with class-validator or Zod
@RestControllerAdvice an exception filter
Spring Security @nestjs/authentication and @nestjs/authorization
application.yml, profiles, @ConfigurationProperties @nestjs/config
Spring Data JPA TypeORM (@nestjs/typeorm) or Drizzle (@nestjs/drizzle)
@Scheduled, ShedLock @nestjs/schedule, @nestjs/locks
@EventListener @nestjs/event-emitter
RestClient, WebClient @nestjs/http-client
Resilience4j @nestjs/resilience
Actuator health @nestjs/terminus
springdoc-openapi @nestjs/swagger
@WebMvcTest, @SpringBootTest @nestjs/testing with Supertest

Every row has its own section below. The docs have the same mapping as a reference page, with a link to the full chapter for each row: Coming from Spring Boot.

Your tools, translated

Before any code, here's what replaces the things around it:

Spring world Nest world
JDK Node.js (a current LTS release)
Maven or Gradle, pom.xml npm, package.json
Maven Central the npm registry
Spring Initializr npx @nestjs/cli new
mvn spring-boot:run, DevTools npm run start:dev, which restarts on every save
mvn package, a fat jar npm run build (the TypeScript compiler, or SWC for speed), a dist/ folder plus node_modules
javac tsc
JUnit and Mockito Vitest, with its own mocks
Lombok not needed: constructor parameter properties replace the boilerplate
Jackson nothing: JSON is the language's native format
IntelliJ IDEA WebStorm, or VS Code
A multi-module build a Nest workspace: nest generate app and nest generate library

npm run start:debug starts the app with the Node inspector attached, and both editors above connect to it the way IntelliJ connects to a JVM debug port.

Project layout

nest new orders-api gives you a small src/ folder and asks two questions: ES modules or CommonJS (ESM is the default, with Vitest; CommonJS uses Jest), and whether to set up NestJS Observe for monitoring. As the app grows, the convention is one folder per feature, each with its module, and tests next to the code they test rather than in a parallel tree:

src/ main.ts # the main class app.module.ts # the root module orders/ orders.module.ts orders.controller.ts orders.controller.spec.ts orders.service.ts order.entity.ts create-order.dto.ts payments/ payments.module.ts ... test/ app.e2e-spec.ts # end-to-end tests 

nest g resource orders generates the orders/ folder above with CRUD routes filled in, which is the fastest way to see the structure with your own names in it.

The entry point is the counterpart of your @SpringBootApplication class:

@SpringBootApplication public class OrdersApplication { public static void main(String[] args) { SpringApplication.run(OrdersApplication.class, args); } } 
// main.ts async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(process.env.PORT ?? 3000); } await bootstrap(); 

Beans are providers, and you list them

A Spring service and the same service in Nest:

@Service public class OrdersService { private final OrdersRepository ordersRepository; public OrdersService(OrdersRepository ordersRepository) { this.ordersRepository = ordersRepository; } } 
@Injectable() export class OrdersService { constructor(private readonly ordersRepository: OrdersRepository) {} } 

Constructor injection, no @Autowired, and private readonly declares and assigns the field in one go. The one real difference is that there's no component scanning. Every provider belongs to a module, and the module lists it:

@Module({ controllers: [OrdersController], providers: [OrdersService, OrdersRepository], exports: [OrdersService], }) export class OrdersModule {} 

That looks like boilerplate at first, and I'd argue it's the best part. A module is a boundary Spring's application context doesn't have: OrdersRepository isn't exported, so no other module can inject it. In a big Spring codebase you rely on package conventions and ArchUnit tests for that. In Nest the container enforces it, and you can read what a feature exposes from one file. A module that needs OrdersService adds OrdersModule to its imports.

If a dependency can't be resolved, the app fails at startup with an error naming the class, the missing dependency and the module, much like Spring's "unsatisfied dependency" failure.

@Configuration and @bean

A @Bean method builds something you don't own, or something that needs setup:

@Configuration public class StorageConfig { @Bean public S3Client s3Client(StorageProperties properties) { return S3Client.builder().region(Region.of(properties.region())).build(); } } 

In Nest it's a factory provider. inject lists what gets passed to the factory, in order, and the factory can be async:

@Module({ providers: [ { provide: S3Client, useFactory: (config: ConfigService) => new S3Client({ region: config.getOrThrow<string>('AWS_REGION') }), inject: [ConfigService], }, ], exports: [S3Client], }) export class StorageModule {} 

And the starters? There's no auto-configuration. A package ships a module, and you import and configure it: ConfigModule.forRoot(), TypeOrmModule.forRootAsync(), ScheduleModule.forRoot(). Nothing turns on because it's on the classpath, which I think is the right trade for a language where "the classpath" is node_modules.

Interfaces and @Qualifier

This is the first thing that trips Spring developers up. In Java you inject PaymentGateway, the interface, and the container finds the implementation. TypeScript interfaces are erased when the code compiles, so there's nothing left for the container to look up. Use an abstract class as the contract: it exists at runtime, so it doubles as the injection token.

export abstract class PaymentGateway { abstract charge(orderId: string, amountInCents: number): Promise<void>; } @Module({ providers: [{ provide: PaymentGateway, useClass: StripePaymentGateway }], exports: [PaymentGateway], }) export class PaymentsModule {} // anywhere that imports PaymentsModule constructor(private readonly paymentGateway: PaymentGateway) {} 

Where you'd use @Qualifier("primary") to pick one of several beans of the same type, Nest uses a string or Symbol token and @Inject(TOKEN) on the parameter.

Scopes and lifecycle

Spring Nest
singleton (the default) Scope.DEFAULT (the default)
@Scope("prototype") Scope.TRANSIENT
@RequestScope Scope.REQUEST
@PostConstruct onModuleInit()
ApplicationRunner onApplicationBootstrap()
@PreDestroy onModuleDestroy(), onApplicationShutdown()

The defaults match, and you should keep them: almost every provider should be a singleton. Request scope works differently from Spring's, which I'll come back to under "What's actually different".

Controllers you can read without a guide

@RestController @RequestMapping("/orders") public class OrdersController { private final OrdersService ordersService; public OrdersController(OrdersService ordersService) { this.ordersService = ordersService; } @GetMapping public List<Order> findAll(@RequestParam(defaultValue = "0") int page) { return ordersService.findAll(page); } @GetMapping("/{id}") public Order findOne(@PathVariable String id) { return ordersService.findOne(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Order create(@Valid @RequestBody CreateOrderRequest request) { return ordersService.create(request); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void remove(@PathVariable String id) { ordersService.remove(id); } } 
@Controller('orders') export class OrdersController { constructor(private readonly ordersService: OrdersService) {} @Get() findAll(@Query('page', new ParseIntPipe({ optional: true })) page = 0) { return this.ordersService.findAll(page); } @Get(':id') findOne(@Param('id') id: string) { return this.ordersService.findOne(id); } @Post() create(@Body() dto: CreateOrderDto) { return this.ordersService.create(dto); } @Delete(':id') @HttpCode(204) remove(@Param('id') id: string) { return this.ordersService.remove(id); } } 

Small things:

  • Route parameters are :id.
  • A POST answers 201 without being told; @HttpCode() changes any status.
  • Query and path parameters arrive as strings. ParseIntPipe does what Spring's type conversion does, and answers 400 for ?page=abc.
  • Handlers return Promises (or plain values), and Nest awaits them and serializes the result as JSON.
  • There's no ResponseEntity. You return the body, set headers with @Header(), and throw NotFoundException, ConflictException and friends for error statuses. They play the role of ResponseStatusException.

Filters, interceptors and AOP

Spring gives you servlet filters, HandlerInterceptors and aspects. Nest has a fixed set of components around each route handler, run in this order:

Nest When it runs Spring counterpart
Middleware before routing, with the raw request a servlet Filter
Guards after routing: may the handler run? the authorization part of the security filter chain
Interceptors around the handler, with its result HandlerInterceptor, @Around advice
Pipes on each argument type conversion and validation
Exception filters when anything above throws @ControllerAdvice

Each can be bound to one handler, a whole controller or the entire app. An interceptor that logs how long each request took, the way you'd write an @Around aspect:

@Injectable() export class TimingInterceptor implements NestInterceptor { private readonly logger = new Logger(TimingInterceptor.name); intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> { const started = performance.now(); const handler = `${context.getClass().name}.${context.getHandler().name}`; return next .handle() .pipe(tap(() => this.logger.log(`${handler} took ${Math.round(performance.now() - started)} ms`))); } } 

next.handle() is your joinPoint.proceed(), as an RxJS stream of the handler's result. The difference from AOP: interceptors wrap route handlers (and message and event handlers), not arbitrary methods of any bean. More on that below.

Validation is explicit, and that's the first gotcha

Bean Validation:

public record CreateOrderRequest( @NotBlank String customerId, @NotEmpty List<@Valid OrderItem> items, @Size(max = 500) String note ) {} 

The closest Nest equivalent is a DTO class with class-validator decorators and a global ValidationPipe:

export class CreateOrderDto { @IsString() @IsNotEmpty() customerId: string; @ArrayNotEmpty() @ValidateNested({ each: true }) @Type(() => OrderItemDto) items: OrderItemDto[]; @IsOptional() @MaxLength(500) note?: string; } 
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true })); 

whitelist drops fields the DTO doesn't declare, and transform turns the body into an actual CreateOrderDto instance. An invalid body gets a 400 listing every failed rule.

If you'd rather not write classes, Nest 12 also takes a Zod (or any Standard Schema) schema per parameter, and the type is inferred from it:

export const createOrderSchema = z.object({ customerId: z.string().min(1), items: z.array(z.object({ productId: z.string(), quantity: z.int().positive() })).min(1), note: z.string().max(500).optional(), }); export type CreateOrderDto = z.infer<typeof createOrderSchema>; @Post() create(@Body({ schema: createOrderSchema }) dto: CreateOrderDto) { return this.ordersService.create(dto); } 

Here's the gotcha. In Java, Jackson builds the class you declared, so a request body is at least the right shape before validation even runs. TypeScript types are erased when the code compiles. Without a pipe, @Body() dto: CreateOrderDto is whatever JSON the client sent, with whatever fields it felt like sending. Register a validation pipe globally on day one and you never think about it again. Forget it and the compiler won't warn you.

@ControllerAdvice becomes an exception filter

Spring 6 with ProblemDetail:

@RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(OrderNotFoundException.class) public ProblemDetail handle(OrderNotFoundException exception) { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, exception.getMessage()); } } 

The same thing in Nest. @Catch() names the exception types, like @ExceptionHandler:

@Catch(OrderNotFoundError) export class OrderNotFoundFilter implements ExceptionFilter { constructor(private readonly httpAdapterHost: HttpAdapterHost) {} catch(exception: OrderNotFoundError, host: ArgumentsHost) { const { httpAdapter } = this.httpAdapterHost; const response = host.switchToHttp().getResponse(); httpAdapter.setHeader(response, 'Content-Type', 'application/problem+json'); httpAdapter.reply( response, { type: 'about:blank', title: 'Not Found', status: 404, detail: exception.message }, 404, ); } } 

Register it app-wide as a provider in the root module, { provide: APP_FILTER, useClass: OrderNotFoundFilter }, and it can inject other providers like any bean. Exceptions nobody handles become a 500 with a generic body, and the stack trace goes to the log, not to the client.

Security that's closed by default

Spring Security's default is "everything requires authentication", and you open things up with permitAll(). @nestjs/authentication works the same way: the moment you register the module, every route answers 401 unless the request carries valid credentials, and @Public() opens a route. @CurrentUser() is your @AuthenticationPrincipal.

@RestController public class MeController { @GetMapping("/me") public User me(@AuthenticationPrincipal User user) { return user; } } 
@Controller('me') export class MeController { @Get() me(@CurrentUser() user: User) { return user; } } 

Where Spring has AuthenticationProviders, the package has credential providers: one reads the session cookie, another a bearer token, another an API key, and each loads the user through your code. The user is your own object, not a UserDetails. It also ships the flows Spring applications usually end up writing by hand: sign-up, password hashing, server-side sessions, email verification and password reset links, TOTP two-factor, OpenID Connect sign-in, rotating refresh tokens and API keys. State lives in your database through a store you implement against documented interfaces.

For @PreAuthorize, @nestjs/authorization uses policy classes. The check on a route is type-checked against the policy, so a typo in an ability name doesn't compile, which is more than a SpEL string gives you:

@PostMapping @PreAuthorize("hasRole('STAFF')") public Product create(@Valid @RequestBody CreateProductRequest request) { ... } 
@Policy() export class ProductPolicy { create(user: User | null) { return !!user?.roles.includes('staff'); } } // in the controller @Post() @Can(ProductPolicy, 'create') create(@Body() dto: CreateProductDto) { ... } 

Its guard denies by default too, so a route that declares no check at all is closed, not open. Checks that depend on the record, the job you'd give @PostAuthorize, go in the service: authorizationService.authorize(OrderPolicy, 'view', user, order) throws when the policy says no.

Configuration and profiles

application.yml and profiles become .env files and environment variables through @nestjs/config. Real environment variables win over the files, which is what you want in a container:

# application.yml orders: page-size: 20 payments-url: https://payments.example.com 
@Module({ imports: [ ConfigModule.forRoot({ i...
Source:https://dev.to/nestjs/nestjs-for-spring-boot-developers-a-typescript-backend-that-will-feel-familiar-1208