|
| 1 | +# NodeBoot Cloudflare Server |
| 2 | + |
| 3 | +Cloudflare Workers server package for NodeBoot framework. Provides seamless integration with the Cloudflare Workers |
| 4 | +Fetch API while maintaining all NodeBoot features including dependency injection, middleware, routing, and error |
| 5 | +handling. |
| 6 | + |
| 7 | +## Features |
| 8 | + |
| 9 | +- **Multi-route Worker Functions**: Handle multiple HTTP routes in a single Cloudflare Worker |
| 10 | +- **Full NodeBoot Integration**: Complete support for controllers, services, middleware, and dependency injection |
| 11 | +- **Standard Fetch API**: Native support for the Web Fetch API `Request`/`Response` objects used by Cloudflare Workers |
| 12 | +- **Request/Response Handling**: Automatic parsing of JSON bodies, query parameters, headers, and cookies |
| 13 | +- **Error Handling**: Integrated error handling with proper HTTP status codes |
| 14 | +- **Authorization**: Built-in authorization support using NodeBoot's authorization system |
| 15 | +- **Environment Bindings**: Access to Worker environment bindings (KV, D1, secrets, etc.) via the action context |
| 16 | +- **Codegen-free routing**: Ships its own dependency-free `SimpleRouter` instead of `find-my-way`, since |
| 17 | + Workers' V8 isolate disallows `eval`/`new Function` (which `find-my-way` relies on internally) |
| 18 | + |
| 19 | +## Installation |
| 20 | + |
| 21 | +```bash |
| 22 | +npm install @nodeboot/cloudflare-server |
| 23 | +``` |
| 24 | + |
| 25 | +## Basic Usage |
| 26 | + |
| 27 | +### 1. Create your NodeBoot application |
| 28 | + |
| 29 | +```typescript |
| 30 | +import {NodeBoot, NodeBootApp, NodeBootApplication, NodeBootAppView} from "@nodeboot/core"; |
| 31 | +import {CloudflareServer} from "@nodeboot/cloudflare-server"; |
| 32 | +import {EnableDI} from "@nodeboot/di"; |
| 33 | +import {Container} from "typedi"; |
| 34 | + |
| 35 | +// A plain object, not a YAML file - see the note below. |
| 36 | +const appConfig = { |
| 37 | + app: {name: "my-app", platform: "node-boot"}, |
| 38 | + api: {routePrefix: "/api"}, |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * NodeBoot application entry point. |
| 43 | + * |
| 44 | + * Notice that, unlike the Express/Koa/Fastify samples, this application does not |
| 45 | + * "listen" on a port. Instead, it is bootstrapped once per Worker isolate (cold start) |
| 46 | + * and its `CloudflareServer` exposes a `fetch` handler function that the Cloudflare |
| 47 | + * runtime invokes for every incoming request. |
| 48 | + */ |
| 49 | +@EnableDI(Container) |
| 50 | +@NodeBootApplication() |
| 51 | +export class CloudflareSampleApp implements NodeBootApp { |
| 52 | + start(): Promise<NodeBootAppView> { |
| 53 | + // Cloudflare Workers have no filesystem, so `app-config.yaml`-style file-based config |
| 54 | + // discovery can never succeed at runtime. Pass your configuration in directly instead. |
| 55 | + return NodeBoot.run(CloudflareServer, appConfig); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +> **Note:** Unlike the Express/Koa/Fastify samples, this package does **not** support |
| 61 | +> `@EnableComponentScan()` (it relies on `fs.readdirSync`/`require.cache`, unavailable in |
| 62 | +> Workers). Import your controllers/services/middleware explicitly for their decorator side |
| 63 | +> effects instead - Wrangler's esbuild bundler will include them regardless. See the |
| 64 | +> [sample-cloudflare](../../samples/sample-cloudflare) README for the full rationale and every |
| 65 | +> other Workers-specific caveat (routing, dependency injection, logging, etc.). |
| 66 | +
|
| 67 | +### 2. Create your Worker entry point |
| 68 | + |
| 69 | +```typescript |
| 70 | +import {CloudflareHandler, CloudflareServer} from "@nodeboot/cloudflare-server"; |
| 71 | +import {CloudflareSampleApp} from "./app"; |
| 72 | + |
| 73 | +// Reused across warm invocations of the same Worker isolate. |
| 74 | +// Only re-initialized when Cloudflare spins up a brand-new isolate (cold start). |
| 75 | +let fetchHandler: CloudflareHandler | null = null; |
| 76 | + |
| 77 | +export default { |
| 78 | + async fetch(request: Request, env: Record<string, unknown>, ctx: ExecutionContext): Promise<Response> { |
| 79 | + if (!fetchHandler) { |
| 80 | + const app = await new CloudflareSampleApp().start(); |
| 81 | + const cloudflareServer = app.server as CloudflareServer; |
| 82 | + fetchHandler = cloudflareServer.getHandler(); |
| 83 | + } |
| 84 | + |
| 85 | + return fetchHandler(request, env, ctx); |
| 86 | + }, |
| 87 | +}; |
| 88 | +``` |
| 89 | + |
| 90 | +### 3. Create Controllers |
| 91 | + |
| 92 | +```typescript |
| 93 | +import {Controller, Get, Post, Param, Body} from "@nodeboot/core"; |
| 94 | + |
| 95 | +@Controller("/api") |
| 96 | +export class UserController { |
| 97 | + @Get("/users/:id") |
| 98 | + getUser(@Param("id") id: string) { |
| 99 | + return {id, name: `User ${id}`}; |
| 100 | + } |
| 101 | + |
| 102 | + @Post("/users") |
| 103 | + createUser(@Body() userData: any) { |
| 104 | + return {success: true, user: userData}; |
| 105 | + } |
| 106 | +} |
| 107 | +``` |
| 108 | + |
| 109 | +### 4. Deploy to Cloudflare Workers |
| 110 | + |
| 111 | +Bundle your Worker (e.g. with `wrangler` or `esbuild`) and deploy using [Wrangler](https://developers.cloudflare.com/workers/wrangler/): |
| 112 | + |
| 113 | +```bash |
| 114 | +wrangler deploy |
| 115 | +``` |
| 116 | + |
| 117 | +## Environment Bindings |
| 118 | + |
| 119 | +Cloudflare Workers environment bindings (KV namespaces, D1 databases, secrets, service bindings, etc.) are made |
| 120 | +available through the `response`/execution context passed to every request, so they can be reached from middleware |
| 121 | +and error handlers via `action.response.env`. |
| 122 | + |
| 123 | +## Middleware Support |
| 124 | + |
| 125 | +All NodeBoot middleware is supported: |
| 126 | + |
| 127 | +```typescript |
| 128 | +import {Middleware, MiddlewareInterface, Action} from "@nodeboot/core"; |
| 129 | + |
| 130 | +@Middleware({type: "before"}) |
| 131 | +export class LoggingMiddleware implements MiddlewareInterface { |
| 132 | + @Inject("logger") |
| 133 | + private logger: Logger; |
| 134 | + |
| 135 | + use(action: Action, payload: any): void { |
| 136 | + this.logger.info(`${action.request.method} ${action.request.url.pathname}`); |
| 137 | + } |
| 138 | +} |
| 139 | +``` |
| 140 | + |
| 141 | +> **Note:** Wrangler bundles your Worker with esbuild, which does not emit TypeScript decorator |
| 142 | +> metadata. Always use explicit injection tokens (`@Inject("logger")`, `@Inject(() => |
| 143 | +SomeService)`) rather than bare `@Inject()`, and prefer **property injection** over constructor |
| 144 | +> injection - without decorator metadata, TypeDI can't determine constructor arity and will |
| 145 | +> silently fail to inject constructor parameters. |
| 146 | +
|
| 147 | +## Error Handling |
| 148 | + |
| 149 | +Custom error handlers work seamlessly: |
| 150 | + |
| 151 | +```typescript |
| 152 | +import {ErrorHandler, ErrorHandlerInterface} from "@nodeboot/core"; |
| 153 | + |
| 154 | +@ErrorHandler() |
| 155 | +export class CustomErrorHandler implements ErrorHandlerInterface { |
| 156 | + onError(error: any, action: Action): void { |
| 157 | + // Custom error handling logic |
| 158 | + } |
| 159 | +} |
| 160 | +``` |
| 161 | + |
| 162 | +## Authorization |
| 163 | + |
| 164 | +NodeBoot's authorization system is fully supported. Use decorators like `@Authorize()` in your controllers to protect |
| 165 | +routes. |
| 166 | + |
| 167 | +```typescript |
| 168 | +import {Authorize, Controller, Get} from "@nodeboot/core"; |
| 169 | + |
| 170 | +@Controller("/secure") |
| 171 | +export class SecureController { |
| 172 | + @Get("/data") |
| 173 | + @Authorize("admin") |
| 174 | + getSecureData() { |
| 175 | + return {secret: "This is secure data"}; |
| 176 | + } |
| 177 | +} |
| 178 | +``` |
| 179 | + |
| 180 | +## Conclusion |
| 181 | + |
| 182 | +The NodeBoot Cloudflare Server package provides a powerful way to build serverless applications using the familiar |
| 183 | +NodeBoot framework. With full support for routing, middleware, error handling, and authorization, you can create |
| 184 | +robust APIs that run on Cloudflare Workers with ease. |
| 185 | + |
| 186 | +## License |
| 187 | + |
| 188 | +This project is licensed under the MIT License. |
0 commit comments