nestjs-cloudflare 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +583 -2
  3. package/dist/bindings/get-binding-token.d.ts +6 -0
  4. package/dist/bindings/get-binding-token.js +8 -0
  5. package/dist/cloudflare.module.d.ts +11 -0
  6. package/dist/cloudflare.module.js +55 -0
  7. package/dist/constants.d.ts +6 -0
  8. package/dist/constants.js +6 -0
  9. package/dist/decorators/inject-binding.decorator.d.ts +7 -0
  10. package/dist/decorators/inject-binding.decorator.js +10 -0
  11. package/dist/durable-objects/client.d.ts +13 -0
  12. package/dist/durable-objects/client.js +67 -0
  13. package/dist/durable-objects/constants.d.ts +1 -0
  14. package/dist/durable-objects/constants.js +1 -0
  15. package/dist/durable-objects/context.d.ts +18 -0
  16. package/dist/durable-objects/context.js +53 -0
  17. package/dist/durable-objects/context.transport.d.ts +9 -0
  18. package/dist/durable-objects/context.transport.js +13 -0
  19. package/dist/durable-objects/durable-object.d.ts +11 -0
  20. package/dist/durable-objects/durable-object.js +21 -0
  21. package/dist/durable-objects/index.d.ts +9 -0
  22. package/dist/durable-objects/index.js +7 -0
  23. package/dist/durable-objects/interfaces/client-options.interface.d.ts +15 -0
  24. package/dist/durable-objects/interfaces/client-options.interface.js +1 -0
  25. package/dist/durable-objects/interfaces/server-options.interface.d.ts +14 -0
  26. package/dist/durable-objects/interfaces/server-options.interface.js +1 -0
  27. package/dist/durable-objects/record-builder.d.ts +16 -0
  28. package/dist/durable-objects/record-builder.js +28 -0
  29. package/dist/durable-objects/record.serializer.d.ts +10 -0
  30. package/dist/durable-objects/record.serializer.js +10 -0
  31. package/dist/durable-objects/server.d.ts +16 -0
  32. package/dist/durable-objects/server.js +101 -0
  33. package/dist/index.d.ts +12 -0
  34. package/dist/index.js +9 -0
  35. package/dist/interfaces/worker-options.interface.d.ts +45 -0
  36. package/dist/interfaces/worker-options.interface.js +1 -0
  37. package/dist/interfaces/worker.interface.d.ts +21 -0
  38. package/dist/interfaces/worker.interface.js +1 -0
  39. package/dist/queue/client.d.ts +19 -0
  40. package/dist/queue/client.js +44 -0
  41. package/dist/queue/constants.d.ts +6 -0
  42. package/dist/queue/constants.js +6 -0
  43. package/dist/queue/context.d.ts +25 -0
  44. package/dist/queue/context.js +27 -0
  45. package/dist/queue/index.d.ts +8 -0
  46. package/dist/queue/index.js +6 -0
  47. package/dist/queue/interfaces/client-options.interface.d.ts +14 -0
  48. package/dist/queue/interfaces/client-options.interface.js +1 -0
  49. package/dist/queue/interfaces/server-options.interface.d.ts +16 -0
  50. package/dist/queue/interfaces/server-options.interface.js +1 -0
  51. package/dist/queue/record-builder.d.ts +19 -0
  52. package/dist/queue/record-builder.js +32 -0
  53. package/dist/queue/record.serializer.d.ts +10 -0
  54. package/dist/queue/record.serializer.js +14 -0
  55. package/dist/queue/server.d.ts +28 -0
  56. package/dist/queue/server.js +102 -0
  57. package/dist/schedule/constants.d.ts +3 -0
  58. package/dist/schedule/constants.js +3 -0
  59. package/dist/schedule/cron.explorer.d.ts +20 -0
  60. package/dist/schedule/cron.explorer.js +121 -0
  61. package/dist/schedule/index.d.ts +1 -0
  62. package/dist/schedule/index.js +1 -0
  63. package/dist/schedule/schedule.module.d.ts +10 -0
  64. package/dist/schedule/schedule.module.js +33 -0
  65. package/dist/websockets/adapter.d.ts +76 -0
  66. package/dist/websockets/adapter.js +186 -0
  67. package/dist/websockets/context.d.ts +12 -0
  68. package/dist/websockets/context.js +15 -0
  69. package/dist/websockets/durable-object.d.ts +24 -0
  70. package/dist/websockets/durable-object.js +77 -0
  71. package/dist/websockets/gateway-durable-object.d.ts +17 -0
  72. package/dist/websockets/gateway-durable-object.js +82 -0
  73. package/dist/websockets/index.d.ts +11 -0
  74. package/dist/websockets/index.js +5 -0
  75. package/dist/websockets/interfaces/adapter-options.interface.d.ts +14 -0
  76. package/dist/websockets/interfaces/adapter-options.interface.js +1 -0
  77. package/dist/websockets/interfaces/durable-object-options.interface.d.ts +15 -0
  78. package/dist/websockets/interfaces/durable-object-options.interface.js +1 -0
  79. package/dist/websockets/interfaces/gateway-options.interface.d.ts +11 -0
  80. package/dist/websockets/interfaces/gateway-options.interface.js +1 -0
  81. package/dist/websockets/interfaces/message.interface.d.ts +11 -0
  82. package/dist/websockets/interfaces/message.interface.js +1 -0
  83. package/dist/websockets/interfaces/server.interface.d.ts +9 -0
  84. package/dist/websockets/interfaces/server.interface.js +1 -0
  85. package/dist/websockets/invalid-message.exception.d.ts +8 -0
  86. package/dist/websockets/invalid-message.exception.js +11 -0
  87. package/dist/websockets/message-dispatcher.d.ts +8 -0
  88. package/dist/websockets/message-dispatcher.js +26 -0
  89. package/dist/worker/create-worker.d.ts +11 -0
  90. package/dist/worker/create-worker.js +223 -0
  91. package/dist/worker/request-context.d.ts +19 -0
  92. package/dist/worker/request-context.js +38 -0
  93. package/dist/worker/websocket-routing.d.ts +3 -0
  94. package/dist/worker/websocket-routing.js +10 -0
  95. package/package.json +111 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 blockchainian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,584 @@
1
- # Temporary Holding Version
1
+ # nestjs-cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run a Nest application on Cloudflare Workers with binding injection, scheduled events, Queues, and hibernating Durable Object WebSockets.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install nestjs-cloudflare
9
+ npm install @nestjs/common @nestjs/core reflect-metadata rxjs
10
+ ```
11
+
12
+ 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.
13
+
14
+ 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.
15
+
16
+ ## Application
17
+
18
+ ```ts
19
+ import 'reflect-metadata';
20
+ import { Controller, Get, Module } from '@nestjs/common';
21
+ import { NestFactory } from '@nestjs/core';
22
+ import { CloudflareModule, createWorker } from 'nestjs-cloudflare';
23
+
24
+ @Controller()
25
+ class AppController {
26
+ @Get()
27
+ hello(): string {
28
+ return 'Hello from Nest';
29
+ }
30
+ }
31
+
32
+ @Module({
33
+ imports: [CloudflareModule.forRoot()],
34
+ controllers: [AppController],
35
+ })
36
+ class AppModule {}
37
+
38
+ async function bootstrap() {
39
+ return NestFactory.create(AppModule, { rawBody: true });
40
+ }
41
+
42
+ export default createWorker(bootstrap);
43
+ ```
44
+
45
+ `createWorker` synchronously returns Worker handlers. The first event runs `bootstrap` once, initializes the application, starts connected microservices, and opens its Node HTTP server on an ephemeral port. Later events share the same application. `worker.getApplication()` returns a promise for that application and also starts it when called by a Durable Object.
46
+
47
+ 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.
48
+
49
+ For incremental HTTP migration, pass a native fallback. `fetch` checks the initialized Express route table before dispatch and leaves unmatched request bodies untouched:
50
+
51
+ ```ts
52
+ import { CloudflareRequestContext } from 'nestjs-cloudflare';
53
+
54
+ const worker = createWorker(bootstrap, {
55
+ fallback: {
56
+ async fetch(request, env, ctx) {
57
+ const app = await worker.getApplication();
58
+ const error = app.get(CloudflareRequestContext).getRouteError();
59
+ if (error) return new Response('Invalid route encoding', { status: 400 });
60
+ return legacyRouter.fetch(request, env, ctx);
61
+ },
62
+ },
63
+ routing: { headImplicitMatch: false },
64
+ });
65
+
66
+ await worker.matches(request); // true for a configured WebSocket path or Nest route
67
+ ```
68
+
69
+ Configure Express before constructing the Nest adapter so its router uses the
70
+ same settings during pre-matching and dispatch:
71
+
72
+ ```ts
73
+ import express from 'express';
74
+ import { ExpressAdapter } from '@nestjs/platform-express';
75
+
76
+ async function bootstrap() {
77
+ const instance = express();
78
+ instance.set('case sensitive routing', true);
79
+ instance.set('strict routing', true);
80
+ return NestFactory.create(AppModule, new ExpressAdapter(instance));
81
+ }
82
+ ```
83
+
84
+ The optional `routing.caseSensitive` and `routing.strict` values validate these
85
+ Express settings. Their aliases are `caseSensitiveRouting` and `strictRouting`.
86
+ A mismatch fails startup with instructions to configure Express before creating
87
+ the adapter. They do not change an existing router. Omit them to use the
88
+ bootstrap settings. The default Express configuration remains case-insensitive
89
+ and accepts trailing slashes.
90
+
91
+ Set `routing.headImplicitMatch: false` when a `HEAD` request should match only
92
+ an explicitly registered `HEAD` route. Unmatched requests go to `fallback.fetch`.
93
+ The default preserves Express's implicit `GET` handling.
94
+
95
+ 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`.
96
+
97
+ ## Bindings
98
+
99
+ `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.
100
+
101
+ ```ts
102
+ import { Inject, Injectable } from '@nestjs/common';
103
+ import {
104
+ CLOUDFLARE_ENV,
105
+ InjectBinding,
106
+ getBindingToken,
107
+ } from 'nestjs-cloudflare';
108
+
109
+ interface Env {
110
+ STATE: KVNamespace;
111
+ LABEL: string;
112
+ }
113
+
114
+ @Injectable()
115
+ class StateService {
116
+ constructor(
117
+ @InjectBinding<Env>('STATE') private readonly state: KVNamespace,
118
+ @Inject(CLOUDFLARE_ENV) private readonly env: Env,
119
+ ) {}
120
+
121
+ read(): Promise<string | null> {
122
+ return this.state.get(this.env.LABEL);
123
+ }
124
+ }
125
+
126
+ const stateToken = getBindingToken<Env>('STATE');
127
+ ```
128
+
129
+ 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.
130
+
131
+ 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.
132
+
133
+ ## Scheduled events
134
+
135
+ Install `@nestjs/schedule`, import `CloudflareScheduleModule.forRoot()` from `nestjs-cloudflare/schedule`, and use the official decorator:
136
+
137
+ ```ts
138
+ import { Injectable } from '@nestjs/common';
139
+ import { Cron } from '@nestjs/schedule';
140
+ import { env } from 'cloudflare:workers';
141
+
142
+ @Injectable()
143
+ class DigestService {
144
+ @Cron(env.DIGEST_CRON as string)
145
+ async digest(controller: ScheduledController): Promise<void> {
146
+ await env.STATE.put('last-cron', controller.cron);
147
+ }
148
+ }
149
+ ```
150
+
151
+ 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:
152
+
153
+ ```jsonc
154
+ {
155
+ "vars": { "DIGEST_CRON": "0 8 * * *" },
156
+ "triggers": { "crons": ["0 8 * * *"] },
157
+ }
158
+ ```
159
+
160
+ 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.
161
+
162
+ `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.
163
+
164
+ ## Queues
165
+
166
+ Install `@nestjs/microservices`. Connect the queue transport during bootstrap so Nest can register handlers and inherit application configuration:
167
+
168
+ ```ts
169
+ import { CloudflareQueueServer } from 'nestjs-cloudflare/queue';
170
+
171
+ async function bootstrap() {
172
+ const app = await NestFactory.create(AppModule);
173
+ app.connectMicroservice(
174
+ { strategy: new CloudflareQueueServer({ noAck: true }) },
175
+ { inheritAppConfig: true },
176
+ );
177
+ return app;
178
+ }
179
+ ```
180
+
181
+ Register a producer through Nest's `ClientsModule` and inject its client:
182
+
183
+ ```ts
184
+ import { Inject, Injectable, Module } from '@nestjs/common';
185
+ import { ClientProxy, ClientsModule } from '@nestjs/microservices';
186
+ import { env } from 'cloudflare:workers';
187
+ import { firstValueFrom } from 'rxjs';
188
+ import { CloudflareQueueClient } from 'nestjs-cloudflare/queue';
189
+
190
+ @Injectable()
191
+ class NotificationsService {
192
+ constructor(@Inject('NOTIFICATIONS') private readonly client: ClientProxy) {}
193
+
194
+ async notify(text: string): Promise<void> {
195
+ await firstValueFrom(this.client.emit('notifications', text));
196
+ }
197
+ }
198
+
199
+ @Module({
200
+ imports: [
201
+ ClientsModule.register([
202
+ {
203
+ name: 'NOTIFICATIONS',
204
+ customClass: CloudflareQueueClient,
205
+ options: { queue: env.NOTIFICATIONS },
206
+ },
207
+ ]),
208
+ ],
209
+ providers: [NotificationsService],
210
+ })
211
+ class NotificationsModule {}
212
+ ```
213
+
214
+ Use `CloudflareQueueRecordBuilder` to attach native `QueueSendOptions`, following Nest's transport record builder convention:
215
+
216
+ ```ts
217
+ import { CloudflareQueueRecordBuilder } from 'nestjs-cloudflare/queue';
218
+
219
+ const record = new CloudflareQueueRecordBuilder({ id: 'activity' })
220
+ .setOptions({ delaySeconds: 60, contentType: 'json' })
221
+ .build();
222
+
223
+ await firstValueFrom(client.emit('notifications', record));
224
+ ```
225
+
226
+ 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.
227
+
228
+ 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.
229
+
230
+ ```ts
231
+ import { Controller } from '@nestjs/common';
232
+ import { InjectBinding } from 'nestjs-cloudflare';
233
+ import { Ctx, EventPattern, Payload } from '@nestjs/microservices';
234
+ import {
235
+ CLOUDFLARE_QUEUE_TRANSPORT,
236
+ CloudflareQueueContext,
237
+ } from 'nestjs-cloudflare/queue';
238
+
239
+ @Controller()
240
+ class NotificationsController {
241
+ constructor(@InjectBinding('STATE') private readonly state: KVNamespace) {}
242
+
243
+ @EventPattern('notifications', CLOUDFLARE_QUEUE_TRANSPORT)
244
+ async receive(
245
+ @Payload() text: string,
246
+ @Ctx() context: CloudflareQueueContext,
247
+ ): Promise<void> {
248
+ await this.state.put('last-notification', text);
249
+ }
250
+ }
251
+ ```
252
+
253
+ 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.
254
+
255
+ 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`:
256
+
257
+ ```ts
258
+ const worker = createWorker(bootstrap, {
259
+ fallback: {
260
+ async queue(batch, env, ctx) {
261
+ batch.ackAll();
262
+ },
263
+ async scheduled(controller, env, ctx) {
264
+ await env.STATE.put('unmatched-cron', controller.cron);
265
+ },
266
+ },
267
+ });
268
+ ```
269
+
270
+ ## Durable Objects
271
+
272
+ A native Durable Object can resolve Nest services through the application's asynchronous accessor:
273
+
274
+ ```ts
275
+ import { DurableObject } from 'cloudflare:workers';
276
+
277
+ const worker = createWorker(bootstrap);
278
+
279
+ export class Greeter extends DurableObject<Env> {
280
+ async fetch(): Promise<Response> {
281
+ const app = await worker.getApplication();
282
+ return new Response(app.get(GreetingService).greet());
283
+ }
284
+ }
285
+
286
+ export default worker;
287
+ ```
288
+
289
+ 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.
290
+
291
+ ## WebSockets and hibernation
292
+
293
+ 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.
294
+
295
+ ```ts
296
+ import {
297
+ MessageBody,
298
+ SubscribeMessage,
299
+ WebSocketGateway,
300
+ } from '@nestjs/websockets';
301
+ import {
302
+ CloudflareWebSocketAdapter,
303
+ CloudflareWebSocketDurableObject,
304
+ } from 'nestjs-cloudflare/websockets';
305
+
306
+ @WebSocketGateway({ path: '/chat' })
307
+ class ChatGateway {
308
+ @SubscribeMessage('echo')
309
+ echo(@MessageBody() data: unknown): unknown {
310
+ return data;
311
+ }
312
+ }
313
+
314
+ const adapter = new CloudflareWebSocketAdapter();
315
+
316
+ async function bootstrap() {
317
+ const app = await NestFactory.create(AppModule);
318
+ app.useWebSocketAdapter(adapter);
319
+ return app;
320
+ }
321
+
322
+ const worker = createWorker(bootstrap);
323
+
324
+ export class ChatRoom extends CloudflareWebSocketDurableObject<Env> {
325
+ constructor(ctx: DurableObjectState, env: Env) {
326
+ super(ctx, env, {
327
+ adapter,
328
+ path: '/chat',
329
+ getApplication: worker.getApplication,
330
+ });
331
+ }
332
+ }
333
+ ```
334
+
335
+ Register the gateway as an application provider. Configure the Durable Object binding and migration, then declare native forwarding in `createWorker`:
336
+
337
+ ```ts
338
+ const worker = createWorker<Env>(bootstrap, {
339
+ websockets: [{ paths: ['/chat'], binding: 'CHAT', object: 'shared-chat' }],
340
+ });
341
+ ```
342
+
343
+ 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.
344
+
345
+ Use `object: request => new URL(request.url).searchParams.get('room') ?? 'default'` to select a name per request. Strings are resolved with the namespace's `idFromName()`. A resolver may instead return a native `DurableObjectId`, such as `object: request => env.CHAT.idFromString(new URL(request.url).searchParams.get('id')!)`.
346
+
347
+ Forwarding runs inside `around.fetch`, before Express and `fallback.fetch`. The original request, including its URL, headers, and body, goes directly to `namespace.get(id).fetch(request)`. The object's response is returned unchanged, including the WebSocket on a `101` response. Matching non-upgrade requests also go to the object: both gateway hosts return `426` by default, and `CloudflareWebSocketGatewayDurableObject` subclasses can override `nonWebSocketFetch`. `worker.matches(request)` returns `true` for configured paths regardless of method or upgrade headers, without starting Nest or calling the object resolver. Unmatched paths retain the usual Nest and fallback behavior.
348
+
349
+ `CloudflareWebSocketAdapter` accepts `maxConcurrentMessages`, matching Nest's `@nestjs/platform-ws` option. The default is `1000`, so asynchronous messages on one connection can overlap. Use `new CloudflareWebSocketAdapter({ maxConcurrentMessages: 1 })` when authentication must finish before a later subscription is handled. The limit applies per connection to both Durable Object hosts, including messages delivered through `webSocketMessage` after hibernation. Other connections can keep processing independently. An in-progress handler must finish before the next queued message starts when the limit is `1`.
350
+
351
+ Gateways use port `0`, the default. Separate listening ports and Socket.IO namespaces are unsupported.
352
+
353
+ The base class implements `fetch`, `webSocketMessage`, `webSocketClose`, and `webSocketError`. It accepts connections through `ctx.acceptWebSocket` and waits for Nest startup before dispatching events after hibernation. Restored connections are registered with Nest again, so `handleConnection` can run more than once for a socket. Singleton gateways are shared by the application. Inject durable providers for object-owned I/O and keep persistent room state in Durable Object storage or socket attachments.
354
+
355
+ For Durable Objects that must keep in-memory sessions, timers, and upstream sockets, use the non-hibernating gateway host. It calls `server.accept()` and keeps each object's sockets isolated:
356
+
357
+ ```ts
358
+ import {
359
+ ConnectedSocket,
360
+ SubscribeMessage,
361
+ WebSocketGateway,
362
+ } from '@nestjs/websockets';
363
+ import {
364
+ CloudflareWebSocketAdapter,
365
+ CloudflareWebSocketGatewayDurableObject,
366
+ getCloudflareWebSocketContext,
367
+ } from 'nestjs-cloudflare/websockets';
368
+
369
+ @WebSocketGateway({ path: '/ws' })
370
+ @WebSocketGateway({ path: '/mobula' })
371
+ class ApiGateway {
372
+ @SubscribeMessage('publish')
373
+ publish(@ConnectedSocket() socket: WebSocket, value: unknown): null {
374
+ const { sockets } = getCloudflareWebSocketContext(socket);
375
+ for (const peer of sockets) {
376
+ peer.send(JSON.stringify(value));
377
+ }
378
+ return null;
379
+ }
380
+ }
381
+
382
+ const adapter = new CloudflareWebSocketAdapter({
383
+ messageSerializer: value => JSON.stringify(value),
384
+ });
385
+
386
+ export class ApiWebSocket extends CloudflareWebSocketGatewayDurableObject<Env> {
387
+ constructor(ctx: DurableObjectState, env: Env) {
388
+ super(ctx, env, {
389
+ adapter,
390
+ paths: ['/ws', '/mobula'],
391
+ getApplication: worker.getApplication,
392
+ });
393
+ }
394
+
395
+ protected nonWebSocketFetch(request: Request): Response {
396
+ return new Response(`internal:${new URL(request.url).pathname}`);
397
+ }
398
+ }
399
+ ```
400
+
401
+ `getCloudflareWebSocketContext(socket)` exposes the owning object's `ctx`, `storage`, `env`, object instance, and in-memory `sockets` set. `messageSerializer` may return a string or `ArrayBuffer`, so binary or protocol-specific frames are supported. The `paths` list lets one Durable Object serve multiple gateway paths; in the example the same gateway handles `/ws` and `/mobula`. Override `nonWebSocketFetch` for the object's other requests.
402
+
403
+ Clients send `{"event":"echo","data":"hello"}`. The handler receives `data` and its return value is JSON-serialized directly to the client. Promise and observable results are supported. Configure `messageParser` for another wire protocol:
404
+
405
+ ```ts
406
+ const adapter = new CloudflareWebSocketAdapter({
407
+ messageParser: frame => {
408
+ if (typeof frame !== 'string') {
409
+ return;
410
+ }
411
+ return { event: 'echo', data: frame };
412
+ },
413
+ });
414
+ ```
415
+
416
+ A parser can return `undefined` to ignore a frame. The default parser closes malformed JSON messages with code `1007`. A custom parser can throw `InvalidWebSocketMessageException` for that close code; unexpected failures close with `1011`.
417
+
418
+ ## Durable Object microservices
419
+
420
+ Install `@nestjs/microservices`. Connect a `CloudflareDurableObjectServer` during bootstrap, just like the Queue transport. Import `CloudflareModule.forRoot()` in `AppModule` to provide `CloudflareRequestContext`.
421
+
422
+ ```ts
423
+ import { NestFactory } from '@nestjs/core';
424
+ import {
425
+ CloudflareDurableObject,
426
+ CloudflareDurableObjectServer,
427
+ } from 'nestjs-cloudflare/durable-objects';
428
+
429
+ const transport = new CloudflareDurableObjectServer();
430
+ let application: ReturnType<typeof bootstrap> | undefined;
431
+
432
+ async function bootstrap() {
433
+ const app = await NestFactory.create(AppModule);
434
+ app.connectMicroservice({ strategy: transport }, { inheritAppConfig: true });
435
+ await app.init();
436
+ await app.startAllMicroservices();
437
+ return app;
438
+ }
439
+
440
+ export class JobLease extends CloudflareDurableObject<Env> {
441
+ constructor(state: DurableObjectState, env: Env) {
442
+ super(state, env, {
443
+ server: transport,
444
+ getApplication: () => (application ??= bootstrap()),
445
+ alarmPattern: 'alarm',
446
+ });
447
+ }
448
+ }
449
+ ```
450
+
451
+ Export the class from the Worker entry point and register it in Wrangler's Durable Object bindings and migrations. This transport uses native Workers RPC and requires a compatibility date of `2024-04-03` or later. It does not expose an HTTP URL. Each message carries Nest's pattern and data to the object's `dispatch` RPC method.
452
+
453
+ Register handlers as Nest controllers. `@Ctx()` receives the native state, environment, and normalized pattern. Durable providers use the same object isolation described below; ordinary request providers are recreated for each invocation.
454
+
455
+ ```ts
456
+ import { Controller, Injectable, Scope } from '@nestjs/common';
457
+ import {
458
+ Ctx,
459
+ EventPattern,
460
+ MessagePattern,
461
+ Payload,
462
+ } from '@nestjs/microservices';
463
+ import { CloudflareDurableObjectContext } from 'nestjs-cloudflare/durable-objects';
464
+
465
+ @Injectable({ scope: Scope.REQUEST, durable: true })
466
+ class LeaseService {
467
+ async acquire(state: DurableObjectState, owner: string) {
468
+ return state.storage.transaction(async storage => {
469
+ if (await storage.get('owner')) {
470
+ return { acquired: false };
471
+ }
472
+ await storage.put('owner', owner);
473
+ return { acquired: true };
474
+ });
475
+ }
476
+ }
477
+
478
+ @Controller()
479
+ class LeaseController {
480
+ constructor(private readonly leases: LeaseService) {}
481
+
482
+ @MessagePattern('acquire')
483
+ acquire(
484
+ @Payload() owner: string,
485
+ @Ctx() context: CloudflareDurableObjectContext,
486
+ ) {
487
+ return this.leases.acquire(context.getState(), owner);
488
+ }
489
+
490
+ @EventPattern('alarm')
491
+ async alarm(@Ctx() context: CloudflareDurableObjectContext) {
492
+ await context.getState().storage.delete('owner');
493
+ }
494
+ }
495
+ ```
496
+
497
+ Register `LeaseController` in `controllers` and `LeaseService` in `providers`. Schedule alarms with `context.getState().storage.setAlarm(timestamp)`. The base class dispatches native alarms to `@EventPattern('alarm')`, or to the configured `alarmPattern`, and awaits completion so failures can trigger Cloudflare's alarm retries. Alarm data is `undefined`.
498
+
499
+ Register the client through `ClientsModule` and select the target separately for each message using Nest's record builder convention:
500
+
501
+ ```ts
502
+ import { ClientsModule } from '@nestjs/microservices';
503
+ import { env } from 'cloudflare:workers';
504
+ import { firstValueFrom } from 'rxjs';
505
+ import {
506
+ CloudflareDurableObjectClient,
507
+ CloudflareDurableObjectRecordBuilder,
508
+ } from 'nestjs-cloudflare/durable-objects';
509
+
510
+ const clients = ClientsModule.register([
511
+ {
512
+ name: 'JOB_LEASES',
513
+ customClass: CloudflareDurableObjectClient,
514
+ options: { namespace: env.JOB_LEASES },
515
+ },
516
+ ]);
517
+
518
+ // Import clients in a Nest module and inject its ClientProxy with @Inject('JOB_LEASES').
519
+ const record = new CloudflareDurableObjectRecordBuilder('worker-owner')
520
+ .setOptions({ name: 'job:sync-feed' })
521
+ .build();
522
+ const result = await firstValueFrom(client.send('acquire', record));
523
+ ```
524
+
525
+ Use `{ id: durableObjectId.toString() }` instead of `{ name }` to address an existing ID. Address options stay outside handler data. `ClientsModule.registerAsync` can inject a namespace using `getBindingToken`, as with Queues. `emit` invokes `@EventPattern` handlers and awaits their completion.
526
+
527
+ Both client and server accept Nest serializers and deserializers. The default client serializer unwraps records into `{ ...packet, data, options }`; a replacement serializer must preserve that shape to select an object. `send` preserves the payload from `RpcException`, including structured error codes, as the Observable error. Handler Observable replies are collected until completion and returned in order by the RPC call; use finite streams.
528
+
529
+ `CloudflareRequestContext` is available inside request and alarm handlers. `getEnv()` returns the object's environment, `getRequest()` returns `undefined`, and `getExecutionContext()` returns its native `DurableObjectState`, including `waitUntil`. The execution-context type also permits Worker `ExecutionContext` for Worker events; narrow the union before using event-specific methods.
530
+
531
+ ## Durable Object dependency scopes
532
+
533
+ Mark providers that own upstream sockets, fetch streams, or timers with Nest's `@Injectable({ scope: Scope.REQUEST, durable: true })`. Both gateway hosts bind each accepted or restored socket to its owning Durable Object before Nest resolves the gateway. Nest's durable dependency tree is reused across connections and events in that object. Default singleton providers remain shared across the application, and ordinary request-scoped providers retain their event or connection scope.
534
+
535
+ ```ts
536
+ import { Injectable, Scope } from '@nestjs/common';
537
+ import { resolveForDurableObject } from 'nestjs-cloudflare';
538
+
539
+ @Injectable({ scope: Scope.REQUEST, durable: true })
540
+ class UpstreamClient {
541
+ // Create and retain upstream I/O here, in the owning object's event.
542
+ }
543
+
544
+ // Inside a native Durable Object's fetch, alarm, or RPC method:
545
+ const client = await resolveForDurableObject(
546
+ await worker.getApplication(),
547
+ this.ctx,
548
+ UpstreamClient,
549
+ );
550
+ ```
551
+
552
+ Register the provider in a Nest module. A gateway can inject it through its constructor; durability propagates through the dependency tree according to [Nest's durable provider rules](https://docs.nestjs.com/fundamentals/injection-scopes#durable-providers). In subclasses of either gateway host, use `await this.resolve(UpstreamClient)` from `fetch`, `nonWebSocketFetch`, `alarm`, or RPC handlers. Native Durable Objects use `resolveForDurableObject(app, ctx, token)` in each event. Resolve within the owning object's event so workerd also assigns any new I/O to that object.
553
+
554
+ The package installs `DurableObjectContextIdStrategy` globally through `ContextIdFactory.apply` on first use. It associates Nest event contexts with the object's state and ID, and selects their shared parent only for durable dependency trees. This occupies Nest's single global strategy slot; applications with another custom strategy must compose the strategies. `getDurableObjectContextId(ctx)` exposes the event context for direct Nest integration. The helper also registers the context payload, so `@Inject(REQUEST)` can receive `{ durableObjectId, ctx }`.
555
+
556
+ Context ownership is weakly keyed by the native `DurableObjectState`, so an evicted activation does not leave an isolate-wide ID cache behind. Hibernation, eviction, or isolate restart creates a new in-memory provider tree; durable providers do not persist sockets, timers, or JavaScript state across those boundaries. Use non-hibernating hosts when upstream sessions must stay in memory, and use Durable Object storage for persistent state. Nest does not run application lifecycle hooks for request-scoped providers; manage object-owned resources explicitly.
557
+
558
+ ## Build and local development
559
+
560
+ Compile application TypeScript with `experimentalDecorators` and `emitDecoratorMetadata` before Wrangler bundles the emitted JavaScript. Wrangler's esbuild compilation does not emit the metadata Nest needs for dependency injection. Enable `nodejs_compat` and `enable_nodejs_http_server_modules` for Node HTTP support.
561
+
562
+ ```sh
563
+ yarn install
564
+ yarn build
565
+ yarn lint
566
+ yarn test
567
+ yarn wrangler dev --config example/wrangler.jsonc --test-scheduled
568
+ ```
569
+
570
+ Wrangler runs `yarn build:example` and loads `dist-example/example/index.js`. Local KV, Queues, and Durable Objects need no remote resources. The placeholder KV namespace ID is for local use.
571
+
572
+ ```sh
573
+ curl http://localhost:8787/
574
+ curl http://localhost:8787/durable
575
+ curl -X POST http://localhost:8787/notifications \
576
+ -H 'content-type: application/json' -d '{"text":"Hello"}'
577
+ curl 'http://localhost:8787/cdn-cgi/handler/scheduled?cron=*/15%20*%20*%20*%20*'
578
+ curl http://localhost:8787/state/last-cron
579
+ curl http://localhost:8787/state/last-notification
580
+ ```
581
+
582
+ Run the gateway example with `yarn wrangler dev --config example/websockets/wrangler.jsonc`, then connect to `ws://localhost:8787/chat` and send the JSON echo message above.
583
+
584
+ Wrangler aliases resolve unused optional Nest integrations to `unsupported-dependency.ts`. Nest references optional transport and validation packages while bundling even when an application does not enable them. The alias target throws if evaluated. Remove an integration's alias and install its actual dependencies before enabling it. The gateway example keeps Nest's real WebSocket module; copying the basic example's WebSocket-module alias would disable gateway registration.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Returns the Nest injection token for a native Cloudflare binding.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export declare function getBindingToken<Env extends object = Record<string, unknown>>(name: Extract<keyof Env, string>): string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns the Nest injection token for a native Cloudflare binding.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export function getBindingToken(name) {
7
+ return `cloudflare:binding:${name}`;
8
+ }
@@ -0,0 +1,11 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ export { CloudflareRequestContext } from './worker/request-context.js';
3
+ /**
4
+ * Makes the native Cloudflare environment and its bindings available to Nest.
5
+ *
6
+ * @publicApi
7
+ */
8
+ export declare class CloudflareModule {
9
+ /** Registers the environment's bindings once in the application's root module. */
10
+ static forRoot(): DynamicModule;
11
+ }