DEV Community

Cover image for NestJS for ASP.NET Core developers: a TypeScript backend that will feel familiar
Kamil Mysliwiec for NestJS

Posted on Edited on

NestJS for ASP.NET Core developers: a TypeScript backend that will feel familiar

If your team writes ASP.NET Core and is about to build something in TypeScript (a service next to a frontend that's already in TypeScript, a backend for a product that's leaving .NET, 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. Coming from a framework where dotnet new webapi gives you DI, configuration, logging, validation and a request pipeline out of the box, that's a step back, and it's a fair objection.

Nest is the framework that takes those decisions for you. It has a DI container with lifetimes, attribute-style routing, a pipeline of middleware and filters, typed configuration, and first-party packages for authentication, authorization, background jobs, health checks and OpenAPI. Most of what you know carries over.

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

The short version

ASP.NET Core Nest
dotnet new webapi, NuGet nest new, npm
builder.Services.AddScoped<T>() @Injectable() classes, listed in a module
AddSingleton(sp => ...) a factory provider (useFactory)
Keyed services an injection token and @Inject()
Singleton, scoped, transient Scope.DEFAULT, Scope.REQUEST, Scope.TRANSIENT
[ApiController], [HttpGet] @Controller(), @Get()
Middleware (app.Use()) middleware
Authorization, action and exception filters guards, interceptors, exception filters
Data Annotations, FluentValidation a validation pipe, with class-validator or Zod
Authentication handlers, Identity @nestjs/authentication
Policies, IAuthorizationService @nestjs/authorization
appsettings.json, IOptions<T> @nestjs/config
EF Core TypeORM (@nestjs/typeorm) or Drizzle (@nestjs/drizzle)
BackgroundService, Hangfire lifecycle hooks, @nestjs/schedule, @nestjs/bullmq
MediatR notifications @nestjs/event-emitter
IHttpClientFactory, Polly @nestjs/http-client, @nestjs/resilience
Health checks @nestjs/terminus
ILogger<T> Logger from @nestjs/common
Swashbuckle, NSwag @nestjs/swagger
SignalR WebSocket gateways
WebApplicationFactory<T> @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 ASP.NET Core.

Your tools, translated

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

.NET world Nest world
The .NET SDK and runtime Node.js (a current LTS release)
dotnet CLI the nest CLI, plus npm
NuGet, .csproj npm, package.json
dotnet new webapi npx @nestjs/cli new
dotnet watch npm run start:dev, which restarts on every save
dotnet build, dotnet publish npm run build (the TypeScript compiler, or SWC for speed), a dist/ folder plus node_modules
Roslyn tsc
xUnit and Moq Vitest, with its own mocks
Visual Studio, Rider VS Code, or WebStorm
A solution with several projects 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 attach a debugger to it, breakpoints and all.

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 separate test project:

src/
  main.ts                    # Program.cs
  app.module.ts              # the root module
  orders/
    orders.module.ts         # what AddOrders() would register
    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
Enter fullscreen mode Exit fullscreen mode

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.

Program.cs registers services and builds the pipeline:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped<IOrdersService, OrdersService>();

var app = builder.Build();
app.MapControllers();
app.Run();
Enter fullscreen mode Exit fullscreen mode

In Nest, services are registered in modules, and main.ts only creates the app from the root module:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
Enter fullscreen mode Exit fullscreen mode

Services are providers, and modules own them

A service in both:

public class OrdersService : IOrdersService
{
    private readonly OrdersRepository _ordersRepository;

    public OrdersService(OrdersRepository ordersRepository)
    {
        _ordersRepository = ordersRepository;
    }
}
Enter fullscreen mode Exit fullscreen mode
@Injectable()
export class OrdersService {
  constructor(private readonly ordersRepository: OrdersRepository) {}
}
Enter fullscreen mode Exit fullscreen mode

Constructor injection, and private readonly works like a C# primary constructor. Where ASP.NET Core registers everything on one IServiceCollection, Nest registers providers in modules:

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

Think of a module as the AddOrders() extension method you'd write for a feature, with one addition: what it doesn't export stays private. OrdersRepository above can't be injected anywhere outside OrdersModule. In a large .NET solution you'd get that with separate projects and internal. Here 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.

Factories and library registrations

A registration that builds the instance itself, like AddSingleton(sp => new S3Client(...)), becomes 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 {}
Enter fullscreen mode Exit fullscreen mode

Libraries that you'd register with an AddXyz() extension method ship as modules you import and configure: ConfigModule.forRoot(), TypeOrmModule.forRootAsync(), ScheduleModule.forRoot().

Interfaces and keyed services

AddScoped<IOrdersService, OrdersService>() is the first thing that has no direct translation. 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) {}
Enter fullscreen mode Exit fullscreen mode

Keyed services, AddKeyedSingleton() with [FromKeyedServices("primary")], become a string or Symbol token and @Inject(TOKEN) on the parameter.

Lifetimes: the default is different

Nest has the same three lifetimes, under different names:

ASP.NET Core Nest
AddSingleton() Scope.DEFAULT, the default
AddScoped() Scope.REQUEST
AddTransient() Scope.TRANSIENT

The difference is the habit around them. In ASP.NET Core, scoped is everywhere, mostly because DbContext is scoped. In Nest, providers are singletons unless you say otherwise, and that's right for almost all of them. ORM clients are singletons holding a connection pool, so there's no per-request context to scope.

And request scope behaves differently. ASP.NET Core's scope validation, on by default in Development, rejects a scoped service injected into a singleton as a captive dependency. Nest instead makes the singleton request-scoped too, along with everything up to the controller, and rebuilds that chain on every request. It works, but it's slower and rarely what you meant. When you need the current user or tenant deep in a service, read it from AsyncLocalStorage, which flows through await the way AsyncLocal<T> does, instead of reaching for an IHttpContextAccessor equivalent.

IHostedService.StartAsync() and StopAsync() have counterparts too: any provider can implement onApplicationBootstrap() and onApplicationShutdown().

Controllers

[ApiController]
[Route("orders")]
public class OrdersController : ControllerBase
{
    private readonly IOrdersService _ordersService;

    public OrdersController(IOrdersService ordersService)
    {
        _ordersService = ordersService;
    }

    [HttpGet]
    public Task<List<Order>> FindAll([FromQuery] int page = 0) => _ordersService.FindAllAsync(page);

    [HttpGet("{id}")]
    public async Task<ActionResult<Order>> FindOne(string id)
    {
        var order = await _ordersService.FindOneAsync(id);
        return order is null ? NotFound() : order;
    }

    [HttpPost]
    public async Task<ActionResult<Order>> Create(CreateOrderRequest request)
    {
        var order = await _ordersService.CreateAsync(request);
        return CreatedAtAction(nameof(FindOne), new { id = order.Id }, order);
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Remove(string id)
    {
        await _ordersService.RemoveAsync(id);
        return NoContent();
    }
}
Enter fullscreen mode Exit fullscreen mode
@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')
  async findOne(@Param('id') id: string) {
    const order = await this.ordersService.findOne(id);
    if (!order) {
      throw new NotFoundException();
    }
    return order;
  }

  @Post()
  create(@Body() dto: CreateOrderDto) {
    return this.ordersService.create(dto);
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id') id: string) {
    return this.ordersService.remove(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

Small things:

  • Route parameters are :id.
  • Every parameter says where it comes from (@Body(), @Query(), @Param(), @Headers()), so there are no binding source conventions to remember.
  • Query and path parameters arrive as strings. ParseIntPipe converts and validates one, and answers 400 for ?page=abc.
  • There's no ActionResult<T>. You return the body and throw NotFoundException, ConflictException and friends for error statuses.
  • A POST answers 201 by default and @HttpCode() changes any status. There's no CreatedAtAction(): set a Location header with @Header() when you need one.
  • Handlers return Promises, your Task, and Nest serializes the result as JSON. Property names are whatever they are in your TypeScript, which is camelCase by convention, so there's no naming policy to configure.

Minimal APIs

There's no app.MapGet("/orders/{id}", ...) style in Nest. The smallest Nest app is still a controller and a module, and nest new orders-api --minimal puts them in a single file, src/main.ts. It grows into the layout above by moving things out of that file, not by rewriting them.

Middleware and filters

The pipeline maps closely. Middleware runs first, then four kinds of components around the handler:

ASP.NET Core Nest When it runs
Middleware (app.Use()) Middleware before routing, with the raw request
Authorization filters, [Authorize] Guards after routing: may the handler run?
Action, result and endpoint filters Interceptors around the handler, with its result
Model binding and validation Pipes on each argument
Exception filters, IExceptionHandler Exception filters when anything above throws

Like filters, each can be bound to one handler, a controller or the whole app.

Middleware looks almost the same. A correlation id, in both:

app.Use(async (context, next) =>
{
    var id = context.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? Guid.NewGuid().ToString();
    context.Response.Headers["X-Correlation-Id"] = id;
    await next();
});
Enter fullscreen mode Exit fullscreen mode
export function correlationId(req: Request, res: Response, next: NextFunction) {
  const id = req.header('x-correlation-id') ?? randomUUID();
  res.setHeader('x-correlation-id', id);
  next();
}

// main.ts
app.use(correlationId);
Enter fullscreen mode Exit fullscreen mode

For middleware that needs injected services or only some routes, write a class implementing NestMiddleware and apply it in a module's configure() with consumer.apply(...).forRoutes(...).

An interceptor is an IAsyncActionFilter, with next.handle() in place of await next():

@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`)));
  }
}
Enter fullscreen mode Exit fullscreen mode

next.handle() returns an RxJS stream of the handler's result, which the interceptor can transform before it goes out, the way a result filter would.

Exception filters and problem details

An IExceptionHandler:

public class OrderNotFoundHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        if (exception is not OrderNotFoundException) return false;
        context.Response.StatusCode = StatusCodes.Status404NotFound;
        await context.Response.WriteAsJsonAsync(
            new ProblemDetails { Status = 404, Title = "Not Found", Detail = exception.Message }, ct);
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

In Nest, @Catch() says which exception types a filter handles, so there's no type check to write:

@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,
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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

One thing to know if your clients parse problem details: Nest's own error responses, validation errors included, are not RFC 9457 problem details out of the box. They're plain JSON objects with a statusCode and a message. If you need problem details everywhere, one catch-all filter like the one above does it.

Validation is explicit, and that's the first gotcha

[ApiController] validates models before your action runs, with rules from Data Annotations:

public record CreateOrderRequest(
    [Required] string CustomerId,
    [Required, MinLength(1)] List<OrderItem> Items,
    [MaxLength(500)] string? Note);
Enter fullscreen mode Exit fullscreen mode

In Nest, a global pipe does that job. With classes, it's class-validator decorators and ValidationPipe:

export class CreateOrderDto {
  @IsString()
  @IsNotEmpty()
  customerId: string;

  @ArrayNotEmpty()
  @ValidateNested({ each: true })
  @Type(() => OrderItemDto)
  items: OrderItemDto[];

  @IsOptional()
  @MaxLength(500)
  note?: string;
}
Enter fullscreen mode Exit fullscreen mode
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
Enter fullscreen mode Exit fullscreen mode

whitelist drops fields the DTO doesn't declare, and transform turns the body into an actual CreateOrderDto instance.

If you like FluentValidation's rules-in-code style better, Nest 12 takes a Zod (or any Standard Schema) schema per parameter, and the parameter's 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);
}
Enter fullscreen mode Exit fullscreen mode

Here's the gotcha. System.Text.Json creates the type your action declares, so a body is at least the right shape. TypeScript types are erased when the code compiles. Without a pipe, @Body() dto: CreateOrderDto is whatever JSON the client sent. Register a validation pipe globally on day one and you never think about it again. Forget it and the compiler won't warn you.

Identity and policies

@nestjs/authentication closes every route the moment you register it, like a fallback policy that requires an authenticated user, and @Public() is your [AllowAnonymous]:

[ApiController]
[Authorize]
[Route("me")]
public class MeController : ControllerBase
{
    [HttpGet]
    public IActionResult Me() => Ok(new { Id = User.FindFirstValue(ClaimTypes.NameIdentifier) });
}
Enter fullscreen mode Exit fullscreen mode
@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: User) {
    return user;
  }
}
Enter fullscreen mode Exit fullscreen mode

Where ASP.NET Core has authentication handlers, 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, rather than a ClaimsPrincipal you dig claims out of. It covers much of what Identity and its endpoints do: sign-up, password hashing, server-side sessions, email verification and password reset links, TOTP two-factor, OpenID Connect sign-in, access and refresh tokens and API keys. The state lives in your database through a store you write against documented interfaces, not through a fixed EF schema.

Authorization will feel natural if you use policies. @nestjs/authorization puts them in classes, and the check on a route is type-checked against the class, so a misspelled ability doesn't compile:

[HttpPost]
[Authorize(Policy = "Staff")]
public Task<Product> Create(CreateProductRequest request) => _productsService.CreateAsync(request);
Enter fullscreen mode Exit fullscreen mode
@Policy()
export class ProductPolicy {
  create(user: User | null) {
    return !!user?.roles.includes('staff');
  }
}

// in the controller
@Post()
@Can(ProductPolicy, 'create')
create(@Body() dto: CreateProductDto) { ... }
Enter fullscreen mode Exit fullscreen mode

Resource-based authorization, AuthorizeAsync(User, resource, policy), is authorizationService.authorize(ProductPolicy, 'view', user, product) in a service. And the guard denies by default, so a route that declares no check is closed.

Configuration and options

appsettings.json, the per-environment files and environment variables become .env files and environment variables through @nestjs/config. Real environment variables win over the files, as they do in .NET:

{
  "Orders": {
    "PageSize": 20,
    "PaymentsUrl": "https://payments.example.com"
  }
}
Enter fullscreen mode Exit fullscreen mode
@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 {}
Enter fullscreen mode Exit fullscreen mode

NODE_ENV plays the role of ASPNETCORE_ENVIRONMENT, and the first file in envFilePath that defines a variable wins, so .env.production overrides .env the way appsettings.Production.json overrides appsettings.json. The schema is your ValidateOnStart(): a missing or malformed variable stops the app at startup instead of failing the first request that reads it. Keep secrets out of committed files, the way you'd use user secrets locally and a vault in production.

configuration["Orders:PageSize"] becomes config.get('ORDERS_PAGE_SIZE'), or getOrThrow() for a value that must be there. IOptions<OrdersOptions> becomes a registerAs() namespace, 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>) {}
Enter fullscreen mode Exit fullscreen mode

EF Core becomes TypeORM (or Drizzle)

There's no EF Core in Node, and I won't pretend otherwise: nothing matches LINQ. TypeORM is the closest in shape, with entity classes, a repository per entity in place of a DbSet<T>, and migrations:

public class Order
{
    public Guid Id { get; set; }
    public required string CustomerId { get; set; }
    public OrderStatus Status { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
@Entity('orders')
export class Order {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  customerId: string;

  @Column({ type: 'varchar', default: 'pending' })
  status: 'pending' | 'paid' | 'shipped';
}
Enter fullscreen mode Exit fullscreen mode
@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' });
  }
}
Enter fullscreen mode Exit fullscreen mode

orders.Where(o => o.CustomerId == id && o.Status == OrderStatus.Pending) becomes findBy() with an object of conditions, and anything bigger goes through the query builder. There's no SaveChanges() sweeping up tracked changes: save(), insert() and update() write when you call them. Transactions are a callback that commits when it resolves and rolls back when it throws, where you'd write a using var transaction block with CommitAsync():

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;
});
Enter fullscreen mode Exit fullscreen mode

@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.

The alternatives: MikroORM is the closest in behavior, with a unit of work and an identity map like EF's change tracking, and its em.flush() is the one that works like SaveChanges(). Drizzle (@nestjs/drizzle, the other first-party option) is the one I'd point a Dapper fan to: typed SQL, inferred result types, no entities. Prisma and Mongoose work too. dotnet ef migrations becomes the ORM's own migration tool, run as a separate step before the new version starts.

Background work

A BackgroundService splits into three tools, depending on what it does.

Work on a timer becomes @Cron() from @nestjs/schedule:

public class InvoiceExportService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromHours(1));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            // ...
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
@Injectable()
export class InvoiceJobs {
  @Cron(CronExpression.EVERY_HOUR)
  @OnOneInstance({ key: 'invoices:export' })
  async exportInvoices() {
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

A Nest cron job runs on every replica, just like a hosted service does. @OnOneInstance() from @nestjs/locks takes a lease in a store every instance shares, so the job runs on one of them, the way you'd use a Hangfire recurring job or a distributed lock.

Work handed off by a request (send this email, build that report) goes on a queue with @nestjs/bullmq, with retries and delays, which is what Hangfire's background jobs give you. And startup or shutdown work goes in the onApplicationBootstrap() and onApplicationShutdown() hooks from earlier.

In-process events, the job MediatR notifications often do, come from @nestjs/event-emitter:

// publishing
constructor(private readonly events: EventEmitter2) {}
this.events.emit('order.created', new OrderCreatedEvent(order.id));

// handling, in any provider
@OnEvent('order.created')
handleOrderCreated(event: OrderCreatedEvent) { ... }
Enter fullscreen mode Exit fullscreen mode

And if you use MediatR for commands and queries, @nestjs/cqrs has command and query buses with handlers in the same style.

Calling other services

IHttpClientFactory with typed clients becomes 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Polly's timeouts, retries and circuit breakers become @nestjs/resilience. Like a named resilience pipeline, 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);
}
Enter fullscreen mode Exit fullscreen mode

@Signal() injects an AbortSignal, the JavaScript CancellationToken, which fires when the attempt times out. Pass it to the HTTP call and the request is actually cancelled. 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

AddHealthChecks() and MapHealthChecks() become a controller using @nestjs/terminus, with separate liveness and readiness checks:

@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')]);
  }
}
Enter fullscreen mode Exit fullscreen mode

(@Public() because @nestjs/authentication closes every route, and probes don't sign in.)

ILogger<OrdersService> becomes private readonly logger = new Logger(OrdersService.name). The built-in ConsoleLogger writes JSON with json: true, and if you're used to Serilog, pino plugs in the same way. For the traces, errors and metrics Application Insights gives many .NET teams, nest new offers to set up NestJS Observe, which reports requests, jobs and errors in terms of your controllers and providers.

Swashbuckle and NSwag become @nestjs/swagger:

const config = new DocumentBuilder().setTitle('Orders API').setVersion('1.0').build();
SwaggerModule.setup('api', app, () => SwaggerModule.createDocument(app, config));
Enter fullscreen mode Exit fullscreen mode

Swagger UI is at /api. Swashbuckle gets your types by reflection. TypeScript has no runtime types to reflect on, so @nestjs/swagger comes with a compiler plugin that reads property types and optionality from your DTOs at build time, and you don't put @ApiProperty() on every field. Zod schemas describe the document too.

SignalR becomes a gateway

Real-time endpoints are gateways, on Socket.IO or plain WebSockets, using the same providers, guards and pipes as controllers:

@WebSocketGateway()
export class OrdersGateway {
  @SubscribeMessage('track')
  track(@MessageBody() orderId: string) {
    return { event: 'status', data: { orderId, status: 'shipped' } };
  }
}
Enter fullscreen mode Exit fullscreen mode

A hub method becomes a @SubscribeMessage() handler. It's not wire-compatible with SignalR clients, so the browser side switches to a Socket.IO or WebSocket client. For services talking to each other, @nestjs/microservices has transports for gRPC, Kafka, RabbitMQ, NATS, Redis and MQTT.

Testing

WebApplicationFactory<Program> becomes a testing module, and the HttpClient it creates becomes Supertest:

public class OrdersTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task ReturnsAnOrder()
    {
        var client = factory.WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
            services.AddSingleton<IOrdersService>(new FakeOrdersService()))).CreateClient();

        var order = await client.GetFromJsonAsync<Order>("/orders/42");
        Assert.Equal("42", order!.Id);
    }
}
Enter fullscreen mode Exit fullscreen mode
describe('Orders', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(OrdersService)
      .useValue(new FakeOrdersService())
      .compile();
    app = moduleRef.createNestApplication();
    await app.init();
  });

  afterAll(() => app.close());

  it('returns an order', async () => {
    const response = await request(app.getHttpServer()).get('/orders/42').expect(200);
    expect(response.body.id).toBe('42');
  });
});
Enter fullscreen mode Exit fullscreen mode

overrideProvider() is your ConfigureTestServices(). A testing module can also hold just the parts a test needs, say one controller and a fake service, which runs faster and needs no database. And for a plain unit test you need no framework at all: a provider is a class, so new OrdersService(fakeRepository) works.

Shipping it

dotnet publish gives you a folder or an image. 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"]
Enter fullscreen mode Exit fullscreen mode

Three things to check that the .NET host handled for you:

  • Shutdown hooks. The .NET host stops hosted services on SIGTERM without being asked. Nest runs onModuleDestroy() and onApplicationShutdown() only after app.enableShutdownHooks() in main.ts.
  • The process gets the signal. Use the exec form, CMD ["node", ...], not npm start, which doesn't reliably forward signals to Node.
  • Memory. Set Node's heap limit with --max-old-space-size, below the container's memory limit, so running out of memory is a JavaScript error with a stack trace instead of a silent OOMKilled.

Moving over without a rewrite

You don't have to move an ASP.NET Core 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 reverse proxy (YARP works fine for this), using the same database conventions and the same auth (a guard can verify the JWTs your .NET services already issue, for example with @nestjs/jwt).
  • Share the contract, not the code. Swashbuckle or NSwag already publish an OpenAPI document for your .NET services, and NSwag can generate a TypeScript client from it. The other way round, @nestjs/swagger publishes one for the Nest service.
  • Move existing endpoints only when you'd rewrite them anyway. A route that's being redesigned can move to the Nest service behind the proxy, 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.

async/await looks identical, and the runtime isn't. I/O behaves the same: while a request awaits the database, others run. But ASP.NET Core runs continuations on a thread pool, and Node.js runs all of your JavaScript on one thread. CPU-heavy work in a handler, like hashing a big file or a long synchronous loop, stalls every other request in the process, and there's no Task.Run() to push it aside. Move it to a queue or a worker thread, and scale with more processes or containers. If your service is mostly computation, .NET is the better runtime, and I'd tell anyone that. On the bright side, there's no SynchronizationContext and no ConfigureAwait(false) to think about.

No cancellation token unless you ask. ASP.NET Core binds RequestAborted to a CancellationToken parameter. Nest handlers get nothing by default. The JavaScript equivalent is an AbortSignal, and the HTTP client, fetch() and @nestjs/resilience all take one.

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. There's no reflection to fall back on.

Decorators are functions, not attributes. An attribute is passive metadata read by reflection. A decorator runs when the class is defined, and that's how Nest records what it reads at startup. In practice you'll rarely notice, but it explains why decorators can take arbitrary expressions.

Numbers are doubles. There's no decimal. Keep money in integer cents, or use a decimal library and the database's numeric type, which most drivers return as a string.

No LINQ. Array methods (filter, map, reduce) cover in-memory queries, and query builders cover the database, but nothing composes over both like IQueryable does.

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 .NET

To be fair to .NET: if you have a large ASP.NET Core codebase that works, a rewrite to get TypeScript is rarely worth it. If the work is CPU-bound or leans on EF Core's LINQ for complex queries, stay, or put the TypeScript service next to it rather than in place of it.

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
Enter fullscreen mode Exit fullscreen mode

Then nest g resource orders, and you have a module, controller, service, DTOs and tests to compare against the ASP.NET Core version in your head. The Coming from ASP.NET Core 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 .NET, tell me. It's written for you, and it's easy to fix.

Coming from Java instead? Here's the same tour for Spring Boot: NestJS for Spring Boot developers.

Top comments (0)