Run NestJS applications on Cloudflare Workers using Bun.
- 🚀 Fast: Powered by Bun's native bundler.
- ☁️ Edge Ready: Custom adapter for Cloudflare Workers.
- 📦 Node.js Polyfills: Automatic mocks for Node.js modules that are missing in the Edge environment (like
crypto,perf_hooks,util). - 💾 Cloudflare Native: Seamless integration with Cloudflare KV and D1 Databases.
bun add nestflareIn your src/index.ts:
import 'reflect-metadata';
import { NestflareFactory } from 'nestflare';
import { AppModule } from './app.module';
// Create the fetch handler
const handler = NestflareFactory.create(AppModule, {
globalPrefix: 'api',
});
// Export default for Cloudflare Workers
export default handler;Create a wrangler.jsonc (or wrangler.toml) in your project root:
Run the CLI to build your project:
bunx nestflare buildThen run Wrangler dev server:
wrangler dev dist/index.js --no-bundleTo get strict typing for your environment and bindings, you can generate TypeScript types from your wrangler.jsonc or wrangler.toml by running:
bunx wrangler types --env-interface CloudflareEnv cloudflare-env.d.tsYou can then use the @Env() decorator to access Cloudflare bindings (like KV or D1) directly in your controllers with full type support:
import { Controller, Get, Param } from '@nestjs/common';
import { Env } from 'nestflare';
@Controller('users')
export class UserController {
@Get(':id')
async getUser(@Param('id') id: string, @Env() env: CloudflareEnv) {
// Access D1 Database
const user = await env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(id).first();
return user;
}
}Nestflare uses bun:test for its test suite. To run tests:
bun test
{ "name": "my-nestflare-app", "main": "dist/index.js", "compatibility_date": "2024-09-23", "compatibility_flags": [ "nodejs_compat" ] }