The JIT-Specialized Web Framework for Modern TypeScript
O(1) compiled routing, bounded context pooling, Standard Schema v1 / TypeBox / Zod validation,
bareTreaty RPC + typed SSE, 1-line MCP server, live DevTools, OpenTelemetry OTLP,
durable workflows, OpenAPI 3.1, native TLS, and a complete zero-trust security suite.
Quick Start & Patterns
Zero-boilerplate APIs with full TypeScript inference and native multi-core scaling.
import { BareJS, file } from 'barejs';
const app = new BareJS()
.get('/ping', () => 'pong')
.get('/users/:id', (ctx) => ({ id: ctx.params.id, q: ctx.query }))
.get('/logo', () => file('public/logo.png'))
.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; });
// Native Bun.serve({ routes }) fast-path or auto-detected uWebSockets.js on Node.js
app.listen(3000);
import { BareJS, Type } from 'barejs';
import { mcp } from 'barejs/mcp'; // 11 KB — Auto MCP 2025-03-26 Server
import { devtools } from 'barejs/devtools'; // 8.4 KB — Live UI at /__bare (auto-disabled in prod)
import { aiStream } from 'barejs/ai'; // 2.5 KB — Typed LLM SSE + AbortSignal
const app = new BareJS()
.use(devtools({ path: '/__bare' }))
.post('/orders', {
body: Type.Object({ item: Type.String(), qty: Type.Integer({ minimum: 1 }) }),
detail: { summary: 'Create a new order' }
}, (ctx) => {
ctx.defer(() => console.log('Request cleanup ran'));
return { created: ctx.body };
})
.get('/ai/chat', () => aiStream(async (emit) => {
emit.text('Hello from BareJS AI!');
emit.done();
}))
.use(mcp({ path: '/mcp', name: 'orders-mcp' })); // Exposes routes to Claude & Cursor!
import { BareJS, rateLimit, idempotency } from 'barejs';
import { otel } from 'barejs/otel'; // 3.5 KB — OTLP/HTTP Traces (Grafana/Datadog/Honeycomb)
import { cache } from 'barejs/cache'; // 2.2 KB — HTTP Cache Middleware
import { upstashStore, toRateLimitStore, toCacheStore, toIdempotencyStore } from 'barejs/store';
import { defineWorkflow } from 'barejs/workflow'; // 5.0 KB — Durable Crash-Resumable Workflows
const store = upstashStore({ url: process.env.UPSTASH_URL!, token: process.env.UPSTASH_TOKEN! });
const orderFlow = defineWorkflow('order-flow', async (input: { id: string }, step) => {
const receipt = await step.run('charge', () => ({ paid: true, id: input.id }));
await step.sleep('cooldown', 5000);
const approval = await step.waitForEvent<{ by: string }>('approve', 'order.approved');
return { receipt, approval };
}, { store });
const app = new BareJS()
.use(otel({ url: 'https://otlp.example.com/v1/traces', serviceName: 'orders-api' }))
.use(rateLimit({ max: 100, windowMs: 60_000, store: toRateLimitStore(store) }))
.get('/catalog', cache({ cache: toCacheStore(store, 60_000), cacheControl: 'public, max-age=60' }), () => ({ items: [] }))
.post('/orders/:id', idempotency({ store: toIdempotencyStore(store) }), (ctx) => orderFlow.start({ id: ctx.params.id }));
import { BareJS, Type, bareTreaty, bareTransformer } from 'barejs';
const app = new BareJS()
.post('/orders/:id', {
detail: { summary: 'Create Order', tags: ['Orders'] },
params: Type.Object({ id: Type.Integer() }),
body: Type.Object({ item: Type.String(), qty: Type.Integer({ minimum: 1 }) }),
response: Type.Object({ id: Type.Number(), item: Type.String(), qty: Type.Number() })
}, (ctx) => ({
id: ctx.params.id, item: ctx.body.item, qty: ctx.body.qty,
internalCost: 999 // automatically stripped by response schema
}))
.get('/events', (ctx) => ctx.sse<{ step: number; at: Date }>((async function* () {
yield { data: bareTransformer.serialize({ step: 1, at: new Date() }) };
})()))
.docs({ title: 'Orders API', version: '1.0.0' }); // OpenAPI 3.1 + Scalar UI
// Compile-time typed RPC with Date/Map/Set/BigInt transformer & typed SSE AsyncIterable<T>
const api = bareTreaty<typeof app>(app, { transformer: bareTransformer });
const res = await api.events.get();
if (res.ok) for await (const chunk of res.data) console.log(chunk.step, chunk.at);
import {
BareJS, securityHeaders, cors, csrf, rateLimit,
idempotency, bareAuth, staticFile, healthcheck
} from 'barejs';
const app = new BareJS()
.trustProxy(['10.0.0.0/8', '127.0.0.1'])
.useLog({ format: 'json' })
.onRequest((ctx) => ctx.set('t0', performance.now()))
.onResponse((ctx, res) => console.log(ctx.requestId, res.status))
.use(securityHeaders())
.use(cors({ origin: ['https://app.example.com'], credentials: true }))
.use(csrf({ allowedOrigins: ['https://app.example.com'] }))
.use(rateLimit({ windowMs: 60_000, max: 100 }))
.use(healthcheck({ path: '/health', readyPath: '/ready' }))
.use(staticFile('public', { spa: true }));
app.post('/pay', bareAuth({ secret: process.env.JWT_SECRET! }), idempotency(), (ctx) => ({
ok: true, user: ctx.user
}));
import { BareJS } from 'barejs';
const app = new BareJS();
// Native WebSocket pub/sub on both Bun and Node.js (uWebSockets.js)
app.ws('/ws/chat', {
open(ws) { ws.subscribe('lobby'); },
message(ws, msg) { ws.publish('lobby', msg); }
});
// Multi-core clustering with native TLS (Bun, uWS.SSLApp, or Node https)
app.listenCluster(8443, undefined, '0.0.0.0', {
engine: 'auto',
tls: { keyFileName: '/certs/server.key', certFileName: '/certs/server.crt' }
});
import { BareJS, cors, securityHeaders } from 'barejs/edge';
import { cache } from 'barejs/cache'; // 2.2 KB — Cache-Control + Edge Cache API
import { etag } from 'barejs/etag'; // 1.8 KB — Weak/Strong ETag + 304
import { html } from 'barejs/html'; // 649 B — XSS-safe HTML templates
import { awsLambda } from 'barejs/aws-lambda'; // 3.0 KB — API Gateway v1/v2 & ALB
const app = new BareJS<{ API_KEY: string }>()
.use(securityHeaders(), cors({ origin: '*' }))
.get('/hello', (ctx) => html`<h1>Hi ${ctx.query.name ?? 'Edge'}</h1>`.toResponse())
.get('/feed', cache({ cacheControl: 'public, max-age=60' }), etag(), () => ({ ok: true }));
export default app; // Cloudflare Workers / Vercel Edge / Deno Deploy
export const handler = awsLambda(app); // AWS Lambda
Built for Production
Everything you need for high-throughput APIs without gluing together 15 packages.
JIT Radix Router & Context Pool
Compiles static, parameterized, optional (:type?), and regex (:id{[0-9]+}) routes with bounded Context pooling and Bun native static routes.
uWebSockets.js, Edge & Modular Subpaths
Optional Node.js uWebSockets.js acceleration plus zero-dependency subpaths: barejs/edge, barejs/mcp, barejs/devtools, barejs/otel, barejs/store, barejs/workflow, barejs/queue, barejs/webhooks, barejs/metrics, barejs/ai, barejs/html, barejs/jsx, barejs/ssg & serverless adapters.
Zero-Trust Security Suite
HS256/RS256/ES256 JWKS auth, Argon2id/scrypt hashing, CIDR trustProxy, CRLF header/cookie guards, HMAC-SHA256 webhooks, CSRF, CORS, and rate limiting.
Resilience, DX & Observability
ctx.defer() + Symbol.asyncDispose, ctx.signal, RFC 9457 ctx.problem(), live DevTools (/__bare), OTLP traces, Prometheus /metrics, durable workflows, and job queues.
Standard Schema, OpenAPI, Treaty & MCP
Fail-closed Standard Schema v1 (Valibot, ArkType, Zod 4), TypeBox & JSON Schema validation, Scalar UI docs, typed SSE + bareTransformer RPC, and 1-line MCP AI tool server.
Real-Time, AI Streaming & Static Files
Native WebSockets, SSE & typed LLM streaming (barejs/ai), multipart streaming uploads, zstd/br/gzip compression, and SPA-ready static file serving.
AI Coding Agent Skill & LLM Docs
Install the official BareJS Agent Skill in Claude Code, Cursor, Codex, OpenCode, or Windsurf so your AI writes idiomatic, bug-free BareJS code on the first try.