npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2025 – Pkg Stats / Ryan Hefner

nextrush

v2.0.1

Published

πŸš€ NextRush v2 - Enterprise-grade Node.js framework with built-in security, validation, WebSocket, templates, events (CQRS), logging, and DI. 13,261 RPS, zero dependencies, full TypeScript support.

Readme

πŸš€ NextRush v2

Modern, Type-Safe Web Framework for Node.js

Koa-style Context β€’ Express-inspired API β€’ Enterprise Features Built-in

npm version Node.js TypeScript License Tests Zero Dependencies

import { createApp } from 'nextrush';

const app = createApp();

app.get('/hello', async ctx => {
  ctx.json({ message: 'Welcome to NextRush v2! πŸŽ‰' });
});

app.listen(3000);
// Server running at http://localhost:3000

πŸ“– Documentation β€’ πŸš€ Quick Start β€’ πŸ’‘ Why NextRush?


πŸ’‘ Philosophy

NextRush v2 combines the best of three worlds: Koa's elegant async context pattern, Express's intuitive helper methods, and Fastify's performance optimizationsβ€”all with enterprise-grade features built directly into the core.

Unlike other frameworks that require dozens of plugins for production use, NextRush v2 includes security middleware, validation, templating, WebSocket support, and advanced logging out of the box. Choose your preferred API style: convenience methods, Express-like helpers, or Fastify-style configuration.

Built for teams that value type safety, developer experience, and production readiness without the plugin fatigue.


🎯 Zero Dependencies Philosophy

NextRush v2 is built with ZERO runtime dependencies. Every featureβ€”from routing to WebSocket supportβ€”is implemented using only Node.js core modules.

Why Zero Dependencies?

  • πŸ”’ Security - No third-party vulnerabilities in your supply chain
  • ⚑ Faster Installs - No dependency resolution, instant setup
  • πŸ›‘οΈ Stability - No breaking changes from external packages
  • πŸ” Full Control - Every line of code is maintainable and auditable
  • πŸš€ Performance - Optimized for Node.js internals, no abstraction overhead
# Check it yourself! Only devDependencies, ZERO runtime deps
npm ls --production --depth=0
# Result: (empty)

Every framework claims to be "lightweight." NextRush v2 proves it.

| Framework | Runtime Dependencies | | --------------- | ------------------------------------ | | NextRush v2 | 0 ⭐ | | Express | 34+ packages | | Koa | 0 (but needs plugins for everything) | | Fastify | 20+ packages | | Hapi | 50+ packages |

Built-in features without the dependency hell. Security, validation, WebSocket, templates, logging, CQRSβ€”all implemented with pure Node.js.


🎯 Why NextRush v2?

NextRush v2 represents the evolution of Node.js web frameworks, synthesizing proven patterns from Express, Koa, and Fastify into a unified, type-safe framework with enterprise features integrated at the core.

πŸ† Three API Styles, One Framework

| Convenience API | Enhanced API | Configuration API | | ------------------- | ---------------- | --------------------- | | ctx.json() | ctx.res.json() | { handler, schema } | | Clean & simple | Express-inspired | Fastify-style | | Recommended | Familiar pattern | Advanced use cases |

⚑ Performance That Scales

  • Zero Dependencies - Pure Node.js core, no third-party overhead
  • 13,261 RPS Average - Competitive with established frameworks
  • Optimized Router - O(1) static path lookup, pre-compiled routes
  • Memory Efficient - ~60KB baseline, smallest footprint in class
  • Smart Caching - Template caching, efficient buffer management
  • No Supply Chain Tax - Every feature optimized for Node.js internals

πŸ›‘οΈ Enterprise Features Built-In

Unlike other frameworks requiring extensive plugin ecosystems, NextRush v2 includes production-ready features in the core:

const app = createApp();

// Security middleware (CORS, Helmet, Rate Limiting)
app.use(app.cors({ origin: ['https://example.com'] }));
app.use(app.helmet({ xssFilter: true }));
app.use(app.rateLimiter({ max: 100, windowMs: 15 * 60 * 1000 }));

// Smart body parser with auto-detection
app.use(app.smartBodyParser({ maxSize: 10 * 1024 * 1024 }));

// Advanced validation & sanitization
const userData = validateRequest(ctx, userSchema);
const cleanData = sanitizeInput(userData);

// Custom error classes with contextual information
throw new NotFoundError('User not found', {
  userId: ctx.params.id,
  suggestion: 'Verify the user ID is correct',
});

// Event-driven architecture (Simple + CQRS patterns)
await app.events.emit('user.registered', { userId: user.id });
await app.eventSystem.dispatch({ type: 'CreateUser', data: {...} });

// Template engine with automatic XSS protection
await ctx.render('profile.html', { user, isAdmin });

// WebSocket support with room management
wsApp.ws('/chat', socket => {
  socket.join('room1');
  socket.onMessage(data => wsApp.wsBroadcast(data, 'room1'));
});

// Structured logging with multiple transports
ctx.logger.info('User action', { userId, action });

// Dependency injection container
const service = container.resolve('UserService');

πŸ›‘οΈ Type Safety First

// Full TypeScript integration with IntelliSense support
import type { Context, Middleware, RouteHandler } from 'nextrush';

app.get('/users/:id', async (ctx: Context) => {
  const userId: string = ctx.params.id; // Type-safe route parameters
  const userData: User = ctx.body; // Type-safe request body
  ctx.json({ user: userData }); // Type-safe response
});

// Type-safe middleware composition
const authMiddleware: Middleware = async (ctx, next) => {
  ctx.state.user = await validateToken(ctx.headers.authorization);
  await next();
};

🎭 Choose Your API Style

// Convenience Methods (Recommended)
app.get('/users', async ctx => {
  ctx.json(await getUsers()); // Clean and concise
});

// Enhanced API (Express-inspired helpers)
app.get('/users', async ctx => {
  ctx.res.json(await getUsers()); // Familiar Express-like methods
});

// Configuration API (Fastify-style)
app.get('/users', {
  handler: async ctx => ctx.json(await getUsers()),
  schema: { response: { 200: UserSchema } },
  options: { tags: ['users'] },
});

🌟 Core Features Comparison

| Feature | NextRush v2 | Express | Fastify | Koa | | ----------------------------- | --------------- | --------------- | --------------- | ----------------- | | Security Middleware | Built-in | Plugin required | Plugin required | Plugin required | | Validation & Sanitization | Built-in | Plugin required | Built-in | Plugin required | | Template Engine | Built-in | Plugin required | Plugin required | Plugin required | | WebSocket Support | Built-in | Plugin required | Plugin required | Plugin required | | Event System (CQRS) | Dual system | Plugin required | Plugin required | Plugin required | | Advanced Logging | Plugin included | Plugin required | Plugin required | Plugin required | | Error Classes | 8 custom types | Basic | Basic | Basic | | Dependency Injection | Built-in | Plugin required | Plugin required | Plugin required | | Smart Body Parser | Auto-detection | Plugin required | Built-in | Plugin required | | Static File Serving | Plugin included | Built-in | Plugin required | Plugin required | | TypeScript Support | First-class | Community | First-class | Community | | Dependencies | 0 ⭐ | 34+ packages | 20+ packages | 0 (needs plugins) | | Performance (RPS) | ~13,261 | ~11,030 | ~22,717 | ~17,547 |


✨ Comprehensive Feature Set

Modern Development

  • TypeScript First - Full type safety with IntelliSense
  • Zero Dependencies - Pure Node.js, minimal footprint
  • ESM & CJS - Universal module compatibility
  • Plugin System - Extensible architecture
  • Smart Body Parser - Auto-detection & zero-copy operations
  • Template Engine - Built-in HTML rendering with auto-escaping

Production Ready

  • Error Handling - Custom error classes with context
  • Advanced Logging - Structured logs with multiple transports
  • Security - CORS, Helmet, Rate Limiting included
  • Validation - Schema validation & input sanitization
  • Testing - Test-friendly design, 1461 passing tests
  • Static Files - High-performance file serving
  • Compression - Gzip & Brotli support

Real-time & Events

  • WebSocket Support - RFC 6455 compliant implementation
  • Room Management - Built-in room system for grouping
  • Broadcasting - Efficient message delivery patterns
  • Event System - Simple events + CQRS/Event Sourcing
  • Connection Pooling - Scalable connection management
  • Heartbeat - Automatic connection health monitoring
  • Pub/Sub - Event-driven architecture support

Developer Experience

  • Enhanced Errors - Contextual debugging information
  • Request/Response Enhancers - Express-inspired helpers
  • Path Utilities - URL & path manipulation tools
  • Cookie Utilities - Type-safe cookie management
  • Dependency Injection - Built-in DI container
  • Dev Warnings - Common mistake detection
  • Performance Monitoring - Built-in metrics collection

πŸš€ Quick Start

Prerequisites

  • Node.js: >= 20.0.0
  • pnpm: >= 10.0.0 (recommended) or npm/yarn/bun

Installation

# pnpm (recommended)
pnpm add nextrush

# npm
npm install nextrush

# yarn
yarn add nextrush

# bun
bun add nextrush

Hello World

import { createApp } from 'nextrush';

const app = createApp();

app.get('/', async ctx => {
  ctx.json({
    message: 'Hello NextRush v2! πŸš€',
    timestamp: new Date().toISOString(),
  });
});

app.listen(3000, () => {
  console.log('πŸš€ Server running on http://localhost:3000');
});

30-Second API

import { createApp } from 'nextrush';

const app = createApp({
  cors: true, // Enable CORS
  debug: true, // Development mode
});

// Middleware
app.use(async (ctx, next) => {
  console.log(`πŸ“ ${ctx.method} ${ctx.path}`);
  await next();
});

// Routes with three different styles
app.get('/simple', async ctx => {
  ctx.json({ style: 'convenience' });
});

app.get('/express', async ctx => {
  ctx.res.json({ style: 'express-like' });
});

app.post('/fastify', {
  handler: async ctx => ctx.json({ style: 'fastify-style' }),
  schema: {
    body: {
      type: 'object',
      properties: { name: { type: 'string' } },
    },
  },
});

app.listen(3000);

🎭 Multiple API Styles

NextRush v2 is Koa-style at its core with three distinct API stylesβ€”choose the approach that best fits your team's preferences:

Convenience Methods (Recommended)

app.get('/users/:id', async ctx => {
  const user = await findUser(ctx.params.id);

  if (!user) {
    ctx.json({ error: 'User not found' }, 404);
    return;
  }

  ctx.json(user); // Clean and concise
});

app.post('/users', async ctx => {
  const user = await createUser(ctx.body);
  ctx.json(user, 201); // Status code as second parameter
});

Enhanced API (Express-inspired)

app.get('/users/:id', async ctx => {
  const user = await findUser(ctx.params.id);

  if (!user) {
    ctx.res.status(404).json({ error: 'User not found' });
    return;
  }

  ctx.res.json(user); // Familiar Express-style methods
});

app.post('/users', async ctx => {
  const user = await createUser(ctx.body);
  ctx.res.status(201).json(user); // Chainable method calls
});

Configuration API (Fastify-style)

app.get('/users/:id', {
  handler: async ctx => {
    const user = await findUser(ctx.params.id);
    ctx.json(user || { error: 'Not found' }, user ? 200 : 404);
  },
  schema: {
    params: {
      type: 'object',
      properties: { id: { type: 'string', pattern: '^[0-9]+$' } },
    },
    response: {
      200: { type: 'object', properties: { id: { type: 'string' } } },
      404: { type: 'object', properties: { error: { type: 'string' } } },
    },
  },
  options: {
    name: 'getUser',
    description: 'Retrieve user by ID',
    tags: ['users'],
  },
});

🌐 Real-time WebSocket Support

Production-ready WebSocket server with zero dependencies and full TypeScript support:

import { createApp, WebSocketPlugin, withWebSocket } from 'nextrush';
import type { WSConnection } from 'nextrush';

const app = createApp();

// Install WebSocket plugin
const wsPlugin = new WebSocketPlugin({
  path: '/ws',
  heartbeatMs: 30000,
  maxConnections: 1000,
  verifyClient: async req => {
    // Optional: Custom authentication
    const token = new URL(req.url || '', 'http://localhost').searchParams.get(
      'token'
    );
    return !!token;
  },
});
wsPlugin.install(app);

// βœ… Get typed WebSocket application (Perfect IntelliSense!)
const wsApp = withWebSocket(app);

// Simple echo server with full type safety
wsApp.ws('/echo', (socket: WSConnection) => {
  socket.send('Welcome!');

  socket.onMessage((data: string | Buffer) => {
    socket.send(`Echo: ${data}`);
  });
});

// Room-based chat system
wsApp.ws('/chat', (socket: WSConnection) => {
  const room = 'general';

  socket.join(room);
  socket.send(`Joined room: ${room}`);

  socket.onMessage((data: string | Buffer) => {
    // Broadcast to all users in room using app-level method
    wsApp.wsBroadcast(data.toString(), room);
  });

  socket.onClose((code, reason) => {
    console.log(`Client disconnected: ${code} - ${reason}`);
  });
});

app.listen(3000);

Client Usage:

// Browser WebSocket client
const ws = new WebSocket('ws://localhost:3000/chat');
ws.onopen = () => {
  console.log('Connected!');
  ws.send('Hello everyone!');
};
ws.onmessage = event => console.log('Received:', event.data);
ws.onerror = error => console.error('Error:', error);
ws.onclose = () => console.log('Disconnected');

// With authentication token
const wsAuth = new WebSocket('ws://localhost:3000/echo?token=your-jwt-token');

πŸ›‘οΈ Built-in Security Middleware

import { createApp } from 'nextrush';

const app = createApp();

// CORS - Cross-Origin Resource Sharing
app.use(
  app.cors({
    origin: ['https://example.com'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
  })
);

// Helmet - Security headers
app.use(
  app.helmet({
    contentSecurityPolicy: true,
    xssFilter: true,
    noSniff: true,
    frameguard: { action: 'deny' },
  })
);

// Rate Limiting - DDoS protection
app.use(
  app.rateLimiter({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // 100 requests per window
    message: 'Too many requests',
  })
);

// Request ID - Request tracing
app.use(app.requestId());

// Response Timer - Performance monitoring
app.use(app.timer());

Included Security Features:

  • CORS - Flexible origin control and credential handling
  • Helmet - 15+ security headers preconfigured
  • Rate Limiting - IP-based request throttling
  • XSS Protection - Automatic escaping in template engine
  • Request Tracing - Unique identifiers for request tracking
  • Response Timing - Performance measurement headers

πŸ“ Comprehensive Validation System

πŸ“ Comprehensive Validation System

import { validateRequest, sanitizeInput, ValidationError } from 'nextrush';

// Define validation schema
const userSchema = {
  name: {
    required: true,
    type: 'string',
    minLength: 2,
    maxLength: 50,
  },
  email: {
    required: true,
    type: 'email',
  },
  age: {
    type: 'number',
    min: 18,
    max: 120,
  },
  role: {
    enum: ['user', 'admin', 'moderator'],
  },
};

app.post('/users', async ctx => {
  try {
    // Validate request against schema
    const userData = validateRequest(ctx, userSchema);

    // Sanitize user input
    const cleanData = sanitizeInput(userData);

    const user = await createUser(cleanData);
    ctx.json({ user }, 201);
  } catch (error) {
    if (error instanceof ValidationError) {
      ctx.json(
        {
          error: 'Validation failed',
          details: error.errors,
        },
        400
      );
    }
  }
});

Validation Capabilities:

  • Type Checking - string, number, boolean, email, URL, and more
  • Length Validation - minLength, maxLength constraints
  • Range Validation - min, max for numeric values
  • Pattern Matching - Regular expression validation
  • Enum Validation - Restricted value sets
  • Custom Validation - Extensible validation functions
  • XSS Prevention - Automatic input sanitization

πŸ“š Complete Validation Guide β†’

Validation Features:

  • Type Checking - string, number, boolean, email, URL, etc.
  • Length Validation - minLength, maxLength
  • Range Validation - min, max for numbers
  • Pattern Matching - Regex validation
  • Enum Validation - Allowed values
  • Custom Validation - Your own validation functions
  • XSS Prevention - Auto-sanitization

πŸ“š Complete Validation Guide β†’


🎨 Template Engine

import { createApp, TemplatePlugin } from 'nextrush';

const app = createApp();

// Setup template engine
const templatePlugin = new TemplatePlugin({
  viewsDir: './views',
  cache: true,
  helpers: {
    formatDate: date => new Date(date).toLocaleDateString(),
    currency: value => `$${Number(value).toFixed(2)}`,
  },
});

templatePlugin.install(app);

// Use templates
app.get('/users/:id', async ctx => {
  const user = await getUser(ctx.params.id);

  await ctx.render('user-profile.html', {
    title: 'User Profile',
    user,
    isAdmin: user.role === 'admin',
  });
});

views/user-profile.html:

<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
  </head>
  <body>
    <h1>{{user.name}}</h1>
    <p>Email: {{user.email}}</p>
    <p>Joined: {{user.createdAt | formatDate}}</p>

    {{#if isAdmin}}
    <button>Admin Panel</button>
    {{/if}}

    <!-- Loop through items -->
    {{#each user.posts}}
    <article>
      <h2>{{this.title}}</h2>
      <p>{{this.excerpt}}</p>
    </article>
    {{/each}}
  </body>
</html>

Template Features:

  • Auto-escaping - XSS protection by default
  • Control Structures - if/else, loops, with blocks
  • Helpers - Built-in & custom transformation functions
  • Partials - Reusable template components
  • Layouts - Consistent page structure
  • Caching - Fast production performance

πŸ“š Template Engine Documentation β†’


🚨 Advanced Error Handling

import {
  HttpError,
  BadRequestError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError,
  ConflictError,
  UnprocessableEntityError,
  TooManyRequestsError,
  InternalServerError,
} from 'nextrush';

// Custom error classes with proper status codes
app.get('/users/:id', async ctx => {
  const user = await db.user.findById(ctx.params.id);

  if (!user) {
    throw new NotFoundError('User not found', {
      userId: ctx.params.id,
      suggestion: 'Check the user ID',
    });
  }

  if (ctx.state.user.id !== user.id) {
    throw new ForbiddenError("Cannot access other user's data", {
      requestedUserId: ctx.params.id,
      currentUserId: ctx.state.user.id,
    });
  }

  ctx.json({ user });
});

// Global error handler
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (error) {
    if (error instanceof HttpError) {
      ctx.json(
        {
          error: error.message,
          code: error.code,
          details: error.details,
        },
        error.statusCode
      );
      return;
    }

    // Unexpected errors
    ctx.json({ error: 'Internal server error' }, 500);
  }
});

Error Classes:

  • BadRequestError (400) - Invalid request data
  • UnauthorizedError (401) - Authentication required
  • ForbiddenError (403) - Insufficient permissions
  • NotFoundError (404) - Resource not found
  • ConflictError (409) - Resource conflicts
  • UnprocessableEntityError (422) - Business rule violations
  • TooManyRequestsError (429) - Rate limit exceeded
  • InternalServerError (500) - Server errors

πŸ“š Complete Error Handling Guide β†’


πŸŽͺ Event-Driven Architecture

NextRush v2 includes dual event systems: Simple Events (Express-style) + Advanced Event System (CQRS/Event Sourcing).

Simple Events API (Express-style)

// Emit events
await app.events.emit('user.registered', {
  userId: user.id,
  email: user.email,
});

// Listen to events
app.events.on('user.registered', async data => {
  await sendWelcomeEmail(data.email);
  await createDefaultProfile(data.userId);
  await trackAnalytics('User Registered', data);
});

// One-time handlers
app.events.once('app.ready', async () => {
  await warmupCache();
  await initializeServices();
});

Advanced Event System (CQRS/Event Sourcing)

// Define commands
interface CreateUserCommand {
  type: 'CreateUser';
  data: { name: string; email: string };
  metadata: { id: string; timestamp: Date; correlationId: string };
}

// Register command handlers
app.eventSystem.registerCommandHandler(
  'CreateUser',
  async (command: CreateUserCommand) => {
    const user = await db.user.create(command.data);

    // Emit domain event
    await app.eventSystem.emit({
      type: 'user.created',
      data: { userId: user.id, email: user.email },
      timestamp: new Date(),
      metadata: {
        aggregateId: user.id,
        version: 1,
      },
    });

    return user;
  }
);

// Subscribe to domain events
app.eventSystem.subscribe('user.created', async event => {
  await analytics.track('User Created', {
    userId: event.data.userId,
    correlationId: event.metadata.correlationId,
  });
});

// Execute commands with CQRS
app.post('/users', async ctx => {
  const command: CreateUserCommand = {
    type: 'CreateUser',
    data: ctx.body,
    metadata: {
      id: crypto.randomUUID(),
      timestamp: new Date(),
      correlationId: ctx.id,
    },
  };

  const user = await app.eventSystem.dispatch(command);
  ctx.json({ user }, 201);
});

Event System Features:

  • Simple Events - Express-style emit/on/once patterns
  • CQRS - Command Query Responsibility Segregation
  • Event Sourcing - Domain event tracking and replay
  • Saga Patterns - Complex workflow orchestration
  • Pub/Sub - Event broadcasting capabilities
  • Correlation IDs - Request tracing across services
  • Event Store - Event history and replay functionality

πŸ“š Complete Event System Guide β†’


πŸ“Š Advanced Logging Plugin

import { LoggerPlugin } from 'nextrush';

// Configure advanced logging
const loggerPlugin = new LoggerPlugin({
  level: 'info',
  format: 'json',
  transports: [
    {
      type: 'console',
      colorize: true,
    },
    {
      type: 'file',
      filename: 'logs/app.log',
      maxSize: 10485760, // 10MB
      maxFiles: 5,
    },
    {
      type: 'file',
      filename: 'logs/errors.log',
      level: 'error',
      maxSize: 10485760,
    },
  ],
  includeTimestamp: true,
  includeMetadata: true,
});

loggerPlugin.install(app);

// Use in routes
app.get('/api/data', async ctx => {
  ctx.logger.info('Fetching data', {
    userId: ctx.state.user?.id,
    endpoint: '/api/data',
  });

  try {
    const data = await fetchData();
    ctx.logger.debug('Data fetched successfully', { count: data.length });
    ctx.json({ data });
  } catch (error) {
    ctx.logger.error('Failed to fetch data', {
      error: error.message,
      stack: error.stack,
    });
    throw error;
  }
});

Logger Features:

  • Multiple Transports - Console, file, and custom transports
  • Log Levels - debug, info, warn, error, fatal
  • Structured Logging - JSON format with metadata
  • File Rotation - Size-based and time-based rotation
  • Colorized Output - Enhanced development experience
  • Performance Metrics - Request timing and throughput tracking
  • Custom Formatters - Extensible log formatting

πŸ“š Logger Plugin Documentation β†’


πŸ—οΈ Advanced Features

Modular Router System

import { createApp, createRouter } from 'nextrush';

const app = createApp();

// Create sub-routers
const userRouter = createRouter();
const adminRouter = createRouter();

// User routes
userRouter.get('/profile', async ctx => ctx.json({ user: 'profile' }));
userRouter.post('/login', async ctx => ctx.json({ message: 'Logged in' }));

// Admin routes
adminRouter.get('/dashboard', async ctx => ctx.json({ admin: 'dashboard' }));
adminRouter.get('/users', async ctx => ctx.json({ admin: 'users list' }));

// Mount routers
app.use('/users', userRouter);
app.use('/admin', adminRouter);

Custom Middleware Development

import type { Middleware, Context } from 'nextrush';

// Simple middleware
const logger: Middleware = async (ctx, next) => {
  const start = Date.now();
  console.log(`πŸ”„ ${ctx.method} ${ctx.path}`);

  await next();

  const duration = Date.now() - start;
  console.log(`βœ… ${ctx.status} ${duration}ms`);
};

// Authentication middleware with proper error handling
const requireAuth: Middleware = async (ctx, next) => {
  const token = ctx.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    throw new UnauthorizedError('Authentication token required', {
      hint: 'Include Authorization: Bearer <token> header',
    });
  }

  try {
    ctx.state.user = await validateToken(token);
    await next();
  } catch (error) {
    throw new UnauthorizedError('Invalid authentication token', {
      reason: error.message,
    });
  }
};

// Role-based authorization
const requireRole = (role: string): Middleware => {
  return async (ctx, next) => {
    if (!ctx.state.user) {
      throw new UnauthorizedError('Authentication required');
    }

    if (!ctx.state.user.roles.includes(role)) {
      throw new ForbiddenError(`${role} role required`, {
        userRoles: ctx.state.user.roles,
        requiredRole: role,
      });
    }

    await next();
  };
};

// Rate limiting middleware
const rateLimiter: Middleware = async (ctx, next) => {
  const key = ctx.ip;
  const limit = 100;
  const windowMs = 15 * 60 * 1000;

  const requests = await getRequestCount(key, windowMs);

  if (requests >= limit) {
    throw new TooManyRequestsError('Rate limit exceeded', {
      limit,
      retryAfter: Math.ceil(windowMs / 1000),
    });
  }

  await incrementRequestCount(key, windowMs);
  await next();
};

// Use middleware
app.use(logger);
app.use('/api', requireAuth);
app.use('/admin', requireRole('admin'));

πŸ“š Middleware Development Guide β†’

Enhanced Response Methods

// JSON response with status code
app.get('/api/users', async ctx => {
  const users = await getUsers();
  ctx.json({ users }, 200);
});

// HTML response
app.get('/page', async ctx => {
  ctx.html('<h1>Welcome to NextRush</h1>');
});

// File download with options
app.get('/download', async ctx => {
  ctx.file('./document.pdf', {
    filename: 'report.pdf',
    contentType: 'application/pdf',
  });
});

// Redirect with status code
app.get('/old-url', async ctx => {
  ctx.redirect('/new-url', 301); // Permanent redirect
});

// CSV export
app.get('/export/users', async ctx => {
  const users = await getUsers();
  const csv = users.map(u => `${u.name},${u.email}`).join('\n');
  ctx.csv(`name,email\n${csv}`, 'users.csv');
});

// Stream response
app.get('/stream', async ctx => {
  const stream = fs.createReadStream('./large-file.txt');
  ctx.stream(stream, 'text/plain');
});

// Set custom headers
app.get('/api/data', async ctx => {
  ctx.set('X-Custom-Header', 'value');
  ctx.set('Cache-Control', 'max-age=3600');
  ctx.json({ data: [] });
});

// Cookie management
app.get('/set-cookie', async ctx => {
  ctx.setCookie('session', 'abc123', {
    httpOnly: true,
    secure: true,
    maxAge: 3600000,
    sameSite: 'strict',
  });
  ctx.json({ message: 'Cookie set' });
});

app.get('/get-cookie', async ctx => {
  const session = ctx.getCookie('session');
  ctx.json({ session });
});

πŸ“š Enhanced Request/Response API β†’

πŸ“– Complete API Reference

Context Object

// ===================== Request Properties =====================
ctx.req        // Native HTTP request object
ctx.res        // Enhanced response object
ctx.body       // Parsed request body (JSON, form, etc.)
ctx.method     // HTTP method (GET, POST, PUT, DELETE, etc.)
ctx.path       // Request path (/users/123)
ctx.url        // Full request URL
ctx.query      // Query parameters (?page=1 β†’ { page: '1' })
ctx.headers    // Request headers (lowercase keys)
ctx.params     // Route parameters (/users/:id β†’ { id: '123' })
ctx.cookies    // Parsed cookies
ctx.ip         // Client IP address
ctx.secure     // Is HTTPS?
ctx.protocol   // Request protocol (http/https)
ctx.hostname   // Request hostname
ctx.origin     // Request origin (protocol + host)
ctx.state      // Custom request-scoped state

// ===================== Response Methods =====================
// Convenience API (Recommended)
ctx.json(data, status?)           // Send JSON response
ctx.html(html, status?)            // Send HTML response
ctx.text(text, status?)            // Send plain text
ctx.csv(data, filename?)           // Send CSV file
ctx.file(path, options?)           // Send file download
ctx.stream(stream, contentType?)   // Send stream response
ctx.redirect(url, status?)         // Redirect to URL

// Express-like API (Enhanced)
ctx.res.json(data, status?)        // Send JSON
ctx.res.status(code)               // Set status code (chainable)
ctx.res.send(data)                 // Auto-detect content type
ctx.res.sendFile(path)             // Send file
ctx.res.render(template, data)     // Render template

// ===================== Header & Cookie Methods =====================
ctx.get(headerName)                // Get request header
ctx.set(headerName, value)         // Set response header
ctx.setCookie(name, value, opts)   // Set cookie
ctx.getCookie(name)                // Get cookie value
ctx.clearCookie(name)              // Delete cookie

// ===================== Utility Properties =====================
ctx.id                             // Unique request ID
ctx.logger                         // Request-scoped logger
ctx.services                       // DI container services
ctx.app                            // Application instance

Application Methods

// ===================== HTTP Methods =====================
app.get(path, ...handlers)         // GET route
app.post(path, ...handlers)        // POST route
app.put(path, ...handlers)         // PUT route
app.delete(path, ...handlers)      // DELETE route
app.patch(path, ...handlers)       // PATCH route
app.head(path, ...handlers)        // HEAD route
app.options(path, ...handlers)     // OPTIONS route
app.all(path, ...handlers)         // All HTTP methods

// ===================== Middleware =====================
app.use(...middleware)             // Global middleware
app.use(path, ...middleware)       // Path-specific middleware

// ===================== Built-in Middleware =====================
app.cors(options)                  // CORS middleware
app.helmet(options)                // Security headers
app.rateLimiter(options)           // Rate limiting
app.compression(options)           // Gzip/Brotli compression
app.requestId(options)             // Request ID tracking
app.timer()                        // Response time header
app.smartBodyParser(options)       // Auto body parsing

// ===================== Event System =====================
app.events.emit(event, data)       // Emit simple event
app.events.on(event, handler)      // Listen to event
app.events.once(event, handler)    // One-time listener
app.events.off(event, handler?)    // Remove listener

app.eventSystem.dispatch(op)       // CQRS dispatch
app.eventSystem.executeCommand(c)  // Execute command
app.eventSystem.executeQuery(q)    // Execute query
app.eventSystem.subscribe(e, h)    // Subscribe to domain event

// ===================== Server Control =====================
app.listen(port, callback?)        // Start HTTP server
app.close(callback?)               // Stop server gracefully

Router Methods

// Create router
const router = createRouter('/prefix');

// HTTP methods
router.get(path, handler);
router.post(path, handler);
router.put(path, handler);
router.delete(path, handler);
router.patch(path, handler);

// Middleware
router.use(middleware);

// Mount router
app.use('/api', router);

πŸ§ͺ Testing

import { createApp } from 'nextrush';

describe('NextRush Application', () => {
  it('should handle GET requests', async () => {
    const app = createApp();

    app.get('/test', async ctx => {
      ctx.json({ message: 'OK' });
    });

    // Your test implementation
  });
});

πŸ”₯ Enhanced Body Parser

Enterprise-grade body parsing with zero-copy operations:

// Auto-parsing (recommended)
app.use(app.smartBodyParser());

// Advanced configuration
app.use(
  app.smartBodyParser({
    maxSize: 10 * 1024 * 1024, // 10MB
    enableStreaming: true,
    autoDetectContentType: true,
    enableMetrics: true,
  })
);

// Supports JSON, form-data, text, multipart
app.post('/api/data', ctx => {
  const data = ctx.body; // Already parsed!
  ctx.json({ received: data });
});

Features: Zero-copy buffers β€’ Auto-detection β€’ Streaming β€’ Memory-pooled β€’ Cross-platform

πŸ“š Full Documentation β†’

πŸ“š Documentation

Comprehensive guides, API references, and architecture deep-dives:

Getting Started

Essential Guides

Core API Reference

Advanced Features

Plugin APIs

Architecture Deep-Dives

Performance & Benchmarks

  • Benchmarks - Performance comparisons with Express, Koa, and Fastify
  • Performance Guide - Optimization techniques and best practices
  • Memory Management - Efficient memory usage patterns

🀝 Contributing

Contributions are welcome! Please see our Contributing Guide for details on how to get started.

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ™ Acknowledgments

  • Express.js - Intuitive API design patterns
  • Koa - Powerful async middleware architecture
  • Fastify - Object-based route configuration approach
  • TypeScript - Type safety and enhanced developer experience

Built with precision by Tanzim Hossain

Report Bug β€’ Request Feature β€’ Discussions