Package Exports
- create-nodejs-fn
- create-nodejs-fn/cli
- create-nodejs-fn/package.json
Readme
Create NodeJS Fn
โก A crazy Vite plugin that lets you transparently call Node.js native code from Cloudflare Workers
๐จ WARNING: This project uses INSANE black magic! DO NOT use in production!! ๐จ
๐คฏ What is this?
Cloudflare Workers are amazing, but they run on the V8 JavaScript engineโnot Node.js. This means native modules (binary addons compiled with node-gyp) simply don't work. Want to use @napi-rs/canvas for image generation, sharp for image processing, or pdfjs-dist with canvas rendering? You're out of luck...
...or are you? ๐ฅ
create-nodejs-fn bridges this gap by leveraging Cloudflare Containers (currently in beta). Here's how it works:
- You write functions in
*.container.tsfiles using any Node.js native modules you want - The Vite plugin analyzes your code using
ts-morph(TypeScript AST manipulation) - It auto-generates type-safe proxy functions that look identical to your original exports
- Your container code is bundled with esbuild and packaged into a Docker image
- At runtime, the proxy transparently routes calls via Cap'n Proto RPC to the container
- Cloudflare Durable Objects manage container lifecycle and connection state
The result? You import { myFunction } from "./native.container" and call it like any normal functionโbut it actually executes inside a Docker container running full Node.js with native module support!

๐ฎ Live Demo
Try it now! This example uses @napi-rs/canvas + pdfjs-dist to render PDF pages as images:
๐ Render Bitcoin Whitepaper (Page 1)
https://example-create-nodejs-fn.inaridiy.workers.dev/renderPdf?url=https://bitcoin.org/bitcoin.pdf&pageNum=1&scale=3Yes, this is running on Cloudflare Workers. Yes, it's using native Node.js modules. Yes, it's black magic.
๐ Quick Start
Prerequisites
You need a Cloudflare Workers + Vite project. Create one with:
# Using Hono (recommended)
pnpm create hono@latest my-app --template cloudflare-workers+vite
# Then cd into it
cd my-app1. Install dependencies
pnpm add create-nodejs-fn @cloudflare/containers capnweb@0.2.0 @napi-rs/canvas2. Initialize config
pnpm create-nodejs-fn initThis configures:
- Adds Containers & Durable Objects config to
wrangler.jsonc - Generates
.create-nodejs-fn/Dockerfile - Creates
src/__generated__/directory - Adds DO export to entry file
3. Configure Vite plugin
// vite.config.ts
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
import { createNodejsFnPlugin } from "create-nodejs-fn";
export default defineConfig({
plugins: [
createNodejsFnPlugin({
// Native dependencies to install in the container
external: ["@napi-rs/canvas"],
// Docker config with fonts for text rendering
docker: {
baseImage: "node:20-bookworm-slim",
systemPackages: [
"fontconfig",
"fonts-noto-core",
"fonts-noto-cjk",
"fonts-noto-color-emoji",
],
},
}),
cloudflare(),
],
});4. Write a container function
// src/clock.container.ts
import { createCanvas } from "@napi-rs/canvas";
import { nodejsFn } from "./__generated__/create-nodejs-fn.runtime";
export const renderClock = nodejsFn(async () => {
// ๐จ Create an image with current time using @napi-rs/canvas!
const canvas = createCanvas(600, 200);
const ctx = canvas.getContext("2d");
// Background
ctx.fillStyle = "#1a1a2e";
ctx.fillRect(0, 0, 600, 200);
// Text with Noto font (installed via systemPackages)
ctx.font = "bold 36px 'Noto Sans CJK JP', 'Noto Color Emoji', sans-serif";
ctx.fillStyle = "#eee";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const now = new Date().toISOString();
ctx.fillText(`๐ ${now}`, 300, 100);
// Return as PNG data URL
return await canvas.toDataURLAsync("image/webp");
});5. Call it from your Worker like any normal function
// src/index.ts
import { Hono } from "hono";
import { renderClock } from "./clock.container";
const app = new Hono();
app.get("/clock", async (c) => {
// ๐ฑ Looks like a normal function call!
// But behind the scenes, RPC flies to the container!
const pngDataUrl = await renderClock();
// Convert data URL to response
return fetch(pngDataUrl);
});
// Don't forget to export the DO
export { NodejsFnContainer } from "./__generated__/create-nodejs-fn.do";
export default { fetch: app.fetch };6. Launch!
pnpm devVisit http://localhost:5173/clock to see a dynamically generated image with the current timestamp! ๐
๐ช The Black Magic Revealed
1๏ธโฃ Transparent Proxy Generation via AST Transformation
Uses ts-morph to statically analyze *.container.ts files.
Detects exported functions and auto-generates proxy functions with identical type signatures.
// Your code (clock.container.ts)
export const renderClock = nodejsFn(async () => {
// Node.js native processing...
return pngDataUrl;
});
// ๐ง The plugin auto-generates a proxy
// โ Types fully preserved! IDE autocomplete works!
// โ Calls are routed to the container via RPC!2๏ธโฃ Container Management via Durable Objects
Uses Cloudflare Durable Objects to manage container connections. Stateful, with multi-instance routing support!
// Route to specific instances with containerKey
export const renderClock = nodejsFn(
async () => { /* ... */ },
containerKey(({ args }) => {
// Route to containers based on arguments! Load balancing!
return `instance-${Math.floor(Math.random() * 3)}`;
})
);3๏ธโฃ Fully Automated Build with esbuild + Docker
- Bundles container server code with esbuild
- Auto-generates Dockerfile
- Native deps specified in
externalare auto-extracted topackage.json
โ๏ธ Plugin Options
createNodejsFnPlugin({
// File patterns for container functions (default: ["src/**/*.container.ts"])
files: ["src/**/*.container.ts"],
// Output directory for generated files (default: "src/__generated__")
generatedDir: "src/__generated__",
// Durable Object binding name (default: "NODEJS_FN")
binding: "NODEJS_FN",
// Container class name (default: "NodejsFnContainer")
className: "NodejsFnContainer",
// Container port (default: 8080)
containerPort: 8080,
// External dependencies to install in container
external: ["@napi-rs/canvas", "sharp"],
// Docker image settings
docker: {
baseImage: "node:20-bookworm-slim",
systemPackages: [
"fontconfig",
"fonts-noto-core",
"fonts-noto-cjk",
"fonts-noto-color-emoji",
],
preInstallCommands: [],
postInstallCommands: [],
env: { MY_VAR: "value" },
},
// Environment variables to pass from Worker to Container
workerEnvVars: ["API_KEY", "SECRET"],
// Auto-rebuild on file changes (default: true)
autoRebuildContainers: true,
// Rebuild debounce time (default: 600ms)
rebuildDebounceMs: 600,
});๐๏ธ Internal Architecture
project/
โโโ src/
โ โโโ clock.container.ts # Your code
โ โโโ index.ts # Worker entry
โ โโโ __generated__/ # ๐ง Auto-generated magic
โ โโโ create-nodejs-fn.ts # RPC client & type definitions
โ โโโ create-nodejs-fn.do.ts # Durable Object class
โ โโโ create-nodejs-fn.context.ts # Container key resolution
โ โโโ create-nodejs-fn.runtime.ts # nodejsFn / containerKey helpers
โ โโโ proxy.src__clock.container.ts # Proxy functions
โ
โโโ .create-nodejs-fn/ # ๐ณ Container build artifacts
โโโ Dockerfile # Auto-generated
โโโ container.entry.ts # Server entry (generated)
โโโ server.mjs # Bundled with esbuild
โโโ package.json # Only external deps extractedโ ๏ธ Limitations & Caveats
- Not for production: This is an experimental project
- Requires Cloudflare Containers (currently in beta)
- Function arguments and return values must be serializable
- Container cold starts exist (adjust with
sleepAfter) - Debugging is hard (check your logs if something breaks)
๐ License
MIT