barejs
v0.1.43
Published
High-performance JIT-specialized web framework for Bun
Maintainers
Readme
📊 Benchmarks: Real-World Performance
BareJS leads in complex, real-world scenarios. We measure engine efficiency using a stress test involving 10+ middlewares and deep radix tree routing to ensure performance holds under high concurrency, not just in isolated "Hello World" loops.
| Framework | Latency | Speed | | :--- | :--- | :--- | | BareJS | 1.15 µs | Baseline | | Elysia | 1.60 µs | 1.39x slower | | Hono | 8.81 µs | 7.63x slower |
Last Updated: 2026-01-09 (BareJS Ultra-Accuracy Suite)
[!TIP] View our Continuous Benchmark Dashboard for historical data and detailed performance trends across different hardware.
🚀 Key Features
- JIT Pipeline Compilation: Routes and middleware chains are compiled into a single, flattened JavaScript function at runtime to eliminate recursive call overhead.
- Object Pooling: Recycles
Contextobjects via a circular buffer, significantly reducing Garbage Collection (GC) pressure. - Lazy Body Parsing: Requests are processed instantly. Payloads are only parsed on-demand via
ctx.jsonBody(), maintaining peak speed for GET requests. - Mechanical Sympathy: Intentionally designed to align with V8's optimization heuristics and Bun's internal I/O architecture.
🛠️ Installation
bun add barejs
The "Bare" Minimum
import { BareJS, type Context } from 'barejs';
const app = new BareJS();
app.get('/', (ctx: Context) => ctx.json({ hello: "world" }));
app.listen(3000);
📘 Comprehensive Guide
1. 🔀 Advanced Routing
Modularize your application and maintain clean codebases using BareRouter.
import { BareJS, BareRouter, type Context } from 'barejs';
const app = new BareJS();
const api = new BareRouter("/api/v1");
api.get("/status", (ctx: Context) => ({ status: "ok" }));
app.use(api); // Accessible at /api/v1/status
2. 🛡️ Security & Authentication
Built-in utilities for secure password hashing (Argon2/Bcrypt via Bun) and RFC-compliant JWT handling.
import { bareAuth, createToken, Password, type Context } from 'barejs';
const SECRET = "your-ultra-secure-secret";
app.post('/login', async (ctx: Context) => {
const body = await ctx.jsonBody();
const hash = await Password.hash(body.password);
const isValid = await Password.verify(body.password, hash);
if (isValid) {
const token = await createToken({ id: 1 }, SECRET);
return { token };
}
});
// Protect routes with bareAuth middleware
app.get('/me', bareAuth(SECRET), (ctx: Context) => {
const user = ctx.get('user'); // Identity injected by bareAuth
return { user };
});
3. ✅ Data Validation (3 Styles)
BareJS integrates deeply with TypeBox for JIT-level speeds but remains compatible with the broader ecosystem.
import { typebox, zod, native, t, type Context } from 'barejs';
import { z } from 'zod';
// Style A: TypeBox (Highest Performance - Recommended)
const TypeBoxSchema = t.Object({ name: t.String() });
app.post('/typebox', typebox(TypeBoxSchema), async (ctx: Context) => {
const body = await ctx.jsonBody();
return body;
});
// Style B: Zod (Industry Standard)
const ZodSchema = z.object({ age: z.number() });
app.post('/zod', zod(ZodSchema), async (ctx: Context) => {
const body = await ctx.jsonBody();
return body;
});
// Style C: Native (Zero Dependency / JSON Schema)
const NativeSchema = {
type: "object",
properties: { id: { type: 'number' } },
required: ["id"]
};
app.post('/native', native(NativeSchema), async (ctx: Context) => {
const body = await ctx.jsonBody();
return body;
});
4. 🔌 Essential Plugins
Standard utilities optimized for the BareJS engine's execution model.
Logger
High-precision terminal logging with color-coded status codes and microsecond timing.
import { logger } from 'barejs';
app.use(logger);
CORS
Highly optimized Cross-Origin Resource Sharing middleware.
import { cors } from 'barejs';
app.use(cors({ origin: "*", methods: ["GET", "POST"] }));
Static Files
Serves static assets with zero-overhead using Bun's native file system implementation.
import { staticFile } from 'barejs';
app.use(staticFile("public"));
🧠 Context API
The Context object is pre-allocated in a circular pool to eliminate memory fragmentation.
| Method / Property | Description |
| --- | --- |
| ctx.req | Raw incoming Bun Request object. |
| ctx.params | Object containing route parameters (e.g., :id). |
| ctx.jsonBody() | [Async] Parses the JSON body on-demand and caches it for the lifecycle. |
| ctx.status(code) | Sets the HTTP status code (Chainable). |
| ctx.json(data) | Finalizes and returns an optimized JSON response. |
| ctx.set(k, v) | Stores metadata in the request-scoped store. |
| ctx.get(k) | Retrieves stored data from the lifecycle store. |
⚙️ Performance Tuning
| OS Variable | Default | Description |
| --- | --- | --- |
| BARE_POOL_SIZE | 1024 | Pre-allocated context pool size. Must be a Power of 2. |
| NODE_ENV | development | Use production to hide stack traces and enable V8's hot-path optimizations. |
**Maintained by xarhang | License: MIT
