secure-backend

🛡️ Secure Backend

npm version CI Status Coverage Status Security Rating License: MIT

Production-grade security + performance toolkit for backend frameworks with OWASP Top 10 compliance

Secure Backend is a comprehensive middleware solution that provides enterprise-level security and performance optimizations for Express, Koa, Fastify, and NestJS applications. Get OWASP Top 10 protection, performance monitoring, and developer-friendly configuration in minutes, not hours.

🚀 Quick Start

npm install secure-backend
import express from 'express';
import { ExpressAdapter, secureBackend } from 'secure-backend';

const app = express();

// One-line security + performance setup
const secureAdapter = new ExpressAdapter(secureBackend('api'));
secureAdapter.applyMiddleware(app);

app.listen(3000);

That's it! Your app now has:

  • ✅ CSRF protection
  • ✅ CORS configuration
  • ✅ Security headers (Helmet)
  • ✅ Rate limiting
  • ✅ Input sanitization
  • ✅ Compression & caching
  • ✅ Performance monitoring

🎯 Problem It Solves

Building secure, performant backend APIs requires implementing dozens of security measures and performance optimizations. Most developers either:

  1. Skip security → vulnerable to OWASP Top 10 attacks
  2. Implement piecemeal → inconsistent, hard to maintain
  3. Over-engineer → complex configuration, performance issues

Secure Backend gives you enterprise-grade security + performance with zero configuration complexity.

📦 Installation

# npm
npm install secure-backend

# yarn
yarn add secure-backend

# pnpm
pnpm add secure-backend

Framework-specific installations:

# Express.js
npm install secure-backend express

# Koa.js
npm install secure-backend koa

# Fastify
npm install secure-backend fastify

# NestJS
npm install secure-backend @nestjs/common @nestjs/core

🔧 Configuration Presets

API Preset (Recommended for REST APIs)

import { secureBackend } from 'secure-backend';

const config = secureBackend('api');
// Optimized for: REST APIs, microservices, mobile backends
// Features: Strong CSRF, strict CORS, API-focused headers

Web App Preset (For SSR Applications)

const config = secureBackend('webapp');
// Optimized for: Server-rendered web apps, full-stack apps
// Features: Relaxed CORS, web-friendly CSP, session support

Strict Preset (Maximum Security)

const config = secureBackend('strict');
// Optimized for: Financial, healthcare, high-security apps
// Features: Maximum security headers, strict rate limits, enhanced monitoring

🎨 Framework Usage Examples

Express.js

import express from 'express';
import { ExpressAdapter, secureBackend } from 'secure-backend';

const app = express();
const secureAdapter = new ExpressAdapter(secureBackend('api'));

secureAdapter.applyMiddleware(app);

app.get('/api/users', (req, res) => {
res.json({ users: [] });
});

app.listen(3000);

Koa.js

import Koa from 'koa';
import { KoaAdapter, secureBackend } from 'secure-backend';

const app = new Koa();
const secureAdapter = new KoaAdapter(secureBackend('webapp'));

secureAdapter.applyMiddleware(app);

app.use(async ctx => {
ctx.body = { message: 'Secure Koa app!' };
});

app.listen(3000);

Fastify

import Fastify from 'fastify';
import { FastifyAdapter, secureBackend } from 'secure-backend';

const fastify = Fastify();
const secureAdapter = new FastifyAdapter(secureBackend('strict'));

await secureAdapter.applyMiddleware(fastify);

fastify.get('/api/health', async () => {
return { status: 'healthy' };
});

await fastify.listen({ port: 3000 });

NestJS

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SecureBackendMiddleware, secureBackend } from 'secure-backend';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.use(new SecureBackendMiddleware(secureBackend('api')));

await app.listen(3000);
}
bootstrap();

⚙️ Advanced Configuration

Custom Configuration with TypeScript

import { secureBackend, SecureBackendConfig } from 'secure-backend';

const config: SecureBackendConfig = secureBackend({
preset: 'api',
security: {
cors: {
origin: ['https://myapp.com', 'https://admin.myapp.com'],
credentials: true,
},
csrf: {
enabled: true,
tokenLength: 32,
cookieName: 'csrf-token',
},
rateLimit: {
enabled: true,
max: 1000,
windowMs: 15 * 60 * 1000, // 15 minutes
},
headers: {
csp: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
},
},
sanitization: {
enabled: true,
xss: true,
sqlInjection: true,
},
auth: {
jwt: {
secret: process.env.JWT_SECRET,
algorithms: ['HS256'],
maxAge: 3600,
},
},
},
performance: {
compression: {
enabled: true,
threshold: 1024,
level: 6,
},
caching: {
enabled: true,
maxAge: 300,
etag: true,
},
monitoring: {
enabled: true,
logSlowRequests: true,
slowRequestThreshold: 1000,
},
},
logging: {
enabled: true,
level: 'info',
suspiciousRequests: true,
rateLimitViolations: true,
},
});

🛡️ Security Features

OWASP Top 10 Protection

  • A01 - Broken Access Control: JWT validation, RBAC support
  • A02 - Cryptographic Failures: Secure headers, HSTS enforcement
  • A03 - Injection: Input sanitization, XSS protection, SQL injection prevention
  • A04 - Insecure Design: Secure defaults, configuration validation
  • A05 - Security Misconfiguration: Helmet integration, CSP headers
  • A06 - Vulnerable Components: Dependency scanning, security audits
  • A07 - Identity & Auth Failures: Rate limiting, session management
  • A08 - Software Integrity: Package integrity, secure updates
  • A09 - Logging Failures: Security event logging, monitoring
  • A10 - Server-Side Request Forgery: Request validation, URL filtering

Security Headers (Helmet Integration)

// Automatically applied based on preset
{
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
dnsPrefetchControl: true,
frameguard: true,
hidePoweredBy: true,
hsts: true,
ieNoOpen: true,
noSniff: true,
originAgentCluster: true,
permittedCrossDomainPolicies: true,
referrerPolicy: true,
xssFilter: true,
}

⚡ Performance Features

Compression & Caching

  • Gzip/Brotli compression with configurable thresholds
  • HTTP caching with ETag and Last-Modified support
  • In-memory LRU cache for frequently accessed data
  • Response compression for JSON and static assets

Monitoring & Metrics

  • Request/response timing tracking
  • Memory usage monitoring
  • Slow query detection with configurable thresholds
  • Performance metrics endpoint (/performance-metrics)
// Access performance data
app.get('/metrics', (req, res) => {
const metrics = secureAdapter.getPerformanceMetrics();
res.json(metrics);
});

🔧 CLI Tool

Generate secure configuration templates:

# Initialize with recommended defaults
npx secure-backend init

# Choose preset
npx secure-backend init --preset=api
npx secure-backend init --preset=webapp
npx secure-backend init --preset=strict

# Generate for specific framework
npx secure-backend init --framework=express
npx secure-backend init --framework=koa
npx secure-backend init --framework=fastify

📊 Configuration Endpoints

Secure Backend automatically adds helpful development endpoints:

  • GET /performance-metrics - Performance and timing data
  • GET /security-events - Security violation logs
  • GET /config-summary - Current configuration overview
  • GET /csrf-token - CSRF token for frontend apps

Note: These endpoints are automatically disabled in production.

🚨 Security Guarantees & Limitations

✅ What Secure Backend Provides

  • OWASP Top 10 protection with industry-standard practices
  • Zero-config security with secure defaults for all frameworks
  • Performance optimization without compromising security
  • Type-safe configuration with full TypeScript support
  • Production-tested middleware used in enterprise applications

⚠️ What You Still Need

  • Authentication logic - Secure Backend provides JWT validation, you provide login/signup
  • Authorization rules - RBAC and permission checking are application-specific
  • Database security - Use parameterized queries, ORM best practices
  • Infrastructure security - HTTPS, firewalls, network security
  • Business logic validation - Domain-specific input validation and business rules

🛠️ Development

# Clone repository
git clone https://github.com/secure-backend/secure-backend.git
cd secure-backend

# Install dependencies
npm install

# Run tests
npm test

# Build package
npm run build

# Run examples
npm run example:express
npm run example:koa
npm run example:fastify

📈 Roadmap

v0.2.0 - Extended Framework Support

  • Hapi.js adapter
  • AdonisJS adapter
  • Express 5.x support
  • GraphQL security middleware

v0.3.0 - Advanced Monitoring

  • Prometheus metrics integration
  • OpenTelemetry tracing
  • Custom alerting rules
  • Performance regression detection

v1.0.0 - Production Stability

  • 100% test coverage
  • Performance benchmarks
  • Security audit compliance
  • Long-term support (LTS)

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Areas We Need Help

  • Additional framework adapters
  • Security test cases
  • Performance optimizations
  • Documentation improvements
  • Example applications

📄 License

MIT License - see LICENSE file for details.

🆘 Support


Made with ❤️ by the Secure Backend team

Secure Backend is trusted by companies building production applications. Join thousands of developers who've chosen security by default.