Junction Framework Overview
Junction is the official web framework for the Braid language — a production-hardened, middleware-driven HTTP server designed for APIs, SPAs, WebSockets, and microservices. It ships as a built-in library at lib.frameworks.junction and is scaffolded via the braidc junction new CLI command.
Architecture
Junction follows a linear middleware pipeline that feeds into a trie-based router. Every incoming request passes through four stages:
- Request construction — Raw connection data is parsed into a
Requeststruct (method, path, headers, body, cookies, query params, uploaded files, etc.) - Middleware pipeline — An ordered array of middleware functions run in sequence. Each middleware can short-circuit by returning a
Response(e.g., auth failure, rate limit), or returnnullto pass control to the next middleware. - Route dispatch — The trie-based router matches
method + pathagainst registered handlers. Path parameters and wildcard segments are extracted intoreq.params. - Response finalization — Security headers are applied (CSP, HSTS, X-Frame-Options, etc.), compression is negotiated (gzip/brotli/deflate), and structured logging is emitted.
Core Structs
The JunctionApp struct holds the entire application state: config, routes, middlewares, error handlers, storage, sessions, cache, CORS config, WebSocket handlers, and validation schemas. The Request struct carries parsed JSON body (req.json), query parameters, cookies, auth context, trace context, and uploaded files. The Response struct carries status, headers, body, cookies, ETag, Last-Modified, and an optional stream handle.
Production Features
- Authentication — API key extraction (X-API-Key, Bearer token, Basic auth, query param),
require_auth()guard,basic_auth()andbearer_token()helpers - Rate limiting — Per-IP and per-route sliding window via
rate_limit_middleware()with configurable limit and window - Compression — Automatic gzip, brotli, and deflate via
compression_middleware()with Accept-Encoding negotiation - Security headers — Helmet-style defaults: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy, Permissions-Policy
- CORS — Configurable origins, methods, headers, credentials, preflight handling, wildcard subdomain matching
- CSRF protection — Token validation via
csrf_middleware()for state-changing requests - Sessions — In-memory cookie-based session store with configurable TTL, secure/httpOnly flags
- Response caching — LRU-eviction cache with TTL, Vary header support, ETag generation, Cache-Control parsing
- Conditional requests — ETag and Last-Modified checks returning 304 Not Modified
- Content negotiation — JSON, HTML, XML, plain text, file, stream, and redirect responses
- Input validation — JSON schema validation, email/URL/UUID/date helpers, XSS sanitization, SQL injection prevention
- Static file serving — SPA fallback, directory listing, MIME detection, gzip-precompressed assets
- WebSocket support — Upgrade handshake, text/binary frames, ping/pong keepalive, close codes
- Observability — Structured request logging, distributed tracing (trace_id), metrics counters, audit events
- Job queues — In-memory FIFO queue with enqueue/dequeue/process lifecycle
- Connection pooling — Generic pool with acquire/release for database or external service connections
- Request coalescing — Deduplication of concurrent identical requests (thundering herd prevention)
Junction CLI
All Junction management commands are available through braidc junction <subcommand>:
| Command | Description |
|---|---|
braidc junction new <name> | Scaffold a new Junction project with directory structure and sample files |
braidc junction dev | Start the dev server on port 8080 with live reload |
braidc junction build -o <file> | Build the Junction app to a .bx bytecode artifact |
braidc junction run | Run the Junction app from the project directory |
braidc junction routes | List all registered routes with methods and paths |
braidc junction check | Validate the Junction project configuration and dependencies |
braidc junction test | Run Junction project tests |
Project Structure
A scaffolded Junction application follows this convention:
myapp/
braid.toml # Package manifest (name, version, entrypoint, deps)
src/
main.br # App entrypoint — create_app, middleware, serve
routes.br # Route definitions
auth.br # Auth middleware and policies
storage.br # Data layer / repositories
jobs.br # Job handlers
config.br # Environment config
tests/
test_app.br # Integration tests
public/ # Static assets (SPA build output)
index.html
style.css
app.jsHello World Server
import lib.frameworks.junction;
fn main() {
let app = junction.create_app({
name: "hello",
version: "1.0.0",
env: "development"
});
junction.route(app, "GET", "/", fn(req: Request) -> Response {
return junction.text("Hello, Junction!", 200);
});
junction.serve(app, 8080);
}Scaffolding a New App
braidc junction new myapi cd myapi braidc junction devbraid.toml
The package manifest uses standard braid.toml format:
name = "myapi"
version = "1.0.0"
entrypoint = "src/main.br"
[dependencies]
junction = "*"