NestJS Logo

Coming from Laravel

Nest gives a Laravel developer the same batteries in Node.js and TypeScript, as first-party packages: sign-in, policies, mail, queues, file storage and more. Service providers become modules, Form Requests become validation pipes, and Sanctum, Fortify, policies, mailables, disks, translations, jobs and the scheduler have counterparts maintained by the Nest core team. What changes is the language, TypeScript, the runtime, Node.js, and one habit: Nest is split into packages that you install and import.

If you're looking for a framework like Laravel for Node.js, or a Laravel alternative for a TypeScript team, this page maps Laravel concepts to their Nest equivalents, with short code side by side. It ends with what's different, which matters more than the syntax. For the full list of first-party packages, see Batteries included.

At a glance#

LaravelNestRead more
laravel new, composer run devnest new, npm run start:devFirst steps
Artisan make:* commands, tinkernest generate, the REPLCLI usages, REPL
The service container and service providersModules and providersModules, Providers
Routes and controllersControllers with route decoratorsControllers
MiddlewareMiddleware, guards and interceptorsMiddleware
Form RequestsPipes, with Zod or class-validatorValidation
API resourcesPlain objects, or ClassSerializerInterceptorSerialization
Eloquent and migrationsDrizzle or TypeORM, and their migration toolsDrizzle, TypeORM
Sanctum, Fortify, Socialite@nestjs/authenticationAuthentication
Gates and policies@nestjs/authorizationAuthorization
Rate limiting@nestjs/throttlerRate limiting
config/ and .env@nestjs/configConfiguration
The exception handlerException filtersException filters
Queues and jobs@nestjs/bullmqQueues
The scheduler, onOneServer()@nestjs/schedule, with @nestjs/locksTask scheduling
Mail and mailables@nestjs/mailMail
Storage and Flysystem disks@nestjs/storageFile storage
Localization@nestjs/i18nInternationalization
Cache@nestjs/cache-managerCaching
Events and listeners@nestjs/event-emitterEvents
Broadcasting, ReverbGatewaysGateways
The Http facade@nestjs/http-clientHTTP client
Pest, PHPUnit@nestjs/testing with VitestTesting
Telescope, Pulse, NightwatchNestJS ObserveObservability
BladeA view engine and @Render()Model-View-Controller
Community packages for webhooks, workflows and API docs@nestjs/webhooks, @nestjs/workflows, @nestjs/swagger and moreBeyond Laravel's defaults

Start a project#

laravel new creates an application, and composer run dev starts php artisan serve, a queue worker and Vite. The Nest CLI creates a project and generates code, as Artisan's make:* commands do:


$ npm i -g @nestjs/cli
$ nest new orders-api
$ cd orders-api
$ nest generate resource orders

npm run start:dev starts the application and restarts it when a file changes. Queue workers and scheduled jobs run in the same process, so there's no second command. nest generate resource orders creates a module with a controller, a service, DTOs and test files, close to make:model Order -crR. php artisan tinker becomes the REPL, where every provider is at hand: await get(OrdersService).findOne(...).

Service providers become modules#

A Laravel application finds its controllers, policies and listeners by convention, and service providers register bindings in the container. A Nest application is a tree of modules, and each one lists what it contains:

orders/orders.module.ts
JS TS

import { Module } from '@nestjs/common';
import { PaymentsModule } from '../payments/payments.module.js';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersRepository } from './orders.repository.js';
import { OrdersService } from './orders.service.js';

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

The root module, AppModule, imports the feature modules. Nothing is discovered: a controller that isn't listed serves no routes. Code is grouped by feature, not by kind: the orders controller, service and policy live together in src/orders, not in app/Http/Controllers and app/Policies.

Bindings and dependency injection#

A service provider binds an interface to an implementation:


// app/Providers/AppServiceProvider.php
public function register(): void
{
    $this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
}

TypeScript interfaces don't exist at runtime, so Nest binds an abstract class or a token instead. The module does what bind() does, and exports the binding to the modules that import it:

payments/payments.module.ts
JS TS

import { Module } from '@nestjs/common';
import { PaymentGateway } from './payment-gateway.js';
import { StripePaymentGateway } from './stripe-payment-gateway.js';

@Module({
  providers: [{ provide: PaymentGateway, useClass: StripePaymentGateway }],
  exports: [PaymentGateway],
})
export class PaymentsModule {}

Constructor injection then works as in Laravel, and every provider is a singleton by default. See Custom providers.

Nest has no facades. Mail::to(), Cache::get() and Storage::disk() become a mailer, a cache and a disk injected into the class that uses them, and a test replaces them by providing another value.

Routes and controllers#

A Laravel API registers a resource controller in routes/api.php:


// routes/api.php
Route::apiResource('orders', OrderController::class)
    ->only(['index', 'store', 'show', 'destroy'])
    ->middleware('auth:sanctum');

The controller receives route-model-bound orders and authorizes them:


// app/Http/Controllers/OrderController.php
public function show(Order $order)
{
    Gate::authorize('view', $order);

    return new OrderResource($order);
}

public function destroy(Order $order)
{
    Gate::authorize('cancel', $order);
    $this->orders->cancel($order);

    return response()->noContent();
}

In Nest, a controller declares its routes with decorators, so there's no route file:

orders/orders.controller.ts
JS TS

import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  Param,
  ParseUUIDPipe,
  Post,
} from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import {
  createOrderSchema,
  type CreateOrderDto,
} from './create-order.schema.js';
import { OrdersService } from './orders.service.js';

@Controller('orders')
@Can.Anyone() // OrdersService checks each order against OrderPolicy
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  findAll(@CurrentUser() user: User) {
    return this.ordersService.findForUser(user);
  }

  @Get(':id')
  findOne(@CurrentUser() user: User, @Param('id', ParseUUIDPipe) id: string) {
    return this.ordersService.findOne(user, id);
  }

  @Post()
  create(
    @CurrentUser() user: User,
    @Body({ schema: createOrderSchema }) dto: CreateOrderDto,
  ) {
    return this.ordersService.place(user, dto);
  }

  @Delete(':id')
  @HttpCode(204)
  cancel(@CurrentUser() user: User, @Param('id', ParseUUIDPipe) id: string) {
    return this.ordersService.cancel(user, id);
  }
}

The differences:

  • @Controller('orders') is the URL prefix, and each method decorator adds a path. Route parameters are written :id. app.setGlobalPrefix('api') adds the prefix that Laravel gives routes/api.php.
  • There are no resource routes and no route names. The four methods above are what Route::apiResource() registers, written out.
  • There's no route model binding. A pipe such as ParseUUIDPipe checks the parameter, and the service loads the record and throws NotFoundException when there's none, as findOrFail() does.
  • A handler returns the body as JSON. A POST answers 201 by default; @HttpCode() changes it.
  • With @nestjs/authentication, every route requires a signed-in user unless it's marked @Public(), so auth:sanctum is the default. @CurrentUser() is $request->user(). @Can.Anyone() is explained in Gates and policies.
Middleware, guards and interceptors#

Laravel middleware wraps the request, and some of it, such as auth and can, decides whether the controller runs. Nest splits those roles into components that run in this order:

NestRunsLaravel counterpart
MiddlewareBefore routing, with the raw request and responseGlobal middleware
GuardsAfter routing, to decide whether the handler runsauth, can, throttle middleware
InterceptorsAround the handler, with access to its resultMiddleware that changes the response
PipesOn each argument, before the handlerForm Requests
Exception filtersWhen anything above throwsThe exception handler's render() callbacks

Form Requests become validation pipes#

A Form Request holds a request's rules:


// app/Http/Requests/StoreOrderRequest.php
public function rules(): array
{
    return [
        'items' => ['required', 'array', 'min:1'],
        'items.*.product_id' => ['required', 'uuid', 'exists:products,id'],
        'items.*.quantity' => ['required', 'integer', 'between:1,20'],
        'note' => ['nullable', 'string', 'max:500'],
    ];
}

In Nest, input is validated by pipes. Describe the body with a Standard Schema library such as Zod, and the parameter's type is inferred from the schema:

orders/create-order.schema.ts
JS TS

import { z } from 'zod';

export const createOrderSchema = z.object({
  items: z
    .array(
      z.object({
        productId: z.uuid(),
        quantity: z.int().min(1).max(20),
      }),
    )
    .min(1),
  note: z.string().max(500).nullish(),
});

export type CreateOrderDto = z.infer<typeof createOrderSchema>;

The controller passes it with the schema option of @Body(), and one line in main.ts, app.useGlobalPipes(new StandardSchemaValidationPipe()), turns validation on for the whole application. Three things work differently:

  • The status is 400, not 422. The response's message lists every failed rule, each prefixed with the field's path.
  • A schema checks shape, not the database. There's no exists or unique rule: the service checks those.
  • Authorization isn't in the request. A Form Request's authorize() becomes a policy check.

If you prefer a class, write the DTO with class-validator decorators and bind ValidationPipe instead. See Validation.

Warning TypeScript types don't exist at runtime, so a type annotation alone validates nothing. Without a validation pipe, @Body() dto: CreateOrderDto receives whatever JSON the client sent.

API resources have no direct counterpart: a resource's toArray() becomes a function that maps a row to a plain object, or a query that selects only those columns. See Serialization.

Eloquent becomes Drizzle or TypeORM#

Nest integrates the ORM you choose through first-party packages. This page shows Drizzle, where the schema is TypeScript and queries read like SQL, and TypeORM, where models are decorated classes; Sequelize and Mongoose have packages too. Neither is an active record: rows are plain objects, and queries go through an injected database.

A Laravel migration:


// database/migrations/2026_11_30_000000_create_orders_table.php
Schema::create('orders', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->foreignUuid('user_id')->constrained()->cascadeOnDelete();
    $table->enum('status', ['pending', 'paid', 'shipped'])->default('pending');
    $table->integer('total_cents');
    $table->timestamps();
});

With Drizzle, the table is declared once, in TypeScript, and the migration is generated from it:

database/schema.ts
JS TS

import { integer, pgEnum, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid().primaryKey().defaultRandom(),
  email: text().notNull().unique(),
});

export const orderStatus = pgEnum('order_status', ['pending', 'paid', 'shipped']);

export const orders = pgTable('orders', {
  id: uuid().primaryKey().defaultRandom(),
  userId: uuid('user_id')
    .notNull()
    .references(() => users.id, { onDelete: 'cascade' }),
  status: orderStatus().notNull().default('pending'),
  totalCents: integer('total_cents').notNull(),
  createdAt: timestamp('created_at').notNull().defaultNow(),
  updatedAt: timestamp('updated_at').notNull().defaultNow(),
});

export type Order = typeof orders.$inferSelect;

make:migration and migrate become npx drizzle-kit generate, which writes a SQL migration from the changes to the schema, and npx drizzle-kit migrate. With TypeORM, migration:generate and migration:run do the same. Nothing is filled in by convention: timestamps() is two columns you declare and keep up to date. See Migrations.

DrizzleModule.forRootAsync() registers the database once, in the root module, and queries go through it. $user->orders()->latest()->get() and Order::find($id) become:

orders/orders.repository.ts
JS TS

import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { desc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { orders } from '../database/schema.js';

@Injectable()
export class OrdersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  findForUser(userId: string) {
    return this.db
      .select()
      .from(orders)
      .where(eq(orders.userId, userId))
      .orderBy(desc(orders.createdAt));
  }

  async findById(id: string) {
    const [order] = await this.db.select().from(orders).where(eq(orders.id, id));
    return order;
  }
}

A query runs when it's awaited, and there's no lazy loading: $order->user has no counterpart that queries on first access, so an N+1 can't hide in a template. Load related rows with a join or Drizzle's relational queries, as with() does, and use db.transaction() where you'd use DB::transaction(). See Relations.

Sign-in: Sanctum and Fortify#

Laravel splits sign-in across Sanctum, Fortify and Socialite. @nestjs/authentication covers them in one package, and leaves the users table to you:

  • Users are your table. The package never reads it: a credential provider of yours loads a user by id, like the Eloquent user provider.
  • Passwords are hashed with PasswordHasher, with scrypt at OWASP's parameters, where Laravel defaults to bcrypt. needsRehash() works like Hash::needsRehash().
  • Sessions are server-side, in an HttpOnly cookie. SignInService.signIn() is Auth::login() and session()->regenerate() in one call.
  • Fortify's flows are services you call from your own controllers: email verification, password reset links and TOTP two-factor authentication with recovery codes, plus magic links.
  • Sanctum's tokens become short-lived access tokens with rotating refresh tokens, for mobile apps, and API keys that users create and revoke, like personal access tokens. Like Sanctum, the package stores only a SHA-256 hash of each key.
  • Socialite's providers become OpenID Connect providers, with google(), github() and microsoft() presets.

Fortify registers its routes for you. With @nestjs/authentication, you write the controller, and the package does the checks:

auth/auth.controller.ts
JS TS

import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, SignInService } from '@nestjs/authentication';
import { signInSchema, type SignInDto } from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';

@Public()
@Controller('auth')
export class AuthController {
  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly signInService: SignInService,
  ) {}

  @Post('sign-in')
  @HttpCode(200)
  async signIn(@Body({ schema: signInSchema }) body: SignInDto) {
    const user = await this.credentialsService.verify(body.email, body.password);
    if (!user) {
      throw new UnauthorizedException('Invalid email or password');
    }
    const { session } = await this.signInService.signIn(user.id, { method: 'password' });
    return { mfaRequired: session.mfa === 'pending' };
  }
}

CredentialsService is yours: it checks the password with PasswordHasher, as Auth::attempt() does. Where Fortify publishes its migrations, the package keeps sessions and tokens in your database through a store you implement against its interfaces. The Authentication chapter builds every flow above, step by step.

Gates and policies#

Laravel policies map almost one to one. A policy with a before() filter:


// app/Policies/OrderPolicy.php
public function before(User $user, string $ability): bool|null
{
    return $user->is_admin ? true : null;
}

public function view(User $user, Order $order): bool
{
    return $user->id === $order->user_id;
}

public function cancel(User $user, Order $order): bool
{
    return $user->id === $order->user_id && $order->status === 'pending';
}

The same policy for @nestjs/authorization, a class whose methods are abilities:

orders/order.policy.ts
JS TS

import { Policy, type PolicyBefore } from '@nestjs/authorization';
import type { Order } from '../database/schema.js';
import type { User } from '../users/user.js';

@Policy()
export class OrderPolicy implements PolicyBefore<User> {
  // Admins pass every check of this policy.
  before(user: User | null) {
    if (user?.roles.includes('admin')) {
      return true;
    }
  }

  view(user: User, order: Order) {
    return order.userId === user.id;
  }

  cancel(user: User, order: Order) {
    return order.userId === user.id && order.status === 'pending';
  }
}

Gate::authorize('view', $order) becomes authorize() on the injected AuthorizationService. Without route model binding, the service loads the order first:

orders/orders.service.ts
JS TS

async findOne(user: User, id: string) {
  const order = await this.ordersRepository.findById(id);
  if (!order) {
    throw new NotFoundException();
  }
  await this.authorizationService.authorize(OrderPolicy, 'view', user, order);
  return order;
}
  • authorize() throws when the policy denies, which answers 403, or 401 to a guest. can() answers true or false, like $user->can().
  • A check that needs no record, such as a create ability that takes only the user, goes on the route as @Can(OrderPolicy, 'create'), like the can middleware. Ability names are type-checked.
  • Unlike Laravel, the authorization guard denies by default: a route that declares no check, with @Can(), @Can.Anyone() or @Public(), is closed. That's why OrdersController declares @Can.Anyone() and checks in the service.

See Authorization.

RateLimiter::for() and the throttle middleware become @nestjs/throttler: named limits in ThrottlerModule.forRoot(), a global ThrottlerGuard, and @Throttle() per route. See Rate limiting, and Rate-limit sign-in for login limits like Fortify's.

Configuration and errors#

@nestjs/config reads .env files and environment variables, validates them with a schema, so a missing DATABASE_URL stops the application at startup, and replaces config() with an injectable ConfigService. See Configuration.

abort(404) becomes a thrown NotFoundException, and the other subclasses of HttpException become JSON error responses with their status; any other exception becomes a 500. The exception handler's render() callbacks become exception filters, classes decorated with @Catch(). See Exception filters.

Queues and jobs#

A Laravel job is a class with a handle() method, dispatched onto a queue:


// app/Jobs/GenerateInvoice.php
class GenerateInvoice implements ShouldQueue
{
    use Queueable;

    public function __construct(public Order $order) {}

    public function handle(InvoiceRenderer $renderer): void
    {
        // ...
    }
}

GenerateInvoice::dispatch($order);

@nestjs/bullmq splits the job class in two. A processor class takes the queue's jobs, and the job itself is plain data:

invoices/invoice.processor.ts
JS TS

import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
import { InvoiceRenderer } from './invoice-renderer.js';

@Processor('invoices')
export class InvoiceProcessor extends WorkerHost {
  constructor(private readonly renderer: InvoiceRenderer) {
    super();
  }

  async process(job: Job<{ orderId: string }>) {
    await this.renderer.render(job.data.orderId);
  }
}

A service adds a job to the queue it injects, as dispatch() does:

orders/orders.service.ts
JS TS

// constructor(@InjectQueue('invoices') private readonly invoices: Queue) {}
await this.invoices.add('generate', { orderId: order.id }, { attempts: 5 });
  • Pass ids, not models. Job data is JSON, and nothing reloads a model for you as Laravel's queued jobs do: the processor loads what it needs.
  • Retries are job options: attempts, backoff and delay.
  • BullMQ runs on Redis, or on PostgreSQL through its backendFactory option, where a new Laravel application queues jobs in the database. See Queues.
  • Workers run in the application's process, or in a separate one that starts the same modules.

For what Horizon shows, NestJS Observe records each job's wait time, run time, attempts and failures, as a hosted service.

Scheduling#

Laravel's scheduler lives in routes/console.php and runs from one cron entry:


// routes/console.php
Schedule::job(new ExportInvoices)
    ->dailyAt('02:00')
    ->onOneServer()
    ->withoutOverlapping();

In Nest, @Cron() from @nestjs/schedule goes on a method of any provider, and the schedule runs inside the application. @OnOneInstance() and @WithoutOverlapping() from @nestjs/locks do what onOneServer() and withoutOverlapping() do:

invoices/invoice-export.job.ts
JS TS

import { Injectable } from '@nestjs/common';
import { OnOneInstance, WithoutOverlapping } from '@nestjs/locks';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class InvoiceExportJob {
  @Cron('0 2 * * *', { name: 'invoice-export' })
  @OnOneInstance({ key: 'invoices:nightly-export' })
  @WithoutOverlapping()
  async exportInvoices() {
    // ...
  }
}

Laravel takes these locks from the cache store. @nestjs/locks takes them from a store you implement on your database or Redis, as Keep locks in your database shows. See Task scheduling.

Mail#

A Laravel mailable has an envelope and content:


// app/Mail/OrderShipped.php
class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(public Order $order) {}

    public function envelope(): Envelope
    {
        return new Envelope(subject: 'Your order has shipped');
    }

    public function content(): Content
    {
        return new Content(view: 'mail.orders.shipped');
    }
}

A mail class from @nestjs/mail returns the subject, the template's name and the values the template reads, from one render() method:

notifications/order-shipped.mail.ts
JS TS

import { Injectable } from '@nestjs/common';
import type { Mailable } from '@nestjs/mail';
import type { Order } from '../database/schema.js';

@Injectable()
export class OrderShippedMail implements Mailable<{ order: Order }> {
  render({ order }: { order: Order }) {
    return {
      subject: 'Your order has shipped',
      template: 'order-shipped',
      context: { order },
    };
  }
}

Mail::to($user)->send(new OrderShipped($order)) becomes a call on the injected Mailer, and the type of data comes from the mail class:

orders/orders.service.ts
JS TS

await this.mailer.send(OrderShippedMail, {
  to: { name: customer.name, address: customer.email },
  data: { order },
});
  • Templates are HTML files in a logic-less, Handlebars-style syntax that escapes every value.
  • Transports: SMTP, Resend, Postmark, SendGrid and Amazon SES, plus file and log transports for development.
  • Mail::fake() becomes InMemoryMailTransport, whose assertSent() finds a mail by recipient or mail class.
  • Queued mail and afterCommit(). Send from a job, or use @nestjs/outbox, which saves the message in the same transaction as the order and sends it after the commit, with retries.

See Mail.

Files and translations#

Laravel's Flysystem disks become disks from @nestjs/storage: a local folder, S3, or an S3-compatible store such as R2. Storage::put() becomes put(), and temporaryUrl() becomes signedUrl():

invoices/invoices.service.ts
JS TS

import { Injectable } from '@nestjs/common';
import { InjectDisk, StorageDisk } from '@nestjs/storage';

@Injectable()
export class InvoicesService {
  constructor(@InjectDisk('private') private readonly files: StorageDisk) {}

  async store(orderId: string, pdf: Buffer) {
    const key = `invoices/${orderId}.pdf`;
    await this.files.put(key, pdf, { contentType: 'application/pdf' });
    return this.files.signedUrl(key, { expiresIn: '15m' });
  }
}

A local disk signs its own URLs, so signedUrl() works in development without S3, and Storage::fake() becomes InMemoryDisk. See File storage.

lang/en/orders.php becomes a JSON catalog per locale and namespace, with placeholders in single braces and named plural forms:

i18n/en/orders.json
JS TS

{
  "notFound": "Order #{id} was not found.",
  "items": {
    "one": "{count} item",
    "other": "{count} items"
  }
}

__('orders.not_found', ['id' => $id]) becomes t() on the injected I18nService. Keys are typed from the English catalog, so a misspelled key fails to compile:

orders/orders.service.ts
JS TS

throw new NotFoundException(this.i18n.t('orders.notFound', { args: { id } }));

Plurals follow each language's rules, and the locale is resolved per request, from Accept-Language, a query parameter, a cookie or the user's saved language. See Internationalization.

Cache, events, broadcasting and HTTP#

  • Cache: @nestjs/cache-manager gives an injectable cache with get(), set() and del(), in memory or on Redis. TTLs are milliseconds, not seconds. See Caching.
  • Events: OrderShipped::dispatch($order) and a listener's handle() become emit() and a method decorated with @OnEvent('order.shipped'), from @nestjs/event-emitter. There are no model events: emit from the service that saved the row. See Events.
  • Broadcasting: Reverb and broadcast events become gateways, WebSocket servers inside the application, with Socket.IO or ws. The authentication guard and @CurrentUser() work in gateways too.

The Http facade becomes @nestjs/http-client, built on the fetch in Node.js. Http::withToken($key)->get(...) becomes a named client, registered in a module with its base URL, headers and timeout, and injected where it's used:

shipping/shipping-rates.service.ts
JS TS

import { Injectable } from '@nestjs/common';
import { HttpClient, InjectHttpClient } from '@nestjs/http-client';

interface Rate {
  service: string;
  cents: number;
}

@Injectable()
export class ShippingRatesService {
  constructor(@InjectHttpClient('carrier') private readonly carrier: HttpClient) {}

  async rates(zip: string) {
    const { data } = await this.carrier.get<Rate[]>('/rates', { query: { zip } });
    return data;
  }
}

Unlike Http, the client retries GET, PUT and DELETE requests up to 3 attempts by default, and throws on a non-2xx response. Http::fake() becomes a stub fetch passed to HttpClientModule.forRoot() in the test. See HTTP client.

Testing#

Where a Pest feature test calls getJson() on the whole application, a Nest test builds a testing module with the part under test, puts fakes in place of its dependencies, and sends requests with Supertest. This test creates only the controller, with a fake service:

orders/orders.controller.spec.ts
JS TS

import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { vi } from 'vitest';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';

describe('OrdersController', () => {
  let app: INestApplication;
  const ordersService = { findForUser: 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('lists orders', async () => {
    ordersService.findForUser.mockResolvedValue([]);
    await request(app.getHttpServer()).get('/orders').expect(200, []);
  });
});

For the whole application, import AppModule and replace providers with overrideProvider(). There's no RefreshDatabase and no actingAs(): point DATABASE_URL at a test database, apply the migrations first, and sign in through your sign-in route. New projects use Vitest, whose describe() and it() read much like Pest. See Testing.

Monitoring and commands#

NestJS Observe takes the place of Pulse and Nightwatch: traces of requests and jobs down to the class and method, and errors with their stack trace and logs. nest new sets up its SDK, and the dashboard is a hosted service with a free plan. There's no local dashboard like Telescope.

An Artisan command, or a seeder, becomes a script that starts the application's modules without the HTTP server, a standalone application: NestFactory.createApplicationContext(AppModule), then app.get(CartsService).closeStale(). For arguments, options and help text, use nest-commander.

Beyond Laravel's defaults#

Several first-party packages cover ground a Laravel application fills with community packages or its own code: webhooks that are signed, retried and verified, durable workflows whose steps survive restarts, a transactional outbox, idempotency keys, retries and circuit breakers, distributed locks, OpenAPI documents built from your controllers, GraphQL, microservice transports for Kafka, RabbitMQ, NATS and gRPC, and AI and MCP packages. See Batteries included for the full list.

Frontend, admin and billing#

Nest is a backend framework, so a few Laravel pieces map to something else:

  • Blade, Livewire and Inertia. Nest renders server-side pages with a view engine such as Handlebars and @Render(), as Model-View-Controller shows. Most Nest applications are APIs behind a separate frontend, such as Next.js.
  • Nova. Teams use an admin panel that reads the database, or internal pages in their own frontend.
  • Cashier. Call your payment provider's SDK, and receive its webhooks with @nestjs/webhooks, as the payments tutorial does.
  • Notifications. Mail, gateways and database rows are each first-party, and a small service of your own picks the channel per user, as via() does.
  • Starter kits. nest new creates an API; @nestjs/authentication provides sign-in, and your frontend provides the screens.

What's different#

The mappings above hold for structure. These are the differences that change how you write code.

The application stays in memory. Under PHP-FPM, Laravel boots for every request. A Nest application starts once and serves every request from the same process, as under Octane. A provider is a singleton shared by all requests, so keep per-request data in parameters, not on this.

One process serves many requests at once. Node.js runs your code on one thread, and while a request waits for the database, others run. A forgotten await doesn't block: the code continues before the query has finished. CPU-heavy work in a handler stalls every other request, so move it to a queue, and run several processes or containers to use several cores.

No global request, no facades. There's no request() or auth() helper. Pass the user to the service, or read per-request state from AsyncLocalStorage, which follows a request through awaits. See Async local storage.

Everything is wired explicitly. Laravel discovers policies, listeners and package service providers. In Nest, nothing is configured because a package is installed: what an application does at startup can be read from its modules.

Batteries are separate packages. Each first-party package is installed separately, so a project carries only what it uses. Batteries included lists them all.

Pick the ORM your team knows. Eloquent is part of Laravel, and every Laravel package assumes it. Nest's packages that keep state, such as the session store and the lock store, work through a small store interface, so they run on Drizzle, TypeORM, or whichever you picked.

Decorators and types. @Controller() and @Injectable() play the role of PHP attributes such as #[Fillable]: they record metadata that the framework reads. Types exist only at compile time, so a request body or a job's data is whatever was sent, and only a validation pipe or a schema checks it at runtime.

Numbers are doubles. JavaScript has no decimal type, so keep money in integer cents.

ES modules and npm. Nest 12 packages are ES modules, and a project imports local files with a .js extension, even from .ts files, because that's the name of the compiled file. npm and package.json take the place of Composer and composer.json. See ESM packages.

Edit on GitHub

Support us

Nest is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If you'd like to join them, please read more here.

Principal Sponsors

SerpApi LogoTrilon LogoMojam Logo

Sponsors / Partners

Become a sponsor