# BareJS (`barejs`) — AI Quick Reference (`llms.txt`) > BareJS is a batteries-included, JIT-compiled TypeScript web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `33 KB`, zero `node:*` / zero external imports), **AWS Lambda**, **Cloudflare Pages**, **Netlify**, and **Meta Frameworks** (Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start via `new BareJS({ prefix: '/api' })` + `export const GET = app.fetch`) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)**, official AI Agent Skill (`bunx skills add xarhang/bareJS`), and **511 tests across 38 files verified in CI (Bun, Node.js 20/22, Deno 2)**. ## 0. Complete Export & Subpath Index (Check Here First!) - `barejs` (core): `BareJS`, `BareRouter`, `Context`, `Type`/`T`/`TypeBox`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `isTokenRevoked`, `Hash`/`Password`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck`, `generateOpenAPISpec`, `renderDocsHTML` (router supports `:param`, optional `:param?`, regex `:id{[0-9]+}`, and `*` wildcards) - `barejs/node`: Node.js `>= 20` build (same exports + native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` / `ws` / `@node-rs/argon2`) - `barejs/edge` (`33 KB`): Zero-`node:*`, zero-external-dep Edge build (Cloudflare Workers, Vercel Edge, Deno Deploy) - `barejs/html` (`1.3 KB`): `html`, `raw`, `escapeHtml`, `type HtmlString` - `barejs/etag` (`2.4 KB`): `etag`, `type EtagOptions` - `barejs/cache` (`2.2 KB`): `cache`, `type CacheOptions` - `barejs/jsx` / `barejs/jsx-runtime` (`4.5 KB`): `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse` - `barejs/ssg` (`2.1 KB`): `toSSG`, `type ToSSGOptions`, `type ToSSGResult` - `barejs/aws-lambda` (`3.0 KB`): `awsLambda`, `handle`, `type AwsLambdaEvent`, `type AwsLambdaResult` - `barejs/cloudflare-pages` (`768 B`): `handle`, `cloudflarePages` (`export const onRequest = handle(app)`) - `barejs/netlify` (`752 B`): `handle`, `netlify` (`export default handle(app)`) ## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge) ```bash bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebSockets.js, Deno) bun create barejs my-app --bun # --bun | --node | --node-uws | --deno ``` ```ts import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy // Optional { poolSize, prefix } (or numeric poolSize 0..65536, default 1024): lazy bounded LIFO Context pool + optional base path prefix (e.g. `new BareJS({ prefix: '/api' })` or `app.basePath('/api')`) const app = new BareJS(); // Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams) app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name })); app.get('/ping', () => 'pong'); app.get('/logo', () => file('public/logo.png')); // Or file(ctx.params.name, { root: './uploads', download: true }) app.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; }); // Pull-based ReadableStream backpressure // Wildcard catch-all route (`ctx.params['*']`) app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] })); // Native TLS works across Bun, uWebSockets.js (SSLApp), and Node https: app.listen(3000); // or app.listen(8443, '0.0.0.0', false, { tls: { keyFileName, certFileName } }) ``` ## 2. Routing, Plugins & Unified Schema Validation Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.all`, `app.basePath(prefix)`, `app.group(prefix, fn)`, `app.route(prefix, router)`, `app.use(mwOrRouterOrPlugin)`. Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`): ```ts app.post('/users/:id', { detail: { summary: 'Update user', description: 'Updates user profile', tags: ['Users'] }, params: Type.Object({ id: Type.Integer() }), query: Type.Object({ active: Type.Optional(Type.Boolean()) }), headers: Type.Object({ 'x-client': Type.Optional(Type.String()) }), body: Type.Object({ name: Type.String({ minLength: 1 }) }), response: Type.Object({ id: Type.Number(), name: Type.String() }), // Recursive JIT projector auto-strips undeclared fields (e.g. password_hash)! maxBodySize: 1024 * 1024 // default 1MB (returns 413 on overflow) }, (ctx: Context) => ({ id: ctx.params.id, // auto-coerced to number active: ctx.query.active, // auto-coerced to boolean name: ctx.body.name, password_hash: 'secret' // automatically stripped before sending to client! })); ``` Supports **Standard Schema v1** (`~standard` — Valibot, ArkType, Zod 4, Effect; sync & async fail-closed), **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`). ### Modular Routers & Plugins ```ts // Sub-router const api = new BareRouter(); api.get('/items', () => []); // Modular sub-routers preserve full bareClient() type inference across prefixes: const api = new BareRouter().get('/items', () => []); const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api) ``` ## 3. Context (`ctx`) & Testing (`app.request`) - `await app.request('/items', { method: 'POST', body: JSON.stringify({ name: 'a' }) })`: Ergonomic in-memory helper (normalizes relative paths to `http://localhost` and delegates to `app.fetch`). - `ctx.req`: Raw incoming Bun `Request`. - `ctx.params`: Route params (`Record`, including `ctx.params['*']` for wildcards). - `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support. - `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit. - `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type). - `ctx.uploadStream({ maxFileSize, maxFiles, maxFieldSize, allowedTypes })`: True streaming `multipart/form-data` async generator yielding `{ type: 'field', fieldName, value }` and `{ type: 'file', fieldName, filename, safeName, contentType, stream }` (`ReadableStream`, $O(\text{chunk})$ memory). - `ctx.cookies`: Lazy parsed request cookies (`Record`). - `await ctx.setCookie(name, value, { secret?, httpOnly?, sameSite?, secure?, maxAge?, expires?, domain?, path? })`: Defaults to `HttpOnly; SameSite=Lax; Path=/`. Pass `secret` for HMAC-SHA256 signing. - `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing. - `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`). - `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`. - `ctx.ip`: Client IP from `x-forwarded-for` (first non-empty), `x-real-ip`, `cf-connecting-ip` (only when `trustProxy` is enabled), else peer IP or `'127.0.0.1'`. - `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`. - `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map` (automatically cleared on pool release). - **Response Helpers (Hono / Express style):** - `ctx.status(code)` (chainable) - `ctx.setHeader(name, val)` (chainable, copy-on-write safe) - `ctx.json(data)` -> `application/json` - `ctx.send(message, extra?)` -> `{ status: 'success' | 'error', msg: message, ...extra }` - `ctx.html(html, status?)` -> `text/html; charset=utf-8` - `ctx.text(text, status?)` -> `text/plain; charset=utf-8` - `ctx.redirect(url, status = 302)` -> `Location: url` - `ctx.problem(status, detailOrOpts?)` -> RFC 9457 `application/problem+json` (auto `title` & `instance`, supports extension fields) - `ctx.defer(fn)` -> Registers LIFO request-scoped cleanup callback (runs after handler finishes, even on error; 0 overhead when unused) - `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` -> `text/event-stream` ## 4. Context Enrichment (`app.derive`) & Plugin Deduplication ```ts const derivedApp = app.derive((ctx) => ({ requestTime: Date.now(), tenant: ctx.req.headers.get('x-tenant') || 'public' })); ``` Derived properties are attached directly onto `ctx` with TypeScript inference (`Bare`), automatically dispose values implementing `Symbol.asyncDispose` / `Symbol.dispose` after the handler finishes, and clean up when `Context` returns to the pool. Named plugins (`{ name, seed?, install }`) and sub-apps (`new BareJS({ name, seed })`) are automatically deduplicated when mounted via `.use()` or `.route()`. ## 5. Built-in Security Middlewares, Pluggable Redis Store, Compression & Static Cache ```ts import { cors, csrf, timeout, rateLimit, securityHeaders, idempotency, createSingleflight, redisStore, compress, bareAuth, createToken, basicAuth, hasRole, revokeToken, Hash, staticFile } from 'barejs'; // Optional shared Redis store (compatible with Bun.redis and ioredis) const store = redisStore(Bun.redis, { prefix: 'myapp:' }); app.use(securityHeaders()); app.use(cors({ origin: ['https://app.example.com'], credentials: true })); app.use(csrf({ allowedOrigins: ['https://app.example.com'], requireToken: true })); app.use(timeout(10_000, { status: 408, message: 'Timed out' })); app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip app.use(rateLimit({ windowMs: 60_000, max: 100, store })); // Omit store for zero-overhead in-memory Map app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } })); // Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true) app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store, keyScope: (ctx) => ctx.user?.id }), (ctx) => ({ paid: true })); // Thundering-herd / Cache-stampede request coalescer const sf = createSingleflight(); app.get('/report', () => sf('report-key', async () => ({ total: 100 }))); // Auth & Hashing (HS256 sync fast-path + RS256/ES256/JWKS async verification + revocationStore) const hash = await Hash.make('password'); // Argon2id (64MB default) const ok = await Hash.verify('password', hash); const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET!); app.get('/admin', bareAuth({ secret: process.env.JWT_SECRET!, revocationStore: store }), hasRole('admin'), (ctx) => ctx.user); app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user); ``` ## 6. Real-Time, RPC, OpenAPI & Client - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })` (Native on Bun, built-in RFC 6455 or optional `ws` on Node.js, `Deno.upgradeWebSocket` on Deno) - **SSE**: `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` (works across Bun, Node.js, Deno) - **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes) - **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`) - **Type-Safe Client & Chained RPC (`bareClient` / `bareTreaty`, URL or Zero-Network In-Memory `app`)**: - Network: `const api = bareClient('http://localhost:3000');` - In-Memory (SSR / Unit Tests): `const api = bareClient(app); await api.get('/users/:id', { params: { id: 1 } });` - Non-Throwing Result Union: `const res = await api.safe.get('/users/:id', { params: { id: 1 } }); // { ok: true, data } | { ok: false, error, status }` - Chained Proxy RPC & Typed WebSockets: `const treaty = bareTreaty(app); await treaty.users({ id: 1 }).get(); const ws = treaty.ws.chat.subscribe();` ## 7. Lifecycle & Error Handling ```ts app.onStart(() => console.log('Server started')); app.onDrain(async () => console.log('Draining...')); // Also triggered by IPC DRAIN_REQUEST app.onStop(async () => await db.close()); app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId })); app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' })); await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners ``` > **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`). ## 8. Optional Subpaths, Macros & Observability - **MCP Server (`barejs/mcp`)**: `app.use(mcp({ path: '/mcp', name: 'my-mcp' }))` — auto-exposes BareJS routes & schemas as MCP (2025-03-26 Streamable HTTP) tools and executes `tools/call` in-memory via `app.fetch()` with auth header forwarding. - **Live Visual DevTools (`barejs/devtools`)**: `app.use(devtools({ path: '/__bare' }))` — live dark-mode dashboard, SSE request waterfall, per-route p50/p95/p99 latency, redacted headers, and SSRF-safe replay (auto-disabled in `NODE_ENV=production`). - **Background Job Queue (`barejs/queue`)**: `const q = createQueue({ concurrency: 4, retries: 3 }); q.process('email', fn); q.enqueue('email', payload, { delayMs });` — exponential backoff, Dead-Letter Queue, and graceful `q.stop()`. - **Signed Webhooks (`barejs/webhooks`)**: `app.post('/webhooks', verifyWebhook({ secret, toleranceSec: 300 }), handler)` + `sendWebhook(url, payload, { secret, retries: 3 })` — Web Crypto HMAC-SHA256, replay window, secret rotation. - **Prometheus Metrics (`barejs/metrics`)**: `app.use(metrics('/metrics'))` — exports `http_requests_total`, `http_request_duration_seconds`, `http_requests_in_flight`, and custom counters/gauges with ID/UUID path normalization. - **AI / LLM Streaming (`barejs/ai`)**: `aiStream(async (emit) => { emit.text('Hi'); emit.done(); })` + `parseOpenAISSE(stream)` — structured SSE events with automatic `AbortSignal` cancellation on client disconnect. - **Client Disconnect & Streaming RPC**: `ctx.signal` / `ctx.onAbort(cb)` on `Context` & `EdgeContext`; `bareTreaty(app, { transformer: bareTransformer })` preserves `Date`/`Map`/`Set`/`BigInt`/`RegExp`/`URL` and decodes `text/event-stream` responses as `AsyncIterable` with `options.signal`. - **OpenTelemetry OTLP (`barejs/otel`)**: `app.use(otel({ url, serviceName, headers }))` — zero-dep OTLP/HTTP JSON (`v1/traces`) batch exporter. - **Unified Store (`barejs/store`)**: `memoryStore()`, `sqliteStore(db)`, `upstashStore({ url, token })`, `kvStore(env.KV)` + bridges `toRateLimitStore()`, `toCacheStore()`, `toIdempotencyStore()` for distributed `rateLimit()`, `cache()`, `idempotency()`, and workflows. - **Durable Workflows (`barejs/workflow`)**: `defineWorkflow(name, async (input, step) => { await step.run(...); await step.sleep(...); await step.waitForEvent(...); }, { store })` — crash-resumable idempotent step replay. - **HTML Templates (`barejs/html`, `649 B`)**: `html\`

Hello ${name}

${raw('✓')}\`.toResponse()` — auto-escapes XSS, supports nested `html`, arrays, and falsy values. - **Dynamic ETag (`barejs/etag`, `1.8 KB`)**: `app.use(etag())` (weak `Bun.hash`/FNV-1a default) or `etag({ weak: false })` (strong SHA-256) with `304 Not Modified`. - **AWS Lambda (`barejs/aws-lambda`, `2.4 KB`)**: `export const handler = awsLambda(app)` (alias `handle`) — supports API Gateway v1, v2, ALB, `Set-Cookie`, and binary base64. - **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro({ auth: { beforeHandle, resolve } }); app.use(plugin).get('/me', { auth: 'admin' }, handler);` - **Cookie & Per-Status Response Schemas**: `RouteSchemas` supports `cookies` validation and `response: { 200: OkSchema, 404: ErrSchema }` (reflected in OpenAPI 3.1 & `bareTreaty`). - **Observability (`tracing`, `serverTiming`)**: `app.use(tracing({ serverTiming: 'app', onSpan }))` — zero-dep W3C `traceparent` + `Server-Timing` header.