frootjs
v1.0.9
Published
High-performance, ultra-flexible, TypeScript-native web framework
Maintainers
Readme
Froot Framework
High-performance, flexible, TypeScript-native web framework engineered for peak V8 performance, multi-runtime portability, and clean developer ergonomics.
Why Froot?
| Feature | Express.js | Fastify | Froot |
| :--- | :--- | :--- | :--- |
| Language | JavaScript (external @types) | JavaScript / TypeScript | 100% Native TypeScript |
| Route Param Type Safety | No (manual casting) | Partial (verbose generics) | Automatic compile-time deduction |
| V8 Hidden Classes | Broken via setPrototypeOf | Shaped constructor | Monomorphic context + lazy getters |
| Router Architecture | Linear O(N) scan | Radix Tree | Smart Tri-Tier (Static O(1) + RegExp + Radix) |
| Static Route Lookup | Slow regex array | Radix tree traversal | 40,000,000+ ops/sec (O(1) Hash Map) |
| Runtimes | Node.js only | Primarily Node.js | Dual-Engine: WinterCG + Native Node.js |
| Middleware | Callback style (req, res, next) | 11 lifecycle hooks | Async Onion Pipeline (await next()) |
| Type-Safe RPC Client | None | None | Built-in createFrootClient<App>() |
| Standards Compliance | Custom legacy streams | Custom legacy streams | RFC 9457 Problem Details + Web Standards |
Quickstart
1. Installation
pnpm add frootjs
# or
npm install frootjs2. Basic Server
import { Froot } from 'frootjs';
const app = new Froot();
// Static route (Tier 1: O(1) Map dispatch)
app.get('/health', (c) => c.json({ status: 'ok' }));
// Dynamic route (Tier 2: Single-pass compiled RegExp)
// c.param('userId') is strictly typed from the route path:
app.get('/users/:userId', (c) => {
const userId = c.param('userId'); // string
return c.json({ id: userId, name: 'Alice' });
});
// Run with Node.js engine:
app.listen(3000, () => {
console.log('Froot server listening on http://localhost:3000');
});
// Or export for WinterCG / Cloudflare Workers / Bun:
export default app;Subpath Imports
Froot provides clean, tree-shakeable subpath imports:
// Core Application
import { Froot } from 'frootjs';
// WebCrypto Auth & JWT
import { jwt, sign, verify } from 'frootjs/jwt';
import { basicAuth } from 'frootjs/basic-auth';
// Streaming & Server-Sent Events (RFC 8895)
import { stream, streamSSE, streamText, sleep } from 'frootjs/streaming';
// WebSockets
import { upgradeWebSocket, createHub } from 'frootjs/ws';
// OpenAPI 3.1 & Scalar Docs
import { buildOpenAPISpec, scalarUIPage } from 'frootjs/openapi';
// Native JSX Engine & SSR
import { jsx, Fragment, renderToHtml, jsxRenderer } from 'frootjs/jsx';
import { html, raw, escapeHtml } from 'frootjs/html';
// Middleware
import { cors } from 'frootjs/cors';
import { logger } from 'frootjs/logger';
import { timing } from 'frootjs/timing';
import { security } from 'frootjs/security';
import { bearerAuth } from 'frootjs/bearer-auth';
// Client RPC
import { createFrootClient } from 'frootjs/client';Core Features
1. Smart Tri-Tier Routing Engine
Froot routes requests through three distinct optimization tiers:
- Tier 1 (Exact Static Map): Routes without dynamic parameters are dispatched via direct JavaScript
Maplookup at 40M+ ops/sec. - Tier 2 (Compiled Single-Pass RegExpRouter): Parameterized routes (
/users/:userId/posts/:postId) are compiled ahead of time into a single unified regular expression. Route matching and parameter extraction happen in a single step. - Tier 3 (Radix Trie): Catch-all wildcards (
*,/assets/*path) route through an optimized prefix tree.
2. Monomorphic Context with Lazy Evaluation
Unlike Express which mutates Object.setPrototypeOf(req) and ruins V8 hidden classes:
FrootContextpreserves fixed object shapes.- Query parameters, cookies, and request bodies are parsed lazily on first access. Zero CPU overhead is spent parsing query strings or bodies for routes that do not need them.
3. Asynchronous Onion Pipeline
Pure async/await middleware execution model:
app.use(async (c, next) => {
const start = performance.now();
await next();
const ms = (performance.now() - start).toFixed(2);
c.header('Server-Timing', `total;dur=${ms}`);
});4. Zero-Codegen End-to-End Typed RPC Client
Share types between backend and frontend without code-generation:
// backend.ts
const app = new Froot()
.get('/api/users/:id', (c) => c.json({ id: c.param('id'), name: 'Alice' }));
export type AppType = typeof app;
// frontend.ts
import { createFrootClient } from 'frootjs/client';
import type { AppType } from './backend';
const client = createFrootClient<AppType>({ baseUrl: 'http://localhost:3000' });
// Fully type-checked route, params, and response:
const res = await client.api.users[':id'].get({
param: { id: '42' }
});
const user = await res.json(); // Inferred as { id: string; name: string }5. Multi-Runtime Support (Write Once, Run Anywhere)
Froot is built on the standard Web Fetch API (Request and Response), allowing your application to run seamlessly across all modern JavaScript runtimes:
Node.js: Low-latency native engine with socket tuning (
setNoDelay(true),keepAliveTimeout):import { Froot } from 'frootjs'; const app = new Froot(); app.listen(3000);Cloudflare Workers: First-class support with typed environment bindings and
c.waitUntil():interface Env { Bindings: { MY_KV: KVNamespace; API_SECRET: string }; } const app = new Froot<Env>(); app.get('/data', async (c) => { c.waitUntil(logAnalytics(c.req.url)); return c.json({ key: await c.env.MY_KV.get('key') }); }); export default app;Bun: Ultra-fast native execution:
export default app;Deno: Native Web Standards server:
Deno.serve(app.fetch);AWS Lambda: Serverless adapter for API Gateway v2 and Function URLs:
import { handle } from 'frootjs/adapters/aws-lambda'; export const handler = handle(app);Runtime Detection Utility:
import { getRuntime } from 'frootjs/runtime'; console.log(getRuntime()); // 'node' | 'bun' | 'deno' | 'workerd' | 'fastly' | 'edge-light'
Running Benchmarks
pnpm benchRunning Examples
pnpm example:basic
pnpm example:streaming
pnpm example:rpcLicense
MIT (c) OrbitNorth LLC
