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
POSTanswers201without being told;@HttpCode()changes any status. - Query and path parameters arrive as strings.
ParseIntPipedoes what Spring's type conversion does, and answers400for?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 throwNotFoundException,ConflictExceptionand friends for error statuses. They play the role ofResponseStatusException.
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({
isGlobal: true,
envFilePath: [`.env.${process.env.NODE_ENV ?? 'development'}`, '.env'],
validationSchema: z.object({
ORDERS_PAGE_SIZE: z.coerce.number().int().positive().default(20),
PAYMENTS_URL: z.url(),
}),
load: [ordersConfig],
}),
],
})
export class AppModule {}
There are no profiles as such. NODE_ENV picks the file, and the first file in envFilePath that defines a variable wins, so .env.production overrides .env the way application-prod.yml overrides application.yml. The schema is checked at startup, so a missing or malformed variable stops the deploy instead of failing the first request that reads it.
@Value("${...}") becomes config.get('PAYMENTS_URL'), or getOrThrow() for a value that must be there. @ConfigurationProperties becomes registerAs(), injected with its type:
export default registerAs('orders', () => ({
pageSize: Number(process.env.ORDERS_PAGE_SIZE ?? 20),
paymentsUrl: process.env.PAYMENTS_URL!,
}));
// in a service
constructor(@Inject(ordersConfig.KEY) private readonly config: ConfigType<typeof ordersConfig>) {}
And @ConditionalOnProperty has a cousin in ConditionalModule.registerWhen(FeatureModule, 'FEATURE_ENABLED'), which imports a module only when an environment variable allows it.
Spring Data becomes TypeORM (or Drizzle)
TypeORM is the closest thing to JPA in Node: entities are decorated classes, and each module registers repositories for the entities it uses.
@Entity
@Table(name = "orders")
public class Order {
@Id @GeneratedValue(strategy = GenerationType.UUID)
private String id;
@Column(nullable = false)
private String customerId;
@Enumerated(EnumType.STRING)
private OrderStatus status;
}
@Entity('orders')
export class Order {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
customerId: string;
@Column({ type: 'varchar', default: 'pending' })
status: 'pending' | 'paid' | 'shipped';
}
@Module({
imports: [TypeOrmModule.forFeature([Order])],
providers: [OrdersService],
controllers: [OrdersController],
})
export class OrdersModule {}
@Injectable()
export class OrdersService {
constructor(@InjectRepository(Order) private readonly orders: Repository<Order>) {}
findPending(customerId: string) {
return this.orders.findBy({ customerId, status: 'pending' });
}
}
Two things you'll miss. Derived query methods: findByCustomerIdAndStatus becomes findBy() with an object of conditions, and anything bigger goes through the query builder. And @Transactional: transactions are a callback that commits when it resolves and rolls back when it throws.
return this.dataSource.transaction(async (manager) => {
const order = await manager.save(Order, { customerId: dto.customerId });
await manager.insert(OrderItem, dto.items.map((item) => ({ ...item, orderId: order.id })));
return order;
});
@InjectRepository(Order) names the entity for the same reason interfaces don't work as tokens: Repository<Order> and Repository<Customer> are the same class at runtime.
If you like jOOQ more than Hibernate, Drizzle is the other first-party option (@nestjs/drizzle): tables are plain TypeScript, queries look like SQL, and every result type is inferred from the schema, with no entity classes. MikroORM, whose unit of work and identity map are the closest thing to a JPA persistence context, Prisma and Mongoose all work too. Flyway or Liquibase migrations become the ORM's own migration tool, run as a separate step before the new version starts.
Scheduling, events and background jobs
@Scheduled becomes @Cron() from @nestjs/schedule. Same six fields, seconds first:
@Scheduled(cron = "0 0 2 * * *")
public void exportInvoices() { ... }
@Injectable()
export class InvoiceJobs {
@Cron('0 0 2 * * *')
@OnOneInstance({ key: 'invoices:export' })
async exportInvoices() {
// ...
}
}
A Nest cron job runs on every replica, exactly like @Scheduled. The second decorator is the ShedLock part: @OnOneInstance() from @nestjs/locks takes a lease in a store every instance shares, so the job runs on one of them. fixedRate becomes @Interval(ms).
ApplicationEventPublisher and @EventListener become @nestjs/event-emitter:
// publishing
constructor(private readonly events: EventEmitter2) {}
this.events.emit('order.created', new OrderCreatedEvent(order.id));
// listening, in any provider
@OnEvent('order.created')
handleOrderCreated(event: OrderCreatedEvent) { ... }
@Async has no counterpart, and you won't miss it: database calls and HTTP requests in Node are already asynchronous, so an async method that awaits them doesn't hold a thread while it waits. Work that should leave the request entirely, like sending emails or building reports, goes on a queue with @nestjs/bullmq, which plays the role a JMS or RabbitMQ listener does in Spring.
Calling other services
RestClient and WebClient become HttpClient from @nestjs/http-client, built on Node's own fetch. Each upstream service gets a named client with its base URL and timeout:
@Module({
imports: [HttpClientModule.register({ name: 'payments', baseUrl: process.env.PAYMENTS_URL, timeout: '5s' })],
providers: [PaymentsClient],
})
export class PaymentsModule {}
@Injectable()
export class PaymentsClient {
constructor(@InjectHttpClient('payments') private readonly http: HttpClient) {}
async getStatus(orderId: string) {
const { data } = await this.http.get<PaymentStatus>(`/payments/${orderId}`);
return data;
}
}
Resilience4j's timeouts, retries and circuit breakers become @nestjs/resilience. You describe each dependency once as a preset, and routes opt in with a decorator:
ResilienceModule.forRoot({
presets: {
carrier: {
timeout: '2s',
retry: { attempts: 2 },
circuitBreaker: { failureRateThreshold: 50, minimumCalls: 10, openDuration: '30s' },
},
},
}),
// in a controller
@Get('quotes')
@Resilience('carrier')
getQuotes(@Query('orderId') orderId: string, @Signal() signal: AbortSignal) {
return this.shippingService.getQuotes(orderId, signal);
}
@Signal() injects an AbortSignal that fires when the attempt times out; pass it to the HTTP call and the request is actually cancelled, not just abandoned. Retries only apply to safe methods like GET by default, so a retried POST never charges a card twice. Inside services, where decorators don't apply, the same presets are available as policy objects.
Health, logs and OpenAPI
Actuator's health endpoints become a controller using @nestjs/terminus, with separate liveness and readiness checks for Kubernetes:
@Public()
@Controller('health')
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly db: TypeOrmHealthIndicator,
) {}
@Get('live')
@HealthCheck()
live() {
return this.health.check([]);
}
@Get('ready')
@HealthCheck()
ready() {
return this.health.check([() => this.db.pingCheck('database')]);
}
}
(@Public() because @nestjs/authentication closes every route, and probes don't sign in.)
For logging, private static final Logger log = LoggerFactory.getLogger(OrdersService.class) becomes private readonly logger = new Logger(OrdersService.name). The built-in ConsoleLogger writes JSON with json: true, which is what your log pipeline wants in production; pino and winston plug in if you already have a preference. For the metrics and traces Micrometer and an APM agent give you, nest new offers to set up NestJS Observe, which reports requests, jobs and errors in terms of your controllers and providers.
springdoc becomes @nestjs/swagger:
const config = new DocumentBuilder().setTitle('Orders API').setVersion('1.0').build();
SwaggerModule.setup('api', app, () => SwaggerModule.createDocument(app, config));
Swagger UI is at /api. Its compiler plugin reads property types and optionality from your DTOs at build time, so you don't put @ApiProperty() on every field, and Zod schemas describe the document too.
Testing
@WebMvcTest with @MockitoBean becomes a testing module with a fake provider, and MockMvc becomes Supertest:
@WebMvcTest(OrdersController.class)
class OrdersControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrdersService ordersService;
@Test
void returnsAnOrder() throws Exception {
when(ordersService.findOne("42")).thenReturn(new Order("42", "c-1", OrderStatus.PENDING));
mvc.perform(get("/orders/42")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value("42"));
}
}
describe('OrdersController', () => {
let app: INestApplication;
const ordersService = { findOne: vi.fn() };
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [OrdersController],
providers: [{ provide: OrdersService, useValue: ordersService }],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(() => app.close());
it('returns an order', async () => {
ordersService.findOne.mockResolvedValue({ id: '42', customerId: 'c-1', status: 'pending' });
const response = await request(app.getHttpServer()).get('/orders/42').expect(200);
expect(response.body.id).toBe('42');
});
});
For a @SpringBootTest, import AppModule instead and swap individual providers with .overrideProvider(OrdersService).useValue(fake). And for a plain unit test you need no framework at all: a provider is a class, so new OrdersService(fakeRepository) works.
Shipping it
A Spring Boot service ships as a fat jar or an image built from one. A Nest service ships as compiled JavaScript plus its node_modules, almost always in a container. A production Dockerfile, built in one stage and run in another:
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "--enable-source-maps", "dist/main.js"]
Three things to check that Spring handled for you:
-
Shutdown hooks. Spring runs
@PreDestroyonSIGTERMwithout being asked. Nest runsonModuleDestroy()andonApplicationShutdown()only afterapp.enableShutdownHooks()inmain.ts. -
The process gets the signal. Use the exec form,
CMD ["node", ...], notnpm start, which doesn't reliably forward signals to Node. -
Memory. Node's heap limit is a flag, like
-Xmx. Set--max-old-space-sizebelow the container's memory limit, so running out of memory is a JavaScript error with a stack trace instead of a silentOOMKilled.
Moving over without a rewrite
You don't have to move a Spring codebase to Nest to start using Nest. The pattern I'd recommend:
-
Start with a new service, not a port. The next service you need gets written in Nest, behind the same gateway or ingress, using the same database conventions and the same auth (a guard can verify the JWTs your Spring services already issue, for example with
@nestjs/jwt). -
Share the contract, not the code. springdoc already publishes an OpenAPI document for your Spring services; generate a TypeScript client from it for the Nest service, and the other way round with
@nestjs/swagger. - Move existing endpoints only when you'd rewrite them anyway. A route that's being redesigned can move to the Nest service behind the gateway, one path at a time.
What's actually different
The syntax takes a week. These take longer, so I'd rather you hear them from me than find them in production.
One thread. Spring MVC gives each request a thread. Node.js runs all of your code on one thread with an event loop: while a request waits for Postgres, the others run. That's why a modest Node process handles thousands of concurrent connections without any pool tuning, the same promise WebFlux and virtual threads make. The flip side is that CPU-heavy work in a handler, like hashing a big file or a long synchronous loop, blocks every other request in the process. Push that work to a queue (@nestjs/bullmq) or a worker thread, and scale with more processes instead of more threads. If your service is mostly number crunching, the JVM is the better runtime, and I'd say so to anyone.
No ThreadLocal, and request scope is contagious. Per-request state goes in AsyncLocalStorage, which follows a request through every await. Don't reach for request-scoped providers to get the current user: Spring injects a request-scoped bean into singletons through a proxy, but Nest has no proxies, so a request-scoped provider makes everything that injects it request-scoped too, all the way up to the controller, rebuilt on every request. Keep providers singletons.
No proxies, no AOP. Nest's DI reads constructor types from metadata the TypeScript compiler emits, once, at startup. There's no bytecode generation and no proxy around your beans. You lose @Transactional, @Cacheable and @Retryable on arbitrary methods, and you also lose the self-invocation trap that comes with them. Cross-cutting concerns live in interceptors, guards and pipes around route handlers, and in decorators from packages like @nestjs/resilience (on handlers) and @nestjs/locks (on scheduled jobs).
Types are a compile-time check. Interfaces and generic type arguments don't exist at runtime, which is why injection uses abstract classes or tokens, and why a request body, a database row or a message from another service is only as typed as the code that validated it.
Decorators are functions. A Java annotation is passive metadata read by reflection. A TypeScript decorator runs when the class is defined, and Nest's decorators use that moment to record what Nest reads at startup. You'll rarely notice, but it's why a decorator can take any expression as an argument.
Numbers are doubles. There's no BigDecimal. Keep money in integer cents, or use a decimal library and your database's numeric type, which most drivers return as a string anyway.
ES modules. A new project imports local files with a .js extension, even from .ts files, because that's the name of the compiled file. It looks wrong for about a day.
When I'd stay on Spring
To be fair to Spring: if you have a large, healthy Spring codebase, a rewrite to get TypeScript is rarely worth it. If the work is CPU-bound, or depends on a JVM library with no Node equivalent, stay. And Spring's ecosystem for things like batch processing is deeper than anything in Node.
Nest is a good fit when the new thing is a new service, when the people building it also write the TypeScript frontend, or when you want one language from the browser to the database without giving up the structure you're used to.
Getting started
npx @nestjs/cli new orders-api
cd orders-api
npm run start:dev
Then nest g resource orders, and you have a module, controller, service, DTOs and tests to compare against the Spring version in your head. The Coming from Spring Boot page in the docs keeps this mapping as a reference, with a link from each row to its full chapter.
If something there doesn't match how you'd do it in Spring, tell me. It's written for you, and it's easy to fix.
Coming from .NET instead? Here's the same tour for ASP.NET Core: NestJS for ASP.NET Core developers.
Top comments (0)