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 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(); 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(); 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; } } @Injectable() export class OrdersService { constructor(private readonly ordersRepository: OrdersRepository) {} } 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 {} 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 {} 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) {} 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(); } } @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); } } 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.
ParseIntPipeconverts and validates one, and answers400for?page=abc. - There's no
ActionResult<T>. You return the body and throwNotFoundException,ConflictExceptionand friends for error statuses. - A
POSTanswers201by default and@HttpCode()changes any status. There's noCreatedAtAction(): set aLocationheader 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(); }); 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); 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`))); } } 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; } } 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, ); } } 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); 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; } 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.
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: Source:https://dev.to/nestjs/nestjs-for-aspnet-core-developers-a-typescript-backend-that-will-feel-familiar-mo7Related posts
Replaying Yesterday: Designing a Date Picker for a Daily Puzzle
A refusal that changes no bytes
NestJS for Spring Boot developers: a TypeScript backend that will feel familiar
