fetchwork
v1.0.20
Published
An ultra-fast, lightweight, and type-safe web framework built on W3C Web Standards with multi-runtime adapter support.
Maintainers
Readme
Features
- Pure W3C Web Standard Core: Built 100% on native
RequestandResponseweb interfaces with zero-copy I/O. - Fast Compiled Regex Engine: High-performance $O(1)$
Maplookups for static routes and single-pass compiled regex matching for dynamic routes. - Standard Schema Interoperability: First-class validation for
body,query,params, andheadersusing Zod, Valibot, or ArkType via Standard Schema (validateSchema). - Ultra-Low Latency SSE: Built-in
c.sse()streaming helper backed by nativeTransformStreamand zero proxy buffering headers. - Gradual Level-Based Rate Limiter: High-performance multi-level
FloodWaitrate limiter (app.rateLimit()) supporting static and wildcard path matching. - Built-in Ultra-Fast CORS: Zero-overhead CORS middleware supporting static origins and $O(1)$ Set-based whitelist matching.
- Custom Not Found & Error Handling: Flexible
app.notFound()andapp.onError()handlers with zero latency penalty on hot paths. - Multi-Runtime Ready: Seamlessly run under Bun, Node.js, Cloudflare Workers, or Vercel via standard
app.fetch.
⚡ Performance & Benchmarks
Benchmarking results measured using Autocannon (100 parallel connections, 10 pipelining factor, 10-second duration) running natively on Bun.
1. Complete Feature Suite Performance (bench-all)
Comparing performance across core framework features under heavy load:
| Feature / Scenario | Throughput (Avg RPS) | Latency Avg | Latency P50 | Latency P99 | Throughput (MB/s) | Total Requests (10s) |
| :----------------------------- | :------------------- | :----------- | :----------- | :------------ | :---------------- | :------------------- |
| Baseline Routing (/ping) | 14,901.6 RPS | 67.24 ms | 66.00 ms | 142.00 ms | 1.71 MB/s | 149k req |
| CORS Preflight (OPTIONS) | 15,100.8 RPS | 66.06 ms | 65.00 ms | 82.00 ms | 3.30 MB/s | 151k req |
| Validator Standard Schema | 11,076.0 RPS | 90.69 ms | 89.00 ms | 111.00 ms | 3.55 MB/s | 110k req |
| SSE Initial Handshake | 6,691.2 RPS | 14.47 ms | 13.00 ms | 27.00 ms | 1.60 MB/s | 66k req |
2. Multi-Level Rate Limiter Throughput
Throughput evaluation when rate limiting is applied across static and wildcard paths:
| Scenario | Throughput (Avg RPS) | Latency Avg | Latency P50 | Latency P99 | Throughput (MB/s) | Total Requests (10s) | | :------------------------------ | :------------------- | :----------- | :----------- | :------------ | :---------------- | :------------------- | | No Rate Limit (Baseline) | 15,409.6 RPS | 64.76 ms | 64.00 ms | 82.00 ms | 1.76 MB/s | 154k req | | Static Rate Limit $O(1)$ | 12,703.2 RPS | 79.15 ms | 77.00 ms | 96.00 ms | 3.44 MB/s | 127k req | | Wildcard Rate Limit (Regex) | 12,674.4 RPS | 79.26 ms | 76.00 ms | 150.00 ms | 3.31 MB/s | 126k req |
Result: Static and Wildcard rate limiting maintain high throughput (12,700+ RPS) while reliably managing penalty windows with less than 0.2% variance between static and regex matching.
Installation
bun add fetchwork
Quick Start
import { FetchWork } from "fetchwork";
const app = new FetchWork();
// Global Logger Middleware
app.use(async (c, next) => {
console.log(`[${c.req.method}] ${c.path}`);
return next();
});
// Basic Route
app.get("/", (c) => c.text("Welcome to FetchWork!"));
// Unified Context JSON Response
app.get("/json", (c) => c.json({ status: "success", message: "Hello World" }));
// Dynamic Route
app.get("/:tenant/users/:userId", (c) => {
const { tenant, userId } = c.params;
return c.json({ tenant, userId });
});
// Custom 404 Not Found Handler
app.notFound((c) => {
return c.json({ status: 404, error: "Custom Route Not Found" }, 404);
});
export default {
port: 3000,
fetch: app.fetch,
};Usage Guide
1. CORS Middleware
Apply CORS globally or per route using the built-in cors middleware:
import { FetchWork } from "fetchwork";
import { cors } from "fetchwork/cors";
const app = new FetchWork();
app.use(
cors({
origin: ["example.com", "tinylink.id"],
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
maxAge: 86400,
}),
);2. Multi-Level Rate Limiter
Protect specific static or wildcard paths with level-based penalty windows (FloodWait):
import { FetchWork } from "fetchwork";
import { rateLimit } from "fetchwork/rate-limiter";
const app = new FetchWork();
// Rate limit specific static route
app.rateLimit(
"/api/v1/auth/login",
rateLimit({
keyPrefix: "auth-login",
limit: [5, 2], // Level 0: 5 reqs, Level 1+: 2 reqs
windowMs: { minutes: 1 },
floodwaitMs: [{ seconds: 30 }, { minutes: 5 }], // Penalties increase per violation level
}),
);
// Rate limit wildcard paths
app.rateLimit(
"/api/v1/data/*",
rateLimit({
keyPrefix: "api-data",
limit: 100,
windowMs: { minutes: 1 },
floodwaitMs: { minutes: 1 },
}),
);3. Input Validation (Standard Schema)
Validate incoming payloads with Zod, Valibot, or ArkType using validateSchema:
import { z } from "zod";
import { validateSchema } from "fetchwork/validator";
const RegisterSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
password: z.string().min(6),
});
app.post(
"/api/v1/register",
validateSchema("body", RegisterSchema),
async (c) => {
const payload = c.validData?.body;
return c.json({ success: true, data: payload }, 201);
},
);4. Server-Sent Events (SSE)
Stream real-time updates seamlessly with non-blocking c.sse():
app.get("/api/v1/stream", (c) => {
c.timeout(0);
return c.sse(async (sse) => {
// Send initial handshake
await sse.send({
event: "connected",
data: { status: "online" },
});
// Push periodic updates
const interval = setInterval(async () => {
await sse.send({
event: "ping",
data: { time: Date.now() },
});
}, 1000);
// Clean up when client disconnects
c.req.signal.addEventListener("abort", () => {
clearInterval(interval);
});
});
});Running Across Runtimes
FetchWork core uses standard W3C interfaces, allowing it to run across any modern JS runtime:
Bun Adapter
import { FetchWork } from "fetchwork";
import { serveBun } from "fetchwork/adapters";
const app = new FetchWork();
app.get("/api", (c) => c.json({ runtime: "Bun" }));
serveBun(app, { port: 3000 });Cloudflare Workers
import { FetchWork } from "fetchwork";
import { serveCloudflare } from "fetchwork/adapters";
const app = new FetchWork();
app.get("/api", (c) => c.json({ runtime: "Cloudflare Workers" }));
export default serveCloudflare(app);FetchWork Progress Checklist
Core & Routing
- [x] High-Performance Router: Static $O(1)$ map lookups and single-pass compiled regex matching.
- [x] W3C Standard Context: Native
Contextabstraction built on standardRequestandResponse. - [x] Scoped Routing / Prefixing: Modular route prefixing via
app.route('/v1', ...). - [x] Flexible Error Handling: Exception management via
app.onError(). - [x] Custom Not Found Handler:
app.notFound()with zero latency penalty on hot paths.
Type Safety & DX
- [x] Standard Schema Interoperability: Validation support for
body,query,params, andheadersviavalidateSchema(). - [x] Route Parameter Inferencing: Automatic type inferencing for
c.params.
Streaming & Real-Time Utilities
- [x] Ultra-Low Latency SSE:
c.sse()helper powered byTransformStreamwith zero proxy buffering. - [ ] WebSockets Adapter: Light abstraction for bidirectional WebSocket connections.
Security & Production Ready
- [x] Built-in CORS Helper: Optimized CORS middleware supporting static and $O(1)$ set matching.
- [x] Multi-Level Rate Limiter: Path-based
FloodWaitrate limiter (app.rateLimit()). - [x] OpenAPI / Swagger Generator: Automatic OpenAPI doc generator reading route metadata and schemas.
- [x] Body Size Limits: Memory protection for large
reqBody()payloads.
License
MIT © Ayiin
