PAS7 Studio
Back to all articles

Running NestJS on Bun.js: setup guide and performance optimizations for 2026

How to run NestJS on the Bun runtime, what performance gains to expect, and which optimizations to apply immediately. Covers SWC compilation, lazy loading modules, Prisma + Bun, Docker configuration, and benchmarks comparing NestJS on Bun vs NestJS on Node.js.

12 Apr 2026· 16 min read· Technology
Best forNestJS developersBackend engineersTech leadsDevOps engineers
NestJS cat silhouette in deep indigo morphing into glowing orange Bun logo with speed lines, symbolizing NestJS running on Bun runtime

This guide assumes you already have a NestJS project or understand the framework basics. It focuses on the Bun-specific setup and performance gains.

How to run an existing NestJS application on the Bun runtime
SWC configuration for ~20x faster NestJS compilation
Lazy loading modules to cut startup time by up to 40%
Prisma + Bun configuration for database operations
Fastify adapter as an alternative to Express for higher throughput
Docker configuration optimized for Bun + NestJS
Real benchmarks: NestJS on Bun vs NestJS on Node.js
Pitfalls and compatibility issues to watch for

NestJS is a well-structured framework. Bun is a fast runtime. Combined, they address two separate performance bottlenecks: framework overhead and runtime overhead.

NestJS provides a modular architecture with dependency injection, decorators, guards, interceptors, pipes, and a strong plugin ecosystem. The framework's structure is valuable for large applications, but it comes with startup overhead — NestJS needs to resolve the module graph, instantiate providers, and build the metadata cache before it can handle requests. On Node.js, this process takes 100-150ms for a medium-sized application. [3][4]

Bun's JavaScriptCore engine starts executing meaningful code in 8-15ms compared to Node.js's 40-120ms. When you run NestJS on Bun, both the runtime startup and the NestJS module resolution happen faster. The result: a medium NestJS application that takes ~117ms to start on Node.js starts in ~48ms on Bun — roughly 60% faster. For serverless deployments where cold starts directly impact user experience and cost, this is significant. [1][2]

The throughput improvement is equally notable. Benchmarks from independent tests show NestJS + Express on Bun delivering ~41,200 req/s compared to ~16,800 req/s on Node.js — a 2.4x improvement. With the Fastify adapter instead of Express, the numbers are even higher on both runtimes, but the relative improvement from Bun remains consistent. [1]

2.4x faster

~41,200 req/s on Bun vs ~16,800 req/s on Node.js with identical NestJS code. [1]

60% faster

~48ms on Bun vs ~117ms on Node.js for a medium NestJS application. [1]

20x faster

SWC replaces tsc for NestJS builds, reducing compilation from minutes to seconds. [3]

10-30x faster

Bun's built-in package manager replaces npm for dependency resolution and installation. [2]

~20x faster

Bun's Jest-compatible test runner executes NestJS test suites dramatically faster. [2]

25-40% smaller

oven/bun:1.3 base image is ~130MB vs node:22-slim at ~180MB. [2]

The setup is straightforward for most NestJS applications. Bun is largely Node.js API-compatible, so your existing NestJS code works without modification.

01

Install the Bun runtime

BASH
curl -fsSL https://bun.sh/install | bash

On Windows:

POWERSHELL
powershell -c "irm bun.sh/install.ps1|iex"

Verify with bun --version. You should see 1.3.x or later. [2]

02

Install project dependencies with Bun

BASH
cd your-nestjs-project
bun install

This replaces npm install. Bun reads your existing package.json and generates a bun.lockb lockfile. Most NestJS dependencies resolve without issues. If you encounter problems with native addons, check the compatibility section below. [1][2]

03

Start the NestJS application with Bun

BASH
bun run src/main.ts

If your NestJS app uses the default TypeScript setup (with tsconfig.json), Bun handles it natively. If you use NestJS CLI scripts like nest start, you can also run:

BASH
bun run nest start

For development with hot reload:

BASH
bun --hot src/main.ts

Bun's hot reload preserves application state across restarts, which is faster than NestJS CLI's --watch flag that restarts the entire process. [1][2]

Compatibility note

Most NestJS applications work on Bun without changes. Test your full route suite, especially if you use custom decorators, native addons, or V8-specific reflection patterns. Run bun test to validate your test suite before switching to Bun in production.

SWC (Speedy Web Compiler) is a Rust-based TypeScript/JavaScript compiler that NestJS supports natively. It is approximately 20x faster than the default TypeScript compiler. Combined with Bun, it eliminates compilation bottlenecks entirely.

01

Install SWC packages

BASH
bun add -d @swc/cli @swc/core

These are the only packages required for NestJS SWC integration. [3]

02

Enable SWC in nest-cli.json

JSON
{
  "compilerOptions": {
    "builder": "swc",
    "typeCheck": true
  }
}

The typeCheck: true option runs tsc in noEmit mode alongside SWC for type validation. If you prefer faster builds without type checking (and rely on your IDE or CI for type checking), set it to false. [3]

03

Start NestJS with SWC + Bun

BASH
bun run nest start -b swc -w

This combines SWC compilation with Bun's runtime and NestJS watch mode. For production builds without watch mode:

BASH
bun run nest start -b swc

The SWC configuration file (.swcrc) can be customized for decorator metadata, JSX support, and other options. NestJS pre-configures SWC to match framework requirements, so most projects work with the defaults. [3]

04

Handle circular dependency edge cases

SWC handles circular imports differently from tsc. If you use TypeORM, MikroORM, or other ORMs with circular entity references, you may need the Relation<> wrapper type to prevent transpilation issues:

TYPESCRIPT
@Entity()
export class User {
  @OneToOne(() => Profile, (profile) => profile.user)
  profile: Relation<Profile>;
}

This prevents the type from being saved in the transpiled metadata, avoiding circular dependency issues. If your ORM does not provide a similar workaround, you can define your own wrapper type. [3]

Performance stack

SWC + Bun gives you the fastest possible NestJS development experience: Rust-speed compilation for builds, JavaScriptCore-speed execution for runtime, and Jest-compatible tests that run 20x faster. The combination eliminates the two biggest sources of developer wait time.

Lazy loading defers module registration until a route is actually hit. For large NestJS applications with many modules, this can reduce startup time by 30-40%.

01

Enable route-based lazy loading

TYPESCRIPT
// app.module.ts
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";

@Module({
  imports: [
    {
      path: "./admin/admin.module",
      lazy: true,
    },
    {
      path: "./reports/reports.module",
      lazy: true,
    },
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Modules marked lazy: true are not loaded at startup. They are loaded and cached on the first request that triggers them. Subsequent requests use the cached module instance. [4]

02

Use LazyModuleLoader for programmatic control

TYPESCRIPT
import { Injectable } from "@nestjs/common";
import { LazyModuleLoader } from "@nestjs/core";

@Injectable()
export class SomeService {
  constructor(
    private readonly lazyModuleLoader: LazyModuleLoader,
  ) {}

  async loadHeavyModule() {
    const { HeavyModule } = await this.lazyModuleLoader.load(
      () => import("./heavy/heavy.module"),
    );
    return HeavyModule;
  }
}

This approach gives you fine-grained control over when heavy modules are loaded, which is useful for on-demand feature activation or conditional module initialization based on user context. [4]

03

Expected startup improvement

For a NestJS application with 20+ modules:

- Eager loading (default): All modules loaded at startup, ~117ms on Node.js, ~48ms on Bun - Lazy loading on Bun: Only core modules loaded at startup, often ~25-30ms for initial boot, remaining modules loaded on first request

Lazy loading is particularly effective for serverless deployments where each function invocation pays the full startup cost. [4][5]

When to use lazy loading

Enable lazy loading for modules that are not needed on every request (admin panels, reporting, batch processing, feature flags). Keep frequently-used modules (auth, core API routes) eagerly loaded to avoid first-request latency penalties.

NestJS defaults to the Express adapter. Express is the most widely used Node.js framework, but it is not the fastest. NestJS also supports a Fastify adapter, which provides significantly higher throughput and lower latency. When running on Bun, the Fastify adapter compounds the performance benefit. [3][5]

To switch to Fastify, install the adapter and update your main.ts bootstrap function. The rest of your NestJS code — controllers, services, guards, interceptors, pipes — remains unchanged. The adapter handles the mapping between NestJS's abstractions and Fastify's request/response objects. [3]

Benchmark data shows NestJS + Fastify on Bun delivering substantially more throughput than NestJS + Express on Bun. The combination is recommended for new projects where you control the adapter choice. For existing projects using Express, the switch requires testing middleware compatibility (many Express middleware packages have Fastify equivalents or work via @fastify/express). [1][3]

Switching from Express to Fastify in NestJS requires changing the bootstrap function and installing @nestjs/platform-fastify. Controllers and services remain unchanged.

Section fastify-adapter screenshot

Performance comparison

NestJS + Express on Bun is already 2.4x faster than on Node.js. Switching to the Fastify adapter adds another significant throughput improvement on both runtimes. The Fastify adapter is the recommended choice for new NestJS projects in 2026.

Prisma works on Bun without modification. The Prisma team has confirmed compatibility, and many production deployments use Prisma + Bun + PostgreSQL. Setup is identical to Node.js: install the packages, generate the client, and use it in your NestJS services. [1][2]

For the development workflow, bunx prisma replaces npx prisma for running Prisma CLI commands. The generate command produces the same client code. The only difference is speed: Prisma CLI commands execute faster on Bun because the JavaScript execution is faster. [2]

Configuration

Use bun add prisma @prisma/client to install, bunx prisma generate to generate the client, and import PrismaClient normally in your NestJS services. Connection pooling, transactions, and migrations work identically to Node.js.

A Docker configuration optimized for NestJS on Bun combines the oven/bun base image with SWC compilation and multi-stage builds.

01

Create a multi-stage Dockerfile

DOCKERFILE
FROM oven/bun:1.3 AS base
WORKDIR /app

COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production

COPY . .
RUN bun run nest build

EXPOSE 3000
CMD ["bun", "dist/main.js"]
02

Build and push the image

BASH
docker build -t nestjs-bun-app .
docker run -p 3000:3000 nestjs-bun-app

The resulting image is approximately 25-40% smaller than an equivalent Node.js-based NestJS image, starts faster, and uses less runtime memory. For Kubernetes deployments, this translates to faster pod scheduling and lower resource requirements. [1][2]

Production tip

Combine Bun's Docker image with SWC compilation (nest build -b swc) for the fastest possible build-and-deploy pipeline. The entire build — install, compile, and image creation — typically completes in under 30 seconds for a medium NestJS application.

These optimizations work on both Node.js and Bun, but compound with Bun's faster runtime for the best results.

Use response DTOs and class-transformer

Define explicit response shapes with @Expose() decorators. This reduces payload size and prevents leaking internal fields. Combined with Fastify's schema-based serialization, you get both security and speed.

Enable route-level caching

Use NestJS's @CacheKey() and @CacheTTL() decorators for routes that return data which changes infrequently. This avoids redundant database queries and serialization work.

Optimize database queries

Use Prisma's select and include to fetch only needed fields. Avoid N+1 queries with eager loading. For read-heavy workloads, consider adding a Redis or bun:sqlite cache layer in front of PostgreSQL.

Minimize dependency injection scope

NestJS creates a new instance for each request-scoped provider. Use the default (singleton) scope where possible. Mark providers as request-scoped only when they hold per-request state.

Use compression middleware

Enable gzip or brotli compression for JSON responses. With the Fastify adapter, use @fastify/compress. This can reduce response payload size by 60-80% for JSON data.

Profile before optimizing

Use Bun's built-in Bun.write() and console.time() for ad-hoc profiling. For deeper analysis, use clinic.js (Node.js) or Bun's experimental profiler to identify actual bottlenecks before optimizing.

Key principle

Bun makes your code execute faster. The optimizations above make your code do less work. The combination is where real performance gains compound: faster execution of optimized code.

These benchmarks come from independent tests comparing NestJS with Express adapter on both runtimes, using identical hardware and workloads.

Comparison pointRequests/secLatency (avg)Throughput (MB/s)
NestJS + Express on Node.js 1816,874116.9 ms4.03 MB
NestJS + Express on Bun41,21347.88 ms7.91 MB
Improvement+144%-59%+96%

What the numbers mean in practice

A 2.4x throughput improvement means that, for the same hardware, a NestJS API on Bun can handle 2.4x more concurrent users. For serverless deployments, the 60% latency reduction directly translates to lower billing. These are framework-level benchmarks; real-world applications with database queries will see smaller but still meaningful improvements.

These are the problems that teams encounter when running NestJS on Bun in production.

SWC does not handle circular imports the same way as tsc. If you use TypeORM or MikroORM with circular entity references, use the Relation<> wrapper type to avoid transpilation issues. This is a NestJS + SWC issue, not a Bun issue, but it becomes more visible when you combine SWC with Bun. [3]

Some NestJS CLI plugins may not generate metadata correctly with SWC. If you use @nestjs/swagger or custom CLI plugins that rely on TypeScript metadata, you may need to run the PluginMetadataGenerator manually in monorepo setups. [3]

Bun's garbage collector (JSC) is less battle-tested for processes running 72+ hours compared to V8's. Monitor memory behavior in staging for at least 48 hours before deploying to production. NestJS applications with large module graphs and long-lived connections are more susceptible. [1][2]

Native C++ addons (bcrypt, node-sass, sharp) may not work on Bun. Use pure-JS alternatives (bcryptjs, sass, @napi-rs/canvas) and test each native dependency before migrating. [1][2]

NestJS's @nestjs/platform-express works on Bun, but some Express-specific middleware may behave differently. If you switch to the Fastify adapter, ensure all middleware has Fastify-compatible equivalents. [3][4]

Safe adoption path

Use Bun as the package manager and test runner first. Then enable SWC for compilation. Finally, switch the runtime to Bun in staging and monitor for 48+ hours. This staged approach minimizes risk while capturing most of the performance benefit.

Short answers to common questions about running NestJS on Bun.

Does NestJS work on Bun without code changes?

In most cases, yes. NestJS applications using standard modules, guards, interceptors, and pipes work on Bun without modification. The main areas to test are custom decorators that depend on V8 internals and native C++ addons. [1][3]

Should I use SWC or Bun's native TypeScript?

For development, Bun's native TypeScript is sufficient and simpler. For production builds where you want compiled output, SWC is the recommended choice because NestJS has first-class SWC support through the CLI. [3]

Is lazy loading worth the complexity?

For applications with 20+ modules or serverless deployments where cold starts matter, yes. Lazy loading can reduce initial startup by 30-40%. For small applications or always-on servers, the benefit is smaller. [4]

Should I switch from Express to Fastify adapter?

For new projects, yes. The Fastify adapter provides higher throughput and lower latency. For existing projects, evaluate the migration cost against the performance benefit — middleware compatibility is the main concern. [3][5]

Can I use Vitest instead of Jest with NestJS on Bun?

Yes. NestJS officially supports Vitest as an alternative test runner. Combined with Bun's fast module resolution, Vitest provides a modern, fast testing experience. Alternatively, bun test works directly with NestJS test files. [3]

What about NestJS microservices on Bun?

NestJS microservices (TCP, Redis, NATS, gRPC transports) work on Bun. The transport layer uses standard Node.js networking APIs which Bun supports. Test each transport protocol individually, as some may have edge cases. [4]

Sources supporting claims about NestJS on Bun benchmarks, SWC configuration, lazy loading, and performance optimization patterns.

Reviewed: 12 Apr 2026Applies to: NestJS 10+Applies to: Bun 1.3+Applies to: SWC (Speedy Web Compiler)Applies to: Fastify adapter for NestJSApplies to: Prisma ORMTested with: NestJS with Express adapterTested with: NestJS with Fastify adapterTested with: Bun 1.3 runtimeTested with: SWC via @swc/cli @swc/coreTested with: Docker (oven/bun base image)Tested with: Prisma + PostgreSQL

If you are considering running NestJS on Bun, PAS7 Studio can help you audit compatibility, configure the optimal build pipeline (SWC + Bun), apply lazy loading and performance optimizations, and deploy a production-ready NestJS application with Docker, CI/CD, and monitoring.

We work with NestJS, Bun, Fastify, PostgreSQL, and the full backend stack. Whether you are building a new API or migrating an existing NestJS application, we can help you capture the performance benefits without the surprises.

You are here02/02

NestJS on Bun.js: setup and performance optimizations

Related Articles

growth

AI SEO / GEO in 2026: Your Next Customers Aren’t Humans — They’re Agents

Search is shifting from clicks to answers. Bots and AI agents crawl, cite, recommend, and increasingly buy. Learn what AI SEO / GEO means, why classic SEO is no longer enough, and how PAS7 Studio helps brands win visibility in the agentic web.

blogs

The most powerful Apple chip yet? M5 Pro and M5 Max are breaking records

A data-backed March 2026 analysis of Apple M5 Pro and M5 Max. We break down why these chips can credibly be called Apple's most powerful pro laptop silicon, how they compare with M4 Pro, M4 Max, M1 Pro, M1 Max, and how they stack up against Intel and AMD laptop rivals.

blogs

Artemis II and the Code That Carries Humans to the Moon

This article unpacks NASA's Artemis II mission, launched on April 1, 2026, and explains what it really says about modern engineering: flight software, backup logic, simulation, telemetry, human control, and the careful role AI can play in space systems.

telegram-media-saver

Automatic Tagging & Search for Saved Links

Integrate with GDrive/S3/Notion for automatic tagging and fast search via search APIs

Professional development for your business

We create modern web solutions and bots for businesses. Learn how we can help you achieve your goals.