nestjs-cloudflare
Run a Nest application on Cloudflare Workers with binding injection, scheduled events, Queues, and hibernating Durable Object WebSockets.
Installation
npm install nestjs-cloudflare
npm install @nestjs/common @nestjs/core reflect-metadata rxjs
Install your chosen Nest HTTP platform, such as @nestjs/platform-express. Queues require @nestjs/microservices, scheduled handlers require @nestjs/schedule, and gateways require @nestjs/websockets. These integrations are optional peers exposed through separate package entry points. Use versions compatible with this package's peer dependency ranges.
The npm package includes compiled JavaScript and type declarations. Applications also need Cloudflare's runtime type declarations, supplied by wrangler types or a compatible @cloudflare/workers-types package.
Application
import 'reflect-metadata';
import { Controller, Get, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { CloudflareModule, createWorker } from 'nestjs-cloudflare';
@Controller()
class AppController {
@Get()
hello(): string {
return 'Hello from Nest';
}
}
@Module({
imports: [CloudflareModule.forRoot()],
controllers: [AppController],
})
class AppModule {}
async function bootstrap() {
return NestFactory.create(AppModule, { rawBody: true });
}
export default createWorker(bootstrap);
createWorker synchronously returns Worker handlers. The first event runs bootstrap once, initializes the application, starts connected microservices by default, and opens its Node HTTP server on an ephemeral port if it is not already listening. Nest skips initialization when the application is already initialized. Later events share the same application. worker.getApplication() returns a promise for that application and also starts it when called by a Durable Object.
HTTP responses from the Node bridge have connection-specific headers removed under RFC 9110 section 7.6.1: Connection, Keep-Alive, Transfer-Encoding, TE, Trailer, Upgrade, Proxy-Authenticate, Proxy-Authorization, and any headers named by Connection. Bodies stream through unchanged. Status codes, status text, and other headers, including repeated Set-Cookie values, are preserved. Responses with status 101 or a webSocket, forwarded Durable Object responses, and application fallback responses are returned unchanged.
If bootstrap calls await app.startAllMicroservices(), pass { microservicesStarted: true } to createWorker to skip repeating that step. This lets applications finish startup before switching to their runtime logger. Bootstrap must start all connected microservices when this option is enabled; event dispatch remains unchanged.
async function bootstrap() {
const app = await NestFactory.create(AppModule, { logger: false });
await app.init();
await app.startAllMicroservices();
app.useLogger(app.get(AppLogger));
return app;
}
export default createWorker(bootstrap, { microservicesStarted: true });
AppLogger is the application's registered logger provider.
Keep Nest creation inside bootstrap. Cloudflare's upload validation runs module initialization without all bindings and disallows I/O and random number generation. Deferring Nest startup to an event avoids those restrictions. Choose HTTP adapters, application options, global guards, pipes, filters, and interceptors in your bootstrap function.
For incremental HTTP migration, pass a native fallback. fetch checks the initialized Express route table before dispatch and leaves unmatched request bodies untouched:
import { CloudflareRequestContext } from 'nestjs-cloudflare';
const worker = createWorker(bootstrap, {
fallback: {
async fetch(request, env, ctx) {
const app = await worker.getApplication();
const error = app.get(CloudflareRequestContext).getRouteError();
if (error) return new Response('Invalid route encoding', { status: 400 });
return legacyRouter.fetch(request, env, ctx);
},
},
routing: { headImplicitMatch: false },
});
await worker.matches(request); // true for a configured WebSocket path or Nest route
Configure Express before constructing the Nest adapter so its router uses the
same settings during pre-matching and dispatch:
import express from 'express';
import { ExpressAdapter } from '@nestjs/platform-express';
async function bootstrap() {
const instance = express();
instance.set('case sensitive routing', true);
instance.set('strict routing', true);
return NestFactory.create(AppModule, new ExpressAdapter(instance));
}
The optional routing.caseSensitive and routing.strict values validate these
Express settings. Their aliases are caseSensitiveRouting and strictRouting.
A mismatch fails startup with instructions to configure Express before creating
the adapter. They do not change an existing router. Omit them to use the
bootstrap settings. The default Express configuration remains case-insensitive
and accepts trailing slashes.
Set routing.headImplicitMatch: false when a HEAD request should match only
an explicitly registered HEAD route. Unmatched requests go to fallback.fetch.
The default preserves Express's implicit GET handling.
Use around.fetch, around.scheduled, or around.queue to wrap complete event dispatch. Each hook receives the native event values and a next function. CloudflareRequestContext is a singleton provider exported by CloudflareModule.forRoot(); inject it to read getRequest(), getEnv(), getExecutionContext(), and getRouteError() from the current event. When Express cannot decode a route parameter, pre-matching sends the request to fallback.fetch and getRouteError() returns the URIError.
Bindings
CloudflareModule.forRoot() registers global providers for the bindings in cloudflare:workers' imported env. Import it once in the root module. Bindings are injected directly, including primitive variables.
import { Inject, Injectable } from '@nestjs/common';
import {
CLOUDFLARE_ENV,
InjectBinding,
getBindingToken,
} from 'nestjs-cloudflare';
interface Env {
STATE: KVNamespace;
LABEL: string;
}
@Injectable()
class StateService {
constructor(
@InjectBinding<Env>('STATE') private readonly state: KVNamespace,
@Inject(CLOUDFLARE_ENV) private readonly env: Env,
) {}
read(): Promise<string | null> {
return this.state.get(this.env.LABEL);
}
}
const stateToken = getBindingToken<Env>('STATE');
RPC bindings expose callable lifecycle properties, so they are excluded from individual providers to prevent Nest from invoking remote lifecycle methods. Inject CLOUDFLARE_ENV and call the binding through env.MY_SERVICE instead. Using @InjectBinding for an RPC binding produces Nest's unresolved-dependency error.
The optional generic restricts binding names to keys of the application's environment. Injecting a binding absent from the runtime environment produces Nest's unresolved-dependency error. Tests can configure bindings in Miniflare or scope imported env with withEnv from cloudflare:workers before creating the application.
Scheduled events
Install @nestjs/schedule, import CloudflareScheduleModule.forRoot() from nestjs-cloudflare/schedule, and use the official decorator:
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { env } from 'cloudflare:workers';
@Injectable()
class DigestService {
@Cron(env.DIGEST_CRON as string)
async digest(controller: ScheduledController): Promise<void> {
await env.STATE.put('last-cron', controller.cron);
}
}
Register the service as a provider. Do not import Nest's ScheduleModule: Cloudflare supplies scheduled events, so no in-process timer is needed. Configure the variable and trigger together in Wrangler:
{
"vars": { "DIGEST_CRON": "0 8 * * *" },
"triggers": { "crons": ["0 8 * * *"] },
}
Expressions must have five fields and match ScheduledController.cron exactly. Workers schedules use UTC. Empty and six-field expressions produce startup warnings; six-field values from Nest's CronExpression enum cannot match Workers triggers. Every matching method runs. Non-static providers are skipped with a warning.
disabled suppresses a handler. waitForCompletion skips overlapping invocations within one isolate. Timer-specific options such as timeZone do not configure Cloudflare triggers. scheduled() waits for all matching handlers to finish and rejects with an AggregateError if any handler fails. Unmatched events use fallback.scheduled when provided and otherwise produce a warning.
Queues
Install @nestjs/microservices. Connect the queue transport during bootstrap so Nest can register handlers and inherit application configuration:
import { CloudflareQueueServer } from 'nestjs-cloudflare/queue';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice(
{ strategy: new CloudflareQueueServer({ noAck: true }) },
{ inheritAppConfig: true },
);
return app;
}
Register a producer through Nest's ClientsModule and inject its client:
import { Inject, Injectable, Module } from '@nestjs/common';
import { ClientProxy, ClientsModule } from '@nestjs/microservices';
import { env } from 'cloudflare:workers';
import { firstValueFrom } from 'rxjs';
import { CloudflareQueueClient } from 'nestjs-cloudflare/queue';
@Injectable()
class NotificationsService {
constructor(@Inject('NOTIFICATIONS') private readonly client: ClientProxy) {}
async notify(text: string): Promise<void> {
await firstValueFrom(this.client.emit('notifications', text));
}
}
@Module({
imports: [
ClientsModule.register([
{
name: 'NOTIFICATIONS',
customClass: CloudflareQueueClient,
options: { queue: env.NOTIFICATIONS },
},
]),
],
providers: [NotificationsService],
})
class NotificationsModule {}
Use CloudflareQueueRecordBuilder to attach native QueueSendOptions, following Nest's transport record builder convention:
import { CloudflareQueueRecordBuilder } from 'nestjs-cloudflare/queue';
const record = new CloudflareQueueRecordBuilder({ id: 'activity' })
.setOptions({ delaySeconds: 60, contentType: 'json' })
.build();
await firstValueFrom(client.emit('notifications', record));
The default serializer unwraps the record and passes its options to queue.send. Options are not included in the message body. A custom serializer replaces the default and must return { ...packet, data, options } to use send options.
For dependency injection into the client factory, use ClientsModule.registerAsync with inject: [getBindingToken<Env>('NOTIFICATIONS')] and return { customClass: CloudflareQueueClient, options: { queue } }. Client and server options accept Nest serializers and deserializers. emit sends the Nest event packet, preserving its pattern and metadata. One Queue can carry multiple patterns. send rejects because Cloudflare Queues do not support request-response messaging.
connect(), unwrap(), and emit() report a missing or invalid Queue binding with a plain Error: Missing or invalid Queue binding: queue. Here queue names the client option; clients receive the binding value rather than its environment key.
import { Controller } from '@nestjs/common';
import { InjectBinding } from 'nestjs-cloudflare';
import { Ctx, EventPattern, Payload } from '@nestjs/microservices';
import {
CLOUDFLARE_QUEUE_TRANSPORT,
CloudflareQueueContext,
} from 'nestjs-cloudflare/queue';
@Controller()
class NotificationsController {
constructor(@InjectBinding('STATE') private readonly state: KVNamespace) {}
@EventPattern('notifications', CLOUDFLARE_QUEUE_TRANSPORT)
async receive(
@Payload() text: string,
@Ctx() context: CloudflareQueueContext,
): Promise<void> {
await this.state.put('last-notification', text);
}
}
The context exposes the original message, batch, execution context, and pattern. For messages sent by other producers without a Nest packet, the Queue name is the event pattern. Successful messages are acknowledged automatically by default. Set noAck: false for manual acknowledgement. A handler can discard an invalid message with context.getMessage().ack() or retry a locked message with context.getMessage().retry({ delaySeconds: 30 }). Return normally after either call so the handler controls that message's outcome. Failed handlers request retries in either mode.
Batches are sequential by default. Set concurrency: 'parallel' on the server to process messages concurrently. Unhandled messages use fallback.queue when supplied. Missing transports and unhandled events are reported explicitly. Fallbacks are passed as the second argument to createWorker:
const worker = createWorker(bootstrap, {
fallback: {
async queue(batch, env, ctx) {
batch.ackAll();
},
async scheduled(controller, env, ctx) {
await env.STATE.put('unmatched-cron', controller.cron);
},
},
});
Durable Objects
A native Durable Object can resolve Nest services through the application's asynchronous accessor:
import { DurableObject } from 'cloudflare:workers';
const worker = createWorker(bootstrap);
export class Greeter extends DurableObject<Env> {
async fetch(): Promise<Response> {
const app = await worker.getApplication();
return new Response(app.get(GreetingService).greet());
}
}
export default worker;
For Nest @MessagePattern calls through ClientProxy.send() and native alarms through @EventPattern, use CloudflareDurableObject as described in Durable Object microservices. Both WebSocket hosts can enable the same transport through their optional transport configuration, so one object can serve sockets, RPC messages, and alarms.
Register the service as an application provider. Register Greeter in Wrangler's durable_objects.bindings and add a SQLite migration, as shown in example/wrangler.jsonc. Durable Object storage remains available through the object's own context.
WebSockets and hibernation
Install @nestjs/websockets and import the adapter and Durable Object base class from nestjs-cloudflare/websockets. Socket.IO and @nestjs/platform-ws are not needed.
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
} from '@nestjs/websockets';
import {
CloudflareWebSocketAdapter,
CloudflareWebSocketDurableObject,
} from 'nestjs-cloudflare/websockets';
@WebSocketGateway({ path: '/chat' })
class ChatGateway {
@SubscribeMessage('echo')
echo(@MessageBody() data: unknown): unknown {
return data;
}
}
const adapter = new CloudflareWebSocketAdapter();
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(adapter);
return app;
}
const worker = createWorker(bootstrap);
export class ChatRoom extends CloudflareWebSocketDurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env, {
adapter,
path: '/chat',
getApplication: worker.getApplication,
});
}
}
Register the gateway as an application provider. Configure the Durable Object binding and migration, then declare native forwarding in createWorker:
const worker = createWorker<Env>(bootstrap, {
websockets: [{ paths: ['/chat'], binding: 'CHAT', object: 'shared-chat' }],
});
Each entry selects exact URL pathnames, a Durable Object namespace binding from the event's env, and an object name. For a shared API object, use { paths: ['/ws', '/mobula'], binding: 'API_WEBSOCKET', object: 'api-websocket' }. These paths must also be configured on the object's gateway host and declared with @WebSocketGateway({ path }). Entries are checked in order; the first matching entry wins. Matching is case-sensitive, distinguishes trailing slashes, ignores query strings, and is independent of Express routing settings.