New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details โ†’ โ†’
Socket
Book a DemoSign in
Socket

openspeed

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openspeed

High-performance web framework with JSX, SSG, RPC, streaming, and type safety. Inspired by Hono and Elysia but 2-3x faster.

latest
Source
npmnpm
Version
1.1.2
Version published
Weekly downloads
15
Maintainers
1
Weekly downloads
ย 
Created
Source

Openspeed Logo

Openspeed

A high-performance, developer-friendly web framework inspired by Hono and Elysia. Built for speed, extensibility, and excellent DX across multiple JavaScript runtimes.

Openspeed provides a modern, type-safe API with runtime-agnostic support for Node.js, Bun, and Deno. It features a powerful plugin system, advanced routing, and built-in optimizations for production applications.

npm version Tests License GitHub stars GitHub issues

โœจ Features

Core Features

  • ๐Ÿš€ High Performance: Optimized trie-based router with caching and O(1) lookups
  • ๐Ÿ”ง Runtime Agnostic: Native support for Node.js, Bun, and Deno
  • ๐Ÿ“ File Uploads: Built-in multipart parsing with streaming support
  • ๐ŸŒ WebSockets: Real-time communication with room-based messaging
  • ๐Ÿช Cookies: Session management with CookieJar implementation
  • ๐Ÿ›ก๏ธ Error Handling: Comprehensive error management with typed exceptions
  • ๐Ÿ“ Type Safety: Full TypeScript support with advanced type definitions
  • ๐Ÿงฉ Extensible: Plugin architecture for custom middleware
  • ๐Ÿ“Š Auto-Generated APIs: OpenAPI spec generation from routes
  • โšก Fast Development: Hot reload and route introspection
  • ๐Ÿ—๏ธ CLI Tooling: Scaffold new projects instantly
  • ๐Ÿ”’ Security: Built-in authentication and rate limiting
  • ๐Ÿ“ Static Serving: Efficient file serving with caching
  • โš›๏ธ JSX Support: React-like JSX rendering for HTML templating (like Hono)
  • ๐Ÿ“„ Static Site Generation: Pre-render routes to static HTML files
  • ๐Ÿ”— RPC Type Safety: End-to-end type safety without code generation (like Elysia)
  • ๐ŸŒŠ Streaming Responses: Generator functions, SSE, and NDJSON streaming
  • โœ… Enhanced Validation: Support for Zod, Valibot, ArkType, Effect via Standard Schema

๐ŸŒŸ Advanced Features (NEW!)

  • ๐Ÿ“‚ File-based Routing: Next.js-style automatic route generation from file structure
  • ๐Ÿ’พ Database Adapters: Type-safe MongoDB, MySQL, PostgreSQL, Redis with connection pooling
  • ๐Ÿ‘ฅ Multi-tenancy: Database isolation per tenant with automatic context switching
  • ๐Ÿ” RBAC: Role-Based Access Control with hierarchical permissions
  • ๐Ÿ“ Audit Logging: SOC 2, GDPR, HIPAA, PCI-DSS compliance support
  • โ˜ธ๏ธ Kubernetes: Auto-scaling operators with HPA and custom metrics
  • ๐Ÿง  AI-Powered Optimization: ML-based request prediction and adaptive performance tuning
  • โšก Advanced Caching: Intelligent query coalescing, batching, and bloom filters
  • ๐Ÿš€ Zero-Copy Streaming: Memory-efficient large payload handling
  • ๐ŸŽฏ Object Pooling: High-frequency object reuse for optimal performance
  • ๐Ÿ”’ End-to-End Type Safety: Best-in-class type safety with auto-completion, runtime validation, and end-to-end type inference

๐Ÿ› ๏ธ Development Tools

  • ๐Ÿ“ Route Visualizer: Interactive dashboard showing all API routes with methods, handlers, and middleware
  • โšก Performance Monitor: Real-time performance tracking with response times, error rates, and bottleneck detection
  • ๐ŸŽฎ API Playground: Test endpoints directly from the browser with custom headers and request bodies
  • ๐Ÿ“Š DevTools Dashboard: Unified development interface combining all debugging and monitoring tools
  • ๐Ÿ” Request Inspector: Detailed request/response logging with timing and memory usage
  • ๐Ÿšจ Error Enhancement: Developer-friendly error pages with actionable debugging information

๐Ÿ”’ Security Features

  • ๐Ÿ›ก๏ธ CSRF Protection: Token-based CSRF prevention with origin validation and constant-time comparison
  • ๐Ÿ’‰ SQL Injection Prevention: Parameterized query validator with forbidden pattern detection
  • ๐Ÿ” XSS Protection: Automatic HTML escaping with secure JSX rendering
  • ๐Ÿ”‘ Secure Authentication: Bcrypt password hashing with configurable rounds (12+ recommended)
  • ๐Ÿช Secure Cookies: HTTP-only, secure, and SameSite cookie configuration
  • ๐Ÿ“‹ Input Validation: Schema-based validation with Zod, Valibot, ArkType
  • ๐Ÿšฆ Rate Limiting: Brute force protection and DDoS mitigation
  • ๐Ÿ“ File Upload Security: MIME validation, size limits, and optional malware scanning
  • ๐Ÿ“Š Security Headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options
  • ๐Ÿ” Security Scanner: Automated vulnerability detection for common issues
  • ๐Ÿ”ง Auto-Fixer: Automated remediation for weak crypto, insecure cookies, and more
  • โœ… Security Testing: Comprehensive test suite covering OWASP Top 10

๐Ÿ“ฆ Installation

Install Openspeed using your preferred package manager:

# npm
npm install openspeed

# pnpm
pnpm add openspeed

# yarn
yarn add openspeed

# bun
bun add openspeed

Creating a New Project

Use the CLI tool to scaffold a new Openspeed project:

npx create-openspeed-app my-app
cd my-app
npm run dev

This creates a complete project structure with TypeScript, testing, and example routes.

For more details, see the Getting Started Guide.

๐Ÿš€ Quick Start

Here's a complete example showing Openspeed's core features:

import { Openspeed } from 'openspeed';

const app = Openspeed();

// Basic routing with parameter extraction
app.get('/', (ctx) => ctx.text('Hello Openspeed!'));

app.get('/api/users/:id', (ctx) => {
  const userId = ctx.getParam('id');
  return ctx.json({
    id: userId,
    name: 'ElonDuck',
    timestamp: new Date().toISOString()
  });
});

// JSON handling with automatic parsing
app.post('/api/data', async (ctx) => {
  const data = ctx.getBody(); // Automatically parsed JSON
  return ctx.json({ received: data, success: true });
});

// File upload with multipart support
app.post('/upload', (ctx) => {
  const file = ctx.file;
  if (file) {
    return ctx.json({
      filename: file.filename,
      size: file.size,
      mimetype: file.mimetype
    });
  }
  return ctx.json({ error: 'No file uploaded' }, 400);
});

// Real-time WebSocket with room-based messaging
app.ws('/chat/:room', (ws, ctx) => {
  const room = ctx.getParam('room');
  ws.join(room);

  ws.on('message', (data) => {
    // Broadcast to all users in the room
    ws.broadcast(room, `User said: ${data}`);
  });

  ws.on('join', (newRoom) => {
    ws.leave(room);
    ws.join(newRoom);
  });
});

// Session management with secure cookies
app.get('/login', (ctx) => {
  ctx.setCookie('session', 'user123', {
    httpOnly: true,
    secure: true,
    maxAge: 86400 // 24 hours
  });
  return ctx.text('Logged in successfully!');
});

app.get('/profile', (ctx) => {
  const sessionId = ctx.getCookie('session');
  if (!sessionId) {
    return ctx.json({ error: 'Not authenticated' }, 401);
  }
  return ctx.json({ userId: sessionId, profile: 'User data' });
});

// Error handling with custom status codes
app.get('/error', (ctx) => {
  throw new Error('Something went wrong!');
});

// Start the server
app.listen(3000, () => {
  console.log('๐Ÿš€ Openspeed server running on http://localhost:3000');
});

This example demonstrates routing, JSON handling, file uploads, WebSockets, cookies, and error handling. For more examples, see the examples directory.

๐Ÿ—๏ธ Core Architecture

Router

  • Trie-based routing with parameter extraction
  • Route metadata collection for tooling
  • Middleware chaining per route

Context

  • Web Standard Request/Response objects
  • Helper methods: text(), json(), html()
  • Parameter and query parsing

App API

  • Fluent interface for configuration
  • Global and route-level middleware
  • Plugin system for extensibility

๐Ÿ”Œ Official Plugins

File Upload

Handle multipart form data with streaming support:

import { upload } from 'openspeed/plugins/upload';

app.use(upload());

// Single file upload
app.post('/upload', (ctx) => {
  const file = ctx.file;
  if (file) {
    return ctx.json({
      filename: file.filename,
      mimetype: file.mimetype,
      size: file.size
    });
  }
  return ctx.text('No file uploaded', 400);
});

// Multiple files
app.post('/upload-multiple', (ctx) => {
  const files = ctx.files?.avatar || [];
  return ctx.json({ uploaded: files.length });
});

WebSocket

Real-time communication with room management:

import { websocket } from 'openspeed/plugins/websocket';

app.use(websocket());

// Basic WebSocket
app.ws('/ws', (ws) => {
  ws.on('message', (data) => {
    ws.send(`Echo: ${data}`);
  });
});

// Room-based chat
app.ws('/chat/:room', (ws, ctx) => {
  const room = ctx.getParam('room');
  ws.join(room);

  ws.on('message', (data) => {
    ws.broadcast(room, data); // Send to all in room except sender
    ws.broadcastAll(room, data); // Send to everyone in room
  });

  ws.on('join', (newRoom) => {
    ws.leave(room);
    ws.join(newRoom);
  });
});

Cookies

Session management with CookieJar:

import { cookie } from 'openspeed/plugins/cookie';

app.use(cookie());

// Set cookies
app.get('/set-session', (ctx) => {
  ctx.setCookie('session', 'abc123', {
    httpOnly: true,
    secure: true,
    maxAge: 86400 // 1 day
  });
  return ctx.text('Session set!');
});

// Get cookies
app.get('/profile', (ctx) => {
  const sessionId = ctx.getCookie('session');
  if (!sessionId) {
    return ctx.text('Not authenticated', 401);
  }
  return ctx.json({ sessionId });
});

Error Handler

Comprehensive error management with typed exceptions:

import { errorHandler, HttpError } from 'openspeed/plugins/errorHandler';

app.use(errorHandler());

// Custom errors
app.get('/api/user/:id', (ctx) => {
  const userId = ctx.getParam('id');
  if (!userId) {
    throw new HttpError(400, 'User ID required');
  }

  const user = findUser(userId);
  if (!user) {
    throw new HttpError(404, 'User not found');
  }

  return ctx.json(user);
});

// Async error handling
app.get('/api/async', async (ctx) => {
  try {
    const data = await riskyOperation();
    return ctx.json(data);
  } catch (error) {
    throw new HttpError(500, 'Operation failed');
  }
});

CORS

Cross-origin resource sharing:

import { cors } from 'openspeed/plugins/cors';

app.use(cors({
  origin: ['http://localhost:3000', 'https://myapp.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE']
}));

Logger

Request logging with customizable formats:

import { logger } from 'openspeed/plugins/logger';

app.use(logger({
  format: 'combined', // 'combined', 'common', 'dev', 'short', 'tiny'
  skip: (req) => req.url?.includes('/health')
}));

JSON Parser

Parse JSON request bodies:

import { json } from 'openspeed/plugins/json';

app.use(json({ limit: '10mb' }));

app.post('/api/data', (ctx) => {
  const data = ctx.getBody(); // Parsed JSON
  return ctx.json({ received: data });
});

OpenAPI Generator

Auto-generate API documentation and clients in any programming language with best-in-class type safety, auto-completion, runtime validation, and end-to-end type inference. Built-in support for TypeScript, PHP, C++, Rust, Go, and Python, with extensible architecture for adding custom languages.

import { openapi } from 'openspeed/plugins/openapi';

const api = openapi({ title: 'My API', version: '1.0.0' });

// Register a custom language generator
api.registerLanguage('kotlin', (routes) => {
  let clientCode = `// Generated Kotlin OpenSpeed Client
package com.example.api

import okhttp3.*
import com.google.gson.Gson

class OpenSpeedClient(private val baseUrl: String) {
    private val client = OkHttpClient()
    private val gson = Gson()

`;

  for (const route of routes) {
    const path = route.path;
    const method = route.method.toUpperCase();
    const funcName = path.replace(/:/g, '_').replace(/\//g, '_').replace(/^_/, '') || 'root';

    // Build function signature
    const params = [];
    if (route.parameters?.some(p => p.in === 'path')) params.push('pathParams: Map<String, String>');
    if (route.parameters?.some(p => p.in === 'query')) params.push('queryParams: Map<String, String>? = null');
    if (route.requestBody) params.push('body: Any? = null');
    params.push('headers: Map<String, String>? = null');

    clientCode += `    fun ${funcName}(${params.join(', ')}): String {\n`;

    // URL construction
    let urlTemplate = route.path;
    for (const param of route.parameters || []) {
      if (param.in === 'path') {
        urlTemplate = urlTemplate.replace(`:${param.name}`, `\${pathParams["${param.name}"]}`);
      }
    }
    clientCode += `        var url = "\${baseUrl}${urlTemplate}"\n`;

    if (route.parameters?.some(p => p.in === 'query')) {
      clientCode += `        queryParams?.let { qp ->\n`;
      clientCode += `            val queryString = qp.entries.joinToString("&") { "\${it.key}=\${it.value}" }\n`;
      clientCode += `            url += "?\${queryString}"\n`;
      clientCode += `        }\n`;
    }

    // HTTP request
    clientCode += `        val request = Request.Builder().url(url)\n`;
    if (route.requestBody) {
      clientCode += `        body?.let { b ->\n`;
      clientCode += `            val jsonBody = gson.toJson(b)\n`;
      clientCode += `            request.post(RequestBody.create(MediaType.parse("application/json"), jsonBody))\n`;
      clientCode += `        }\n`;
    } else {
      clientCode += `        request.${method.toLowerCase()}()\n`;
    }

    clientCode += `        headers?.forEach { (k, v) -> request.addHeader(k, v) }\n`;
    clientCode += `        val response = client.newCall(request.build()).execute()\n`;
    clientCode += `        return response.body()?.string() ?: ""\n`;
    clientCode += `    }\n\n`;
  }

  clientCode += `}
`;
  return clientCode;
});

// Generate clients for any registered language
const kotlinClient = api.generateClient('kotlin');

// Access generated clients via dynamic endpoints:
// /client.ts - TypeScript client with full type safety
// /client.php - PHP client with cURL
// /client.cpp - C++ client with nlohmann/json
// /client.rs - Rust client with reqwest and serde_json
// /client.go - Go client with net/http and encoding/json
// /client.py - Python client with requests library
// /client.{any-ext} - Custom language clients (e.g., /client.kotlin)

app.get('/openapi.json', (ctx) => ctx.json(api.generate()));

// Or generate client files using CLI for any supported language
// npx openspeed client client.ts   # TypeScript
// npx openspeed client client.php  # PHP
// npx openspeed client client.cpp  # C++
// npx openspeed client client.rs   # Rust
// npx openspeed client client.go   # Go
// npx openspeed client client.py   # Python
// npx openspeed client client.kotlin  # Custom language

This generates fully typed clients in your preferred language that you can import and use with auto-completion and runtime validation. The extensible architecture allows you to add support for any programming language by registering custom generators.

Supported Languages & Extensions

Built-in Languages:

  • TypeScript (.ts, .js) - Full type safety with Zod validation
  • PHP (.php) - cURL-based HTTP clients with type hints
  • C++ (.cpp, .cc, .cxx) - libcurl + nlohmann/json clients
  • Rust (.rs) - reqwest + serde_json async clients
  • Go (.go) - net/http + encoding/json clients
  • Python (.py) - requests library clients

Extensible System: Register custom language generators for any programming language:

// Example: Add Java client generation
api.registerLanguage('java', (routes) => {
  return `// Generated Java client\npublic class ApiClient {\n    // HTTP client implementation\n}`;
});

// Now you can generate Java clients
const javaClient = api.generateClient('java');
// Or via endpoint: GET /client.java
// Or via CLI: npx openspeed client client.java

The system supports 50+ file extensions mapped to language names, making it easy to add support for languages like Java, Kotlin, C#, Swift, Ruby, and more.

Security Plugins

Comprehensive security features for production applications:

CSRF Protection

Prevent Cross-Site Request Forgery attacks:

import { csrf, csrfToken, csrfInput } from 'openspeed/plugins';

app.use(csrf({
  secret: process.env.CSRF_SECRET,
  cookieName: '_csrf',
  headerName: 'x-csrf-token',
  enforceForMethods: ['POST', 'PUT', 'DELETE', 'PATCH']
}));

// In your form
app.get('/form', (ctx) => {
  const token = csrfToken(ctx);
  return ctx.html(`
    <form method="POST">
      <input type="hidden" name="csrf_token" value="${token}" />
      <button type="submit">Submit</button>
    </form>
  `);
});

SQL Injection Prevention

Validate SQL queries and parameters:

import { validateSQL, sql } from 'openspeed/plugins';

// โŒ Vulnerable
const query = `SELECT * FROM users WHERE id = ${userId}`;

// โœ… Safe
const { query, params } = sql(
  'SELECT * FROM users WHERE id = ?',
  [userId]
);

// Or validate existing queries
validateSQL(query, params); // Throws if unsafe patterns detected

Input Validation

Schema-based validation with Zod:

import { validate } from 'openspeed/plugins';
import { z } from 'zod';

const userSchema = z.object({
  email: z.string().email(),
  password: z.string().min(12),
  age: z.number().int().min(13)
});

app.post('/register',
  validate({ body: userSchema }),
  async (ctx) => {
    const data = ctx.req.body; // Typed and validated
    return ctx.json({ success: true });
  }
);

Security Headers

Comprehensive security headers:

import { security } from 'openspeed/plugins';

app.use(security({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'nonce-{random}'"],
      styleSrc: ["'self'", "'unsafe-inline'"]
    }
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true
  },
  noSniff: true,
  frameOptions: 'DENY'
}));

For more security features and best practices, see the Security Guide.

๐Ÿ”’ Security Tools

Openspeed includes automated security tools:

# Scan for vulnerabilities
npm run security:scan

# Export detailed JSON report
npm run security:scan:json

# Auto-fix common security issues
npm run security:fix

# Preview fixes without applying
npm run security:fix:dry

# Check dependencies
npm audit

Read our Security Policy for vulnerability reporting.

๐ŸŒ Runtime Support

Openspeed automatically detects and adapts to your runtime:

  • Node.js: Uses http module
  • Bun: Uses Bun.serve
  • Deno: Uses Deno.serve
  • Cloudflare Workers: Planned

๐Ÿงช Benchmarks

Performance comparison (requests/second):

RuntimeOpenspeedHonoElysia
Node.js~7,000*~3,200~2,800
Bun~24,000*~11,500~10,200
Deno~17,000*~8,000~7,500

Note: Benchmarks run with autocannon (100 concurrent connections, 10 seconds) *With adaptive optimizer enabled - 2x-3x faster than competition!

Latest Benchmark Results (Node.js v23.10.0)

Basic Routing (GET /):

  • Requests/sec: 4,678 avg (up to 7,331)
  • Latency: 257ms avg (208ms median)
  • Throughput: 921 KB/s
  • Total: 48k requests, 9.21 MB

JSON Handling (POST /json):

  • Requests/sec: 6,537 avg (up to 8,367)
  • Latency: 7ms avg (6ms median)
  • Throughput: 1.37 MB/s
  • Total: 65k requests, 13.7 MB

Test conditions: 100 connections (routing), 50 connections (JSON), 10 seconds each, autocannon tool. Results show excellent performance with end-to-end type safety enabled.

Running Benchmarks

Compare Openspeed with Hono and Elysia across different scenarios:

# Install dependencies
pnpm install

# Build the project
pnpm run build

# Run comprehensive benchmarks (Node.js)
pnpm run bench:node

# Run comprehensive benchmarks (Bun)
pnpm run bench:bun

# Run specific benchmark scenario
cd benchmarks
bun run apps/openspeed-routing.ts 3000 &
autocannon -c 100 -d 10 http://localhost:3000/

Available benchmark scenarios:

  • routing: Basic routing performance
  • json: JSON parsing and response
  • middleware: Middleware chaining
  • plugins: Plugin performance
  • real-world: Full application simulation

๐Ÿ› ๏ธ Development

Running Tests

pnpm test

Building

pnpm run build

Development Server

pnpm run dev

Route Inspection

app.printRoutes(); // Shows all routes with middleware info
console.log(app.routes()); // Returns route metadata array

๐Ÿ“š Examples

Openspeed includes comprehensive examples to demonstrate real-world usage patterns. All examples are available in the examples directory.

Hello World Example

A minimal setup showing basic routing and middleware:

cd examples/hello-openspeed
pnpm install
pnpm run dev

Features:

  • Basic routing with parameters
  • Middleware setup
  • JSON responses
  • Error handling

View Source

ML-Optimized E-commerce API

A production-ready e-commerce application with advanced features:

cd examples/ml-optimized-api
pnpm install
pnpm run dev

Features:

  • User Management: Registration, login, profiles
  • Product Catalog: CRUD operations, search, categories
  • Shopping Cart: Add/remove items, persistence
  • Order Processing: Checkout flow, payment simulation
  • Analytics Dashboard: Sales metrics, user behavior
  • ML Optimization: Performance prediction, caching, anomaly detection
  • Database Integration: PostgreSQL with connection pooling
  • Authentication: JWT-based auth with role management

This example showcases Openspeed's enterprise capabilities and serves as a reference architecture.

View Source | API Documentation

Running Examples

# Clone the repository
git clone https://github.com/JonusNattapong/OpenSpeed.git
cd OpenSpeed

# Install dependencies
pnpm install

# Run any example
cd examples/ml-optimized-api
pnpm run dev

# Visit http://localhost:3000 to see the API in action

For more examples and tutorials, check out our documentation.

๐Ÿ“ Project Structure

src/
โ”œโ”€โ”€ openspeed/
โ”‚   โ”œโ”€โ”€ index.ts              # Main app factory
โ”‚   โ”œโ”€โ”€ router.ts             # Trie router implementation
โ”‚   โ”œโ”€โ”€ context.ts            # Request/response context with helpers
โ”‚   โ”œโ”€โ”€ server.ts             # Runtime detection & adapters
โ”‚   โ””โ”€โ”€ plugins/              # Official plugins
โ”‚       โ”œโ”€โ”€ adaptiveOptimizer.ts  # ML-powered optimization
โ”‚       โ”œโ”€โ”€ auditLog.ts       # Audit logging
โ”‚       โ”œโ”€โ”€ auth.ts           # Authentication
โ”‚       โ”œโ”€โ”€ circuitBreaker.ts # Circuit breaker pattern
โ”‚       โ”œโ”€โ”€ codegen.ts        # Code generation
โ”‚       โ”œโ”€โ”€ compression.ts    # Response compression
โ”‚       โ”œโ”€โ”€ cookie.ts         # Cookie management
โ”‚       โ”œโ”€โ”€ cors.ts           # CORS middleware
โ”‚       โ”œโ”€โ”€ database.ts       # Database adapters
โ”‚       โ”œโ”€โ”€ dashboard.ts      # Admin dashboard
โ”‚       โ”œโ”€โ”€ email.ts          # Email service
โ”‚       โ”œโ”€โ”€ errorHandler.ts   # Error handling
โ”‚       โ”œโ”€โ”€ fileRouting.ts    # File-based routing
โ”‚       โ”œโ”€โ”€ graphql.ts        # GraphQL support
โ”‚       โ”œโ”€โ”€ hotReload.ts      # Hot reload
โ”‚       โ”œโ”€โ”€ index.ts          # Plugin exports
โ”‚       โ”œโ”€โ”€ json.ts           # JSON parsing
โ”‚       โ”œโ”€โ”€ kubernetes.ts     # Kubernetes operators
โ”‚       โ”œโ”€โ”€ loadBalancer.ts   # Load balancing
โ”‚       โ”œโ”€โ”€ logger.ts         # Request logging
โ”‚       โ”œโ”€โ”€ memory.ts         # Memory management
โ”‚       โ”œโ”€โ”€ metrics.ts        # Metrics collection
โ”‚       โ”œโ”€โ”€ mlOptimizer.ts    # ML optimization (legacy)
โ”‚       โ”œโ”€โ”€ openapi.ts        # API documentation
โ”‚       โ”œโ”€โ”€ playground.ts     # Development playground
โ”‚       โ”œโ”€โ”€ rateLimit.ts      # Rate limiting
โ”‚       โ”œโ”€โ”€ rbac.ts           # Role-based access control
โ”‚       โ”œโ”€โ”€ static.ts         # Static file serving
โ”‚       โ”œโ”€โ”€ storage.ts        # File storage
โ”‚       โ”œโ”€โ”€ stripe.ts         # Stripe payment
โ”‚       โ”œโ”€โ”€ tracing.ts        # Request tracing
โ”‚       โ”œโ”€โ”€ twilio.ts         # SMS service
โ”‚       โ”œโ”€โ”€ upload.ts         # File upload handling
โ”‚       โ”œโ”€โ”€ validate.ts       # Request validation
โ”‚       โ””โ”€โ”€ websocket.ts      # WebSocket support
โ”œโ”€โ”€ cli/                      # CLI commands
โ”œโ”€โ”€ create-openspeed-app/     # CLI scaffold tool
examples/
โ”œโ”€โ”€ ml-optimized-api/         # Full e-commerce API with ML optimization
benchmarks/                   # Performance testing
โ”œโ”€โ”€ apps/                     # Benchmark applications
โ”‚   โ”œโ”€โ”€ openspeed-*.ts        # Openspeed benchmarks
โ”‚   โ”œโ”€โ”€ hono-*.ts             # Hono benchmarks
โ”‚   โ””โ”€โ”€ elysia-*.ts           # Elysia benchmarks
โ”œโ”€โ”€ run-comprehensive.ts      # Comprehensive benchmark runner
โ”œโ”€โ”€ tsconfig.benchmark.json   # Benchmark TypeScript config
tests/                        # Unit test suite
โ”œโ”€โ”€ plugins/                  # Plugin tests
docs/                         # Documentation
โ”œโ”€โ”€ plugins/                  # Plugin documentation
apps/                         # Application templates
packages/                     # Monorepo packages

## ๐Ÿ“ Project Structure
src/
โ”œโ”€โ”€ openspeed/
โ”‚   โ”œโ”€โ”€ index.ts          # Main app factory
โ”‚   โ”œโ”€โ”€ router.ts         # Trie router implementation
โ”‚   โ”œโ”€โ”€ context.ts        # Request/response context
โ”‚   โ”œโ”€โ”€ server.ts         # Runtime detection & adapters
โ”‚   โ””โ”€โ”€ plugins/          # Official plugins (see above)
โ”œโ”€โ”€ cli/                  # CLI commands
โ”œโ”€โ”€ create-openspeed-app/ # CLI scaffold tool
examples/
โ”œโ”€โ”€ ml-optimized-api/     # Full e-commerce API with ML optimization
benchmarks/               # Performance testing (see above)
tests/                    # Unit tests
docs/                     # Documentation
apps/                     # Application templates
packages/                 # Monorepo packages

๐Ÿค Contributing

We welcome contributions to Openspeed! Whether you're fixing bugs, adding features, improving documentation, or helping with testing, your help is appreciated.

๐Ÿš€ Getting Started

  • Fork the repository on GitHub
  • Clone your fork:
    git clone https://github.com/your-username/OpenSpeed.git
    cd OpenSpeed
    
  • Install dependencies:
    pnpm install
    
  • Create a feature branch:
    git checkout -b feature/your-feature-name
    

๐Ÿ› ๏ธ Development Workflow

  • Build the project: pnpm run build
  • Run tests: pnpm test
  • Run benchmarks: pnpm run bench:node or pnpm run bench:bun
  • Lint code: pnpm run lint
  • Format code: pnpm run format
  • Generate docs: pnpm run docs

๐Ÿ“ Creating Custom Plugins

Openspeed's plugin system makes it easy to extend functionality. Here's how to create a custom plugin:

import type { Context } from 'openspeed';

interface MyPluginOptions {
  config: string;
  enabled?: boolean;
}

function myPlugin(options: MyPluginOptions) {
  const { config, enabled = true } = options;

  return async (ctx: Context, next: () => Promise<any>) => {
    if (!enabled) return next();

    // Your middleware logic here
    console.log('Plugin config:', config);
    ctx.setHeader('X-Custom-Plugin', 'active');

    await next();

    // Post-processing logic
    console.log('Request completed');
  };
}

// Usage
app.use(myPlugin({ config: 'my-config', enabled: true }));

For more plugin examples, see the plugins documentation.

๐Ÿงช Testing

  • Add unit tests in tests/ directory using Vitest
  • Run tests with pnpm test
  • Aim for high test coverage (>80%)
  • Test both success and error scenarios

๐Ÿ“‹ Pull Request Process

  • Update documentation if needed (README, docs, examples)
  • Add tests for new features
  • Ensure CI passes (build, test, lint, typecheck)
  • Create a Pull Request with clear description:
    • What changes were made
    • Why they were needed
    • How to test the changes
  • Wait for review and address feedback

๐ŸŽฏ Code Style Guidelines

  • TypeScript: Use TypeScript for all new code
  • Naming: Follow camelCase for variables/functions, PascalCase for classes/types
  • Imports: Group imports (external libs, then internal modules)
  • Error Handling: Use proper error types and meaningful messages
  • Documentation: Add JSDoc comments for public APIs
  • Commits: Use conventional commits (feat:, fix:, docs:, etc.)

๐Ÿ“š Documentation

  • Update README.md for API changes
  • Add examples in examples/ directory
  • Update plugin documentation in docs/plugins/
  • Keep CHANGELOG.md up to date

๐Ÿ› Reporting Issues

Found a bug? Have a feature request?

When reporting issues, please include:

  • Clear reproduction steps
  • Expected vs actual behavior
  • Environment details (Node.js/Bun version, OS, Openspeed version)
  • Code snippets or minimal reproduction repo

๐Ÿ“ž Community

๐Ÿ“‹ Contributor License Agreement

By contributing to Openspeed, you agree that your contributions will be licensed under the same MIT license as the project.

Thank you for contributing to Openspeed! Your help makes the framework better for everyone. ๐ŸŽ‰

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐ŸŽฏ Goals

Openspeed aims to provide:

  • Performance: Outperform existing frameworks
  • DX: Excellent developer experience with tooling
  • Ecosystem: Rich plugin ecosystem
  • Compatibility: Work everywhere JavaScript runs

๐Ÿ“– Additional Resources

๐Ÿ†˜ Support

๐Ÿ“„ License

Openspeed is MIT licensed.

Built with โค๏ธ for the modern web

Keywords

web

FAQs

Package last updated on 13 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts