Skill

Build Scalable Express.js APIs

A skill scaffolding Express.js APIs with layered architecture, custom error handling, JWT auth, and validation middleware.

Works with expressnode.jsmongodbjwt

91
Spark score
out of 100
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Develop robust and scalable backend APIs using Express.js and modern Node.js practices. This asset provides a structured approach to API development, ensuring maintainability, security, and efficient error handling.

Outcomes

What it gets done

01

Implement a clean project structure with separation of concerns (controllers, services, models).

02

Integrate essential middleware for security, rate limiting, logging, and request parsing.

03

Establish a comprehensive error handling system with custom error classes and global handlers.

04

Incorporate input validation and authentication/authorization middleware.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-express-api-builder | bash

Overview

Express API Builder

This skill scaffolds an Express.js API with a layered controller/service/model structure, a custom AppError class and global error handler, express-validator field validation, and JWT authentication with role-based authorization middleware. Use it when an Express API needs a layered project structure and production middleware stack from the start, rather than routes and logic mixed together.

What it does

This skill builds robust, scalable Express.js APIs with modern Node.js best practices - proper error handling, middleware architecture, security, validation, and documentation. Core architecture principles: separation of concerns (controllers handle HTTP logic, services hold business logic, models define data structures), middleware-first design for cross-cutting concerns (auth, validation, logging), an error-first approach with consistent error responses, environment-variable-driven configuration with sensible defaults, and async/await preferred over callbacks.

When to use - and when NOT to

Use it when an Express API needs a layered project structure and production middleware stack from the start, rather than routes and business logic mixed together in one file. The project structure separates controllers/, services/, models/, middleware/, routes/, utils/, and config/.

app.use(helmet());
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000' }));

const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use('/api/', limiter);

app.use(compression());
app.use(morgan('combined'));
app.use(express.json({ limit: '10mb' }));

Inputs and outputs

Error handling centers on a custom AppError class (statusCode, status, code, isOperational flag) and a global error-handler middleware that translates Mongoose CastError/duplicate-key/ValidationError into consistent 4xx responses, exposing the stack trace only in development. Controllers use an asyncHandler wrapper to forward promise rejections to Express's error pipeline without try/catch boilerplate in every handler. Validation uses express-validator with reusable rule sets (email format, password complexity via regex, name length) plus a shared validate middleware that returns a structured 400 with per-field details. Authentication is JWT-based: a Bearer-token auth middleware verifies the token and loads the user, paired with a role-based authorize(...roles) middleware for per-route access control. Routes are organized per resource with .route() chaining combining auth, authorization, and validation middleware per HTTP method. Configuration is centralized in a single config.js reading environment variables for the DB URI, JWT secret/expiry, SMTP settings, and file-upload limits with dotenv.

Who it's for

Node.js developers scaffolding a new Express API who want a production-ready starting structure - layered architecture, security middleware, JWT auth with roles, and consistent error handling - rather than assembling it middleware-by-middleware from scratch. The best-practices list closes with operational concerns beyond the code itself: prefix all routes with /api/v1/ for future versioning, return a consistent success/message/data response shape, log requests with correlation IDs, expose a /health endpoint for monitoring, document the API with Swagger/OpenAPI, and handle SIGTERM/SIGINT for graceful shutdown rather than dropping in-flight requests. Database connection handling is called out specifically too: use pooled connections and handle connection errors gracefully rather than letting a transient DB hiccup crash the whole process.

FAQ

Common questions

Discussion

Questions & comments ยท 0

Sign In Sign in to leave a comment.