HTTP Server
Understand how Frame-Master's HTTP server works, built on top of Bun's blazing-fast server implementation. Learn about request handling, routing, and server lifecycle.
Overview
Frame-Master uses Bun.serve() as its underlying HTTP server, providing exceptional performance while adding a powerful plugin system and request management layer.
Built on Bun
Server Architecture
Server Initialization
Frame-Master initializes the HTTP server through a multi-stage process that loads plugins, merges configurations, and sets up request handling.
Startup Sequence
1. Configuration Loading
Frame-Master loads your frame-master.config.ts file and validates the configuration.
2. Plugin Initialization
All plugins in the plugins array are loaded and initialized in order.
3. Server Config Merging
Plugin serverConfig hooks are merged with your HTTPServer configuration using a deep merge strategy.
4. Server Start Hooks
Plugin serverStart hooks run, allowing plugins to perform initialization tasks.
5. File System Watchers (Development)
In development mode, file watchers are set up for hot reloading and plugin file watching.
6. Bun.serve() Start
Finally, Bun.serve() is called with the merged configuration and Frame-Master's fetch handler.
Server Initialization Code
export default async () => {// Run plugin serverStart hooksawait runOnStartMainPlugins();// Setup file watchers (dev mode only)await runFileSystemWatcherPlugin();// Start the HTTP serverreturn Bun.serve({development: {chromeDevToolsAutomaticWorkspaceFolders: true,},...pluginServerConfig,fetch: (request, server) => {logRequest(request);const reqManager = new masterRequest({ request, server });return reqManager.handleRequest();},routes: { ...masterRoutes, ...pluginsRoutes },websocket: { /* WebSocket handlers */ },});};
Configuration Merging
Frame-Master uses a deep merge strategy to combine server configurations from multiple sources:
// Merge order (lowest to highest priority):// 1. Plugin 1 serverConfig// 2. Plugin 2 serverConfig// 3. Plugin N serverConfig// 4. Your HTTPServer config (highest priority)function deepMergeServerConfig(target: any, source: any): any {const result = { ...target };for (const [key, sourceValue] of Object.entries(source)) {const targetValue = result[key];// Detect conflictsif (targetValue !== sourceValue &&typeof targetValue !== "object") {throw new Error(`Conflict: ${key} has different values`);}// Deep merge objectsif (isPlainObject(targetValue) && isPlainObject(sourceValue)) {result[key] = deepMergeServerConfig(targetValue, sourceValue);}// Concatenate arrayselse if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {result[key] = [...targetValue, ...sourceValue];}// Source overrides targetelse {result[key] = sourceValue;}}return result;}
Configuration Conflicts
disableHttpServerOptionsConflictWarning.Request Lifecycle
Every HTTP request goes through a structured lifecycle managed by Frame-Master's request manager.
Request Phases
Request Manager
The masterRequest class is the core of Frame-Master's request handling:
class masterRequest<ContextType extends Record<string, unknown> = {}> {// Core propertiespublic request: Request;public currentState: RequestState;public match?: RequestMatch;public isAskingHTML: boolean;public URL: URL;public serverInstance: Bun.Server<undefined>;public serverConfig: FrameMasterConfig;// Cookie managementpublic getCookie<T extends Record<string, unknown>>(name: string,encrypted?: boolean): T | undefined;public setCookie<T extends Record<string, unknown>>(name: string,data: T,options?: CookieOptions,dataOptions?: SetDataOptions): this;public deleteCookie(name: string,options?: DeleteCookieOptions): this;// Response managementpublic setResponse(body: BodyInit | null, init?: ResponseInit): this;public unsetResponse(): void;public isResponseSetted(): boolean;public sendNow(): void;public get response(): Response | undefined;// Context managementpublic setContext<T>(context: T): T;public getContext<T = ContextType>(): T;// Global values injectionpublic setGlobalValues<T extends Partial<typeof globalThis>>(values: T): this;public preventGlobalValuesInjection(): this;public isGlobalValuesInjectionPrevented(): boolean;// HTML rewrite controlpublic preventRewrite(): this;// Header managementpublic setHeader(name: string, value: string): this;// Internalpublic async handleRequest(): Promise<Response>;public async toResponse(): Promise<Response>;}
Key Properties
request
The original Web Request object from Bun
currentState
Current phase: before_request, request, or after_request
isAskingHTML
True if the request Accept header includes text/html (initial page load)
Cookie Methods
Get, set, and delete cookies with encryption support
Response Methods
Build and send HTTP responses with full control
Request Logging
Frame-Master automatically logs all incoming requests with color-coded HTTP methods:
GET → /POST → /api/usersPUT → /api/users/123DELETE → /api/users/123PATCH → /api/users/123
Route Handling
Frame-Master supports multiple types of routes: static routes defined in configuration and dynamic routes managed by plugins.
Static Routes
Define static routes in your configuration for simple endpoints:
const config: FrameMasterConfig = {HTTPServer: {port: 3000,// Static routes (Bun native routing)routes: {"/api/health": () => Response.json({ status: "ok" }),"/api/version": () => Response.json({version: "1.0.0",framework: "Frame-Master"}),},},plugins: [],};
Bun Routes
Plugin Routes
Plugins provide their own routes through the serverConfig hook:
const myPlugin: FrameMasterPlugin = {name: "my-api-plugin",version: "1.0.0",serverConfig: {routes: {"/api/custom": () => Response.json({message: "From plugin"}),},},// Or use the request hook for complex routingrouter: {request(master) {if (master.pathname === "/api/complex") {master.setResponse(JSON.stringify({ data: "Complex logic" }),{ headers: { "Content-Type": "application/json" } });}},},};
Route Priority
Routes are merged and matched in this order:
WebSocket Support
Frame-Master provides built-in WebSocket support through Bun's WebSocket implementation with plugin integration.
const config: FrameMasterConfig = {HTTPServer: {port: 3000,websocket: {maxPayloadLength: 16 * 1024 * 1024, // 16MBidleTimeout: 120, // secondsbackpressureLimit: 1024 * 1024, // 1MBperMessageDeflate: true,},},plugins: [],};
Plugin WebSocket Handlers
Plugins can hook into WebSocket events:
const wsPlugin: FrameMasterPlugin = {name: "websocket-plugin",version: "1.0.0",websocket: {onOpen(ws) {console.log("WebSocket opened");ws.send("Welcome!");},onMessage(ws, message) {console.log("Received:", message);ws.send(`Echo: ${message}`);},onClose(ws) {console.log("WebSocket closed");},},};
Learn More
Development Features
Frame-Master includes several development-only features to improve the developer experience.
Hot Module Reload (HMR)
When running in development mode with bun --hot frame-master dev, Frame-Master provides hot reloading:
Server Hot Reload
Bun automatically restarts the server when code changes are detected
Plugin File Watching
Plugins can watch specific directories and trigger custom rebuild logic
Fast Restarts
Bun's hot reload is extremely fast, typically under 100ms
# Start with hot reloadbun --hot frame-master dev# Or via package.json scriptbun run dev
Chrome DevTools
Frame-Master enables Chrome DevTools integration in development mode:
Bun.serve({development: {chromeDevToolsAutomaticWorkspaceFolders: true,},// ... rest of config});
This allows you to debug server-side code using Chrome's DevTools by opening chrome://inspect.
File System Watchers
Plugins can register directories to watch for changes:
const myPlugin: FrameMasterPlugin = {name: "my-plugin",version: "1.0.0",// Specify directories to watchfileSystemWatchDir: ["src/pages", "src/components"],// Handle file changesonFileSystemChange(event, file, absolutePath) {console.log(`${event}: ${file}`);if (event === "change" && file.endsWith(".tsx")) {// Trigger rebuild or processingrebuildComponent(absolutePath);}},};
Production Mode
NODE_ENV=production)Performance
Frame-Master inherits Bun's exceptional performance characteristics while adding minimal overhead.
Bun's Performance
Frame-Master is built on Bun, which offers industry-leading HTTP server performance
Native Speed
Bun's HTTP server is written in Zig and optimized for throughput
Low Latency
Minimal request-to-response overhead, typically under 1ms
High Throughput
Can handle thousands of requests per second on modern hardware
Memory Efficient
Lower memory footprint compared to Node.js-based frameworks
Frame-Master Overhead
Frame-Master adds a thin abstraction layer with minimal performance impact
• Request logging: ~0.1ms (disabled in production if desired)
• Plugin hooks: ~0.5ms per hook (depends on plugin logic)
• Cookie parsing/setting: ~0.2ms
• Route matching: ~0.3ms
Total overhead: ~1-2ms per request
Optimization Tips
- Use Bun's native routes for simple endpoints (fastest)
- Minimize plugin hooks in the request path
- Cache expensive operations in plugins
- Use streaming responses for large payloads
- Enable compression for text-based responses
Best Practices
Configure Development Mode
Set development: true in HTTPServer config during development for better error messages and debugging
Use Request Logging Wisely
Disable verbose logging in production to reduce noise and improve performance
Organize Plugin Order
Place plugins that modify requests early in the array, and response-modifying plugins later
Optimize Hot Paths
Keep plugin request hooks fast - avoid synchronous I/O or heavy computation
Handle Errors Gracefully
Implement custom error handlers to provide better user experience and security
External Resources
Learn more about the underlying technologies and APIs.
Complete guide to Bun's HTTP server implementation
Learn about WebSocket support in Bun
Understand Bun's native routing capabilities
Reference for the standard Web Request object
Next Steps
Continue learning about Frame-Master's core functionality.
Request Handling
Deep dive into the masterRequest class and request lifecycle
Configuration
Explore all HTTPServer configuration options
Plugin System
Learn how plugins extend the HTTP server
Build System
Understand how Frame-Master builds and serves your application
