BackForge is an enterprise-grade backend scaffolder that generates production-ready, scalable backend applications with advanced security, monitoring, and DevOps features built-in.
BackForge eliminates the 2-3 week setup time for production backends by providing:
- Helmet.js - 15+ security headers (CSP, HSTS, X-Frame-Options)
- CORS - Configurable origin whitelisting with credentials support
- Rate Limiting - Distributed rate limiting with Redis support
- HPP - HTTP parameter pollution prevention
- Request Validation - Joi/Zod schema validation out of the box
- SQL Injection Protection - Parameterized queries and ORM safeguards
- XSS Protection - Input sanitization and output encoding
- CSRF Tokens - Cross-site request forgery prevention
- Dependency Scanning - Automated vulnerability detection with npm audit
- Winston Logger - Structured JSON logging with daily rotation
- Morgan HTTP Logging - Request/response logging with custom formats
- OpenTelemetry - Distributed tracing support
- Prometheus Metrics - Custom metrics endpoint (
/metrics) - Health Checks - Liveness (
/health) and readiness (/ready) probes - APM Integration - DataDog, New Relic, AppDynamics ready
- Error Tracking - Sentry integration with source maps
- Auto-Detection - Runtime (Node.js/Bun), package manager (npm/pnpm/yarn/bun)
- Layered Architecture - Controllers โ Services โ Repositories pattern
- Dependency Injection - Testable, maintainable code structure
- Event-Driven - Built-in event emitter for async operations
- SOLID Principles - Clean code architecture from day one
- Response Compression - gzip/brotli with configurable levels
- Database Connection Pooling - Optimized connection management
- Caching Layer - Redis/in-memory cache with TTL support
- Query Optimization - Indexed fields and eager loading
- Cluster Mode - Multi-core CPU utilization
- Memory Management - Automatic garbage collection tuning
npm create backforge@latestInteractive prompts will ask:
- Project name
- Language (TypeScript/JavaScript)
- Framework (Express/Fastify)
- Database (MongoDB+Mongoose / SQL+Prisma)
- Additional features (Docker, Testing, CI/CD)
# Full TypeScript Express + MongoDB stack
npm create backforge@latest my-app -- --lang typescript --framework express --database mongoose
# JavaScript Fastify + PostgreSQL
npm create backforge@latest my-api -- --lang javascript --framework fastify --database prisma
# With all bells and whistles
npm create backforge@latest enterprise-api -- \
--lang typescript \
--framework fastify \
--database prisma \
--auth jwt \
--docker \
--testing \
--ci githubOptions:
-v, --version Output version number
-l, --lang <type> Language: typescript, javascript
-f, --framework <type> Framework: express, fastify
-d, --database <type> Database: mongoose, prisma
-a, --auth <type> Auth: jwt, oauth, passport (coming soon)
--docker Include Docker configuration
--testing Include Jest testing setup
--ci <provider> CI/CD: github, gitlab, circle
--no-install Skip dependency installation
--no-git Skip git initialization
-h, --help Display helpmy-backend/
โโโ src/
โ โโโ config/
โ โ โโโ database.ts # DB connection with pooling + retry
โ โ โโโ logger.ts # Winston with 5 transports
โ โ โโโ cache.ts # Redis cache manager
โ โ โโโ metrics.ts # Prometheus client
โ โ โโโ constants.ts # App-wide constants
โ โโโ controllers/
โ โ โโโ auth.controller.ts # JWT auth flows
โ โ โโโ user.controller.ts # CRUD operations
โ โ โโโ health.controller.ts # Health checks
โ โโโ services/
โ โ โโโ auth.service.ts # Business logic layer
โ โ โโโ user.service.ts
โ โ โโโ email.service.ts # Email templates
โ โ โโโ notification.service.ts
โ โโโ repositories/
โ โ โโโ user.repository.ts # Data access layer
โ โ โโโ base.repository.ts # Generic CRUD methods
โ โโโ models/
โ โ โโโ User.model.ts # Mongoose/Prisma schemas
โ โ โโโ Session.model.ts
โ โ โโโ AuditLog.model.ts
โ โโโ middlewares/
โ โ โโโ auth.middleware.ts # JWT verification
โ โ โโโ validate.middleware.ts # Request validation
โ โ โโโ error.middleware.ts # Centralized error handler
โ โ โโโ logger.middleware.ts # Request logging
โ โ โโโ rateLimit.middleware.ts
โ โโโ routes/
โ โ โโโ v1/
โ โ โ โโโ auth.routes.ts
โ โ โ โโโ user.routes.ts
โ โ โ โโโ index.ts # Route aggregator
โ โ โโโ index.ts
โ โโโ validators/
โ โ โโโ auth.validator.ts # Joi/Zod schemas
โ โ โโโ user.validator.ts
โ โโโ types/
โ โ โโโ express.d.ts # Extended Express types
โ โ โโโ environment.d.ts
โ โ โโโ custom.types.ts
โ โโโ utils/
โ โ โโโ apiResponse.ts # Standardized responses
โ โ โโโ apiError.ts # Custom error classes
โ โ โโโ catchAsync.ts # Async error wrapper
โ โ โโโ encryption.ts # bcrypt/argon2 helpers
โ โ โโโ jwt.ts # Token generation/verification
โ โ โโโ pagination.ts # Cursor-based pagination
โ โโโ events/
โ โ โโโ eventEmitter.ts # Event bus
โ โ โโโ listeners/
โ โ โโโ user.listener.ts
โ โ โโโ email.listener.ts
โ โโโ jobs/
โ โ โโโ emailQueue.ts # Bull/BullMQ queues
โ โ โโโ scheduledTasks.ts
โ โโโ app.ts # Express/Fastify app setup
โ โโโ server.ts # Server + graceful shutdown
โโโ tests/
โ โโโ unit/
โ โ โโโ services/
โ โ โโโ utils/
โ โโโ integration/
โ โ โโโ auth.test.ts
โ โ โโโ user.test.ts
โ โโโ e2e/
โ โ โโโ api.test.ts
โ โโโ fixtures/
โ โโโ setup.ts
โโโ logs/
โ โโโ app-2024-01-15.log
โ โโโ error-2024-01-15.log
โ โโโ exceptions.log
โโโ docker/
โ โโโ Dockerfile
โ โโโ Dockerfile.dev
โ โโโ docker-compose.yml
โโโ .github/
โ โโโ workflows/
โ โโโ ci.yml # Test + lint + build
โ โโโ cd.yml # Deploy to staging/prod
โ โโโ security.yml # Dependency scanning
โโโ scripts/
โ โโโ migrate.ts # Database migrations
โ โโโ seed.ts # Test data seeding
โ โโโ healthcheck.sh # Docker health check
โโโ .env # Environment variables
โโโ .env.example
โโโ .gitignore
โโโ .eslintrc.json
โโโ .prettierrc
โโโ jest.config.js
โโโ tsconfig.json
โโโ tsconfig.build.json
โโโ package.json
โโโ README.md
Every request is validated before reaching controllers:
// src/validators/user.validator.ts
import Joi from 'joi';
export const createUserSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/).required(),
name: Joi.string().min(2).max(50).required(),
});
// Usage in routes
router.post('/users', validate(createUserSchema), userController.create);// src/middlewares/rateLimit.middleware.ts
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { redis } from '../config/cache';
export const authLimiter = rateLimit({
store: new RedisStore({ client: redis }),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 requests per IP
message: 'Too many login attempts, please try again later',
standardHeaders: true,
legacyHeaders: false,
});
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
skipSuccessfulRequests: true, // Don't count successful requests
});// src/utils/jwt.ts
import jwt from 'jsonwebtoken';
export const generateToken = (payload: TokenPayload, expiresIn = '7d') => {
return jwt.sign(payload, process.env.JWT_SECRET!, {
expiresIn,
issuer: 'backforge-api',
audience: 'backforge-client',
});
};
export const verifyToken = (token: string) => {
return jwt.verify(token, process.env.JWT_SECRET!) as TokenPayload;
};
// src/middlewares/auth.middleware.ts
export const authenticate = catchAsync(async (req, res, next) => {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
throw new ApiError(401, 'Authentication required');
}
const decoded = verifyToken(token);
req.user = await userService.findById(decoded.userId);
if (!req.user) {
throw new ApiError(401, 'Invalid token');
}
next();
});// src/config/logger.ts
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: {
service: 'backforge-api',
environment: process.env.NODE_ENV,
version: process.env.npm_package_version,
},
transports: [
new DailyRotateFile({
filename: 'logs/error-%DATE%.log',
level: 'error',
maxFiles: '30d',
maxSize: '20m',
}),
new DailyRotateFile({
filename: 'logs/combined-%DATE%.log',
maxFiles: '30d',
maxSize: '20m',
}),
],
});
// Usage with context
logger.info('User created', {
userId: user.id,
email: user.email,
ipAddress: req.ip,
userAgent: req.get('user-agent'),
});// src/config/metrics.ts
import client from 'prom-client';
const register = new client.Registry();
// Default metrics (CPU, memory, etc.)
client.collectDefaultMetrics({ register });
// Custom metrics
export const httpRequestDuration = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.1, 0.5, 1, 2, 5],
});
export const activeUsers = new client.Gauge({
name: 'active_users_total',
help: 'Number of active users',
});
register.registerMetric(httpRequestDuration);
register.registerMetric(activeUsers);
// Metrics endpoint
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});// src/controllers/health.controller.ts
export const liveness = (req, res) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
};
export const readiness = async (req, res) => {
const checks = {
database: await checkDatabase(),
redis: await checkRedis(),
disk: await checkDiskSpace(),
};
const isReady = Object.values(checks).every(check => check.status === 'ok');
const statusCode = isReady ? 200 : 503;
res.status(statusCode).json({
status: isReady ? 'ready' : 'not_ready',
checks,
timestamp: new Date().toISOString(),
});
};# docker/Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:18-alpine AS runner
RUN apk add --no-cache tini
WORKDIR /app
COPY --from:builder /app/dist ./dist
COPY --from:builder /app/node_modules ./node_modules
COPY --from:builder /app/package.json ./
ENV NODE_ENV=production
EXPOSE 3000
USER node
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "dist/server.js"]
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node dist/healthcheck.js || exit 1# docker/docker-compose.yml
version: '3.8'
services:
api:
build:
context: ..
dockerfile: docker/Dockerfile.dev
ports:
- "3000:3000"
volumes:
- ../src:/app/src
- ../logs:/app/logs
environment:
- NODE_ENV=development
- MONGODB_URI=mongodb://mongo:27017/backforge
- REDIS_URL=redis://redis:6379
depends_on:
- mongo
- redis
mongo:
image: mongo:7
ports:
- "27017:27017"
volumes:
- mongo_data:/data/db
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
volumes:
mongo_data:
redis_data:// tests/integration/auth.test.ts
import request from 'supertest';
import app from '../../src/app';
import { connectDB, disconnectDB } from '../../src/config/database';
describe('Auth Endpoints', () => {
beforeAll(async () => {
await connectDB();
});
afterAll(async () => {
await disconnectDB();
});
describe('POST /api/v1/auth/register', () => {
it('should register a new user', async () => {
const response = await request(app)
.post('/api/v1/auth/register')
.send({
email: 'test@example.com',
password: 'Test1234!',
name: 'Test User',
})
.expect(201);
expect(response.body).toHaveProperty('token');
expect(response.body.user).toHaveProperty('id');
});
it('should return 400 for invalid email', async () => {
await request(app)
.post('/api/v1/auth/register')
.send({
email: 'invalid-email',
password: 'Test1234!',
name: 'Test User',
})
.expect(400);
});
});
});// src/models/User.model.ts (Mongoose)
const UserSchema = new Schema({
email: { type: String, required: true, unique: true, index: true },
username: { type: String, required: true, unique: true, index: true },
createdAt: { type: Date, default: Date.now, index: true },
});
// Compound index for common queries
UserSchema.index({ email: 1, status: 1 });// src/middlewares/cache.middleware.ts
import { redis } from '../config/cache';
export const cacheMiddleware = (duration: number = 300) => {
return async (req, res, next) => {
const key = `cache:${req.originalUrl}`;
const cached = await redis.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
const originalJson = res.json.bind(res);
res.json = (data) => {
redis.setex(key, duration, JSON.stringify(data));
return originalJson(data);
};
next();
};
};
// Usage
router.get('/users', cacheMiddleware(600), userController.getAll);// src/config/database.ts (Mongoose)
const options = {
maxPoolSize: 10,
minPoolSize: 5,
socketTimeoutMS: 45000,
serverSelectionTimeoutMS: 5000,
family: 4,
};
mongoose.connect(process.env.MONGODB_URI!, options);- Core CLI with 8 templates
- TypeScript/JavaScript support
- Express/Fastify frameworks
- Mongoose/Prisma ORMs
- Security middlewares (Helmet, CORS, HPP)
- Winston logging with rotation
- ESLint + Prettier
- GitHub Actions CI/CD
- Docker Support - Multi-stage builds, docker-compose, development setup
- JWT Authentication Templates - Complete auth system with controllers, services, middleware
- Jest Testing Setup - Test configuration, setup files, coverage reporting
- OpenAPI/Swagger Docs - Swagger configuration and UI integration
- OAuth2.0 (Google, GitHub) templates
- GraphQL support (Apollo Server)
- Microservices templates
- WebSocket support (Socket.io)
- Message queues (RabbitMQ, Kafka)
- S3 file upload integration
- Email templates (SendGrid, AWS SES)
- Payment integration (Stripe)
- Admin dashboard generator
- Database migrations UI
- Load testing scripts (k6)
- Deno runtime support
- NestJS framework option
- tRPC support
- Serverless deployment (AWS Lambda, Vercel)
- Multi-tenancy support
We love contributions! See CONTRIBUTING.md for guidelines.
# Fork and clone
git clone https://github.com/yourusername/backforge.git
cd backforge
# Install dependencies
pnpm install
# Create feature branch
git checkout -b feature/awesome-feature
# Make changes and test
pnpm build
pnpm lint
pnpm test
# Commit with conventional commits
git commit -m "feat(templates): add PostgreSQL connection pooling"
# Push and create PR
git push origin feature/awesome-featureWe use Conventional Commits:
feat: new feature
fix: bug fix
docs: documentation changes
style: code style changes (formatting)
refactor: code refactoring
test: add or update tests
chore: maintenance tasks
perf: performance improvements
MIT License - see LICENSE file for details.
- GitHub: github.com/Codewithevilxd/backforge
- npm: npmjs.com/package/backforge-core
- Docs: backforge.dev (coming soon)
- Discord: discord.gg/backforge (coming soon)
- Twitter: @backforge_dev
npm create backforge@latest saas-backend -- \
--lang typescript \
--framework fastify \
--database prisma \
--auth jwt \
--docker \
--testing
# Includes: Multi-tenancy, RBAC, rate limiting, audit logsnpm create backforge@latest shop-api -- \
--lang typescript \
--framework express \
--database mongoose \
--payments stripe
# Includes: Product catalog, cart, orders, webhooksnpm create backforge@latest mobile-backend -- \
--lang typescript \
--framework fastify \
--database prisma \
--auth oauth \
--push firebase
# Includes: User management, push notifications, image uploadFramework: Fastify + Prisma (PostgreSQL)
Hardware: 4 vCPU, 8GB RAM, SSD
Test: wrk -t12 -c400 -d30s
โโโโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโ
โ โ Requests โ Latency โ RPS โ
โโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโค
โ Express โ ~35k โ 11.2ms โ ~1.2k โ
โ Fastify โ ~52k โ 7.6ms โ ~1.7k โ
โ With Cache โ ~78k โ 5.1ms โ ~2.6k โ
โโโโโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโ
Memory Usage (idle): ~45MB
Memory Usage (load): ~180MB
Cold Start: <2s
Built with love using:
Special thanks to all contributors and the open-source community! ๐
BackForge - From zero to production in minutes, not weeks.
Star โญ the repo if you find it helpful!