
How to Create a Simple REST API with Node.js and Express
Architecting enterprise-grade REST APIs in Node.js and Express. Covers clean architecture, request validation, structured error handling, and security.
In enterprise software engineering, building a Node.js REST API extends far beyond binding an HTTP listener and returning JSON blobs. While Express.js remains the de facto framework for Node.js due to its minimal footprint and immense ecosystem, greenfield enterprise projects often fail when built on simplistic “Hello World” patterns. Without structured application boundaries, strict type safety, runtime schema validation, and centralized error handling, Node.js applications quickly turn into unmaintainable, tightly coupled codebases.
This guide provides an enterprise blueprint for building modern, scalable RESTful APIs using Node.js, Express, and TypeScript. We will construct a decoupled, layered application architecture that addresses the non-functional requirements essential for production systems: maintainability, testability, security, and observability.
Architectural Topography: Layered Architecture
To achieve separation of concerns, our REST API will implement a variant of Clean/Layered Architecture. Incoming HTTP requests flow through a strict unidirectional pipeline, keeping HTTP routing, domain logic, and data access decoupled.
+-----------------------------------+
| Client HTTP Request |
+-----------------------------------+
|
v
+-----------------------------------+
| Global Middleware Pipeline |
| (Helmet, CORS, Request ID, Logging)|
+-----------------------------------+
|
v
+-----------------------------------+
| Express Router |
+-----------------------------------+
|
v
+-----------------------------------+
| Request Validation (Zod DTO) |
+-----------------------------------+
|
v
+-----------------------------------+
| Controller Layer |
| (HTTP status codes, parsing) |
+-----------------------------------+
|
v
+-----------------------------------+
| Service Layer |
| (Core business domain logic) |
+-----------------------------------+
|
v
+-----------------------------------+
| Data Access Layer |
| (Repository / ORM / Database) |
+-----------------------------------+
Layer Responsibilities
- Global Middleware Pipeline: Handles horizontal cross-cutting concerns (security headers, CORS, request correlation tracking, parsing).
- Router & Validation Layer: Maps HTTP endpoints to controllers and validates request payloads at runtime using schemas before touching business logic.
- Controller Layer: Decoupled from application logic. Extracts data from request objects, delegates to services, and converts domain responses into standardized HTTP responses.
- Service Layer: Pure domain business logic. Totally agnostic of Express request/response objects.
- Data Access / Repository Layer: Manages persistent storage operations (e.g., Prisma, TypeORM, or custom DB clients).
Project Initialization & Configuration Engine
Production applications must enforce environment configuration validity at startup to implement the Fail Fast principle. We begin by configuring TypeScript and a type-safe environment loader.
Directory Structure
src/
├── config/ # Immutable configuration & environment parsing
├── controllers/ # HTTP presentation handlers
├── errors/ # Standardized enterprise error abstractions
├── middlewares/ # Security, validation, logging, error handling
├── routes/ # Route mapping definitions
├── schemas/ # Zod validation schemas / DTO definitions
├── services/ # Core domain business logic
├── types/ # Ambient & global TypeScript definitions
├── utils/ # Structured logging and helper utilities
├── app.ts # Express application setup (middleware pipeline)
└── server.ts # Application bootstrap & process lifetime management
Type-Safe Environment Configuration (src/config/env.config.ts)
Instead of accessing process.env raw throughout the codebase—which introduces non-deterministic runtime runtime failures—validate configuration via Zod at launch.
import dotenv from 'dotenv';
import { z } from 'zod';
dotenv.config();
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'staging', 'production', 'test']).default('development'),
PORT: z.string().transform((val) => parseInt(val, 10)).default('3000'),
API_PREFIX: z.string().default('/api/v1'),
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).default('info'),
CORS_ORIGIN: z.string().default('*'),
});
const parseConfig = () => {
const result = envSchema.safeParse(process.env);
if (!result.success) {
console.error('❌ Invalid environment variables configuration:', result.error.format());
throw new Error('Invalid environment variables');
}
return result.data;
};
export const config = parseConfig();
export type Config = z.infer<typeof envSchema>;
Domain Model & Schema Validation Layer
In TypeScript applications, compile-time interfaces do not exist at runtime. If a client posts invalid JSON, static types cannot save the server from runtime runtime errors. We solve this using Zod to generate runtime validation and TypeScript types concurrently.
Data Transfer Object (DTO) Schemas (src/schemas/user.schema.ts)
import { z } from 'zod';
export const CreateUserSchema = z.object({
body: z.object({
email: z.string().email({ message: 'Invalid email address format' }),
name: z.string().min(2, { message: 'Name must be at least 2 characters long' }),
role: z.enum(['ADMIN', 'DEVELOPER', 'VIEWER']).default('VIEWER'),
}),
});
export const GetUserParamsSchema = z.object({
params: z.object({
id: z.string().uuid({ message: 'User ID must be a valid UUID v4' }),
}),
});
export type CreateUserInput = z.infer<typeof CreateUserSchema>;
export type GetUserParamsInput = z.infer<typeof GetUserParamsSchema>;
Generic Request Validation Middleware (src/middlewares/validate.middleware.ts)
This higher-order middleware ensures unvalidated payloads never reach the controller layer.
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject, ZodError } from 'zod';
export const validateRequest = (schema: AnyZodObject) => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
});
next();
} catch (error) {
if (error instanceof ZodError) {
next(error); // Forward directly to our centralized error handler
} else {
next(error);
}
}
};
};
Centralized Enterprise Error Architecture
A robust REST API requires deterministic, structured error payloads. Throwing unstructured Error instances yields inconsistent client experiences and leak stack traces in production.
Standardized Error Taxonomy (src/errors/app-error.ts)
export abstract class AppError extends Error {
public abstract readonly statusCode: number;
public readonly isOperational: boolean;
constructor(message: string, isOperational = true) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.isOperational = isOperational;
Error.captureStackTrace(this, this.constructor);
}
}
export class NotFoundError extends AppError {
public readonly statusCode = 404;
constructor(message = 'Resource not found') {
super(message);
}
}
export class BadRequestError extends AppError {
public readonly statusCode = 400;
constructor(message = 'Bad request payload') {
super(message);
}
}
export class ConflictError extends AppError {
public readonly statusCode = 409;
constructor(message = 'Resource conflict detected') {
super(message);
}
}
export class InternalServerError extends AppError {
public readonly statusCode = 500;
constructor(message = 'An unexpected internal error occurred') {
super(message, false); // Non-operational error
}
}
Global Error Interceptor (src/middlewares/error.middleware.ts)
This middleware catches all application errors, translates Zod validation issues into structured responses, logs diagnostic telemetry, and sanitizes outgoing responses based on environment.
import { Request, Response, NextFunction, ErrorRequestHandler } from 'express';
import { ZodError } from 'zod';
import { AppError } from '../errors/app-error';
import { config } from '../config/env.config';
import { logger } from '../utils/logger';
interface ErrorResponsePayload {
status: 'error' | 'fail';
message: string;
requestId?: string;
errors?: Array<{ field: string; message: string }>;
stack?: string;
}
export const errorHandler: ErrorRequestHandler = (
err: Error,
req: Request,
res: Response,
// Express error handlers require 4 arguments to be recognized; do not remove `next`
// eslint-disable-next-line @typescript-eslint/no-unused-vars
next: NextFunction
): void => {
const requestId = req.headers['x-request-id'] as string | undefined;
// Handle Domain Operational Errors
if (err instanceof AppError) {
logger.warn({ err, requestId }, `Operational Error: ${err.message}`);
const response: ErrorResponsePayload = {
status: err.statusCode >= 500 ? 'error' : 'fail',
message: err.message,
...(requestId && { requestId }),
};
if (config.NODE_ENV === 'development') {
response.stack = err.stack;
}
res.status(err.statusCode).json(response);
return;
}
// Handle Zod Schema Validation Failures
if (err instanceof ZodError) {
logger.warn({ err: err.errors, requestId }, 'Validation Failure');
const formattedErrors = err.errors.map((e) => ({
field: e.path.join('.').replace(/^(body|query|params)\./, ''),
message: e.message,
}));
res.status(400).json({
status: 'fail',
message: 'Validation failed',
errors: formattedErrors,
...(requestId && { requestId }),
});
return;
}
// Handle Unhandled/System Errors (Fatal)
logger.error({ err, requestId }, `Unhandled Error: ${err.message}`);
const response: ErrorResponsePayload = {
status: 'error',
message: config.NODE_ENV === 'production' ? 'Internal server error' : err.message,
...(requestId && { requestId }),
};
if (config.NODE_ENV === 'development') {
response.stack = err.stack;
}
res.status(500).json(response);
};
Implementing Business Logic & HTTP Presentation
We decouple business logic from Express via dedicated Service classes. Controllers merely orchestrate data between HTTP semantics and domain services.
Domain Model & Data Access Simulation (src/services/user.service.ts)
import { ConflictError, NotFoundError } from '../errors/app-error';
export interface User {
id: string;
email: string;
name: string;
role: 'ADMIN' | 'DEVELOPER' | 'VIEWER';
createdAt: Date;
}
// In-Memory Repository Abstraction for Demonstration
class UserService {
private users: Map<string, User> = new Map();
public async createUser(data: Omit<User, 'id' | 'createdAt'>): Promise<User> {
const existingUser = Array.from(this.users.values()).find((u) => u.email === data.email);
if (existingUser) {
throw new ConflictError(`User with email '${data.email}' already exists`);
}
const newUser: User = {
id: crypto.randomUUID(),
...data,
createdAt: new Date(),
};
this.users.set(newUser.id, newUser);
return newUser;
}
public async getUserById(id: string): Promise<User> {
const user = this.users.get(id);
if (!user) {
throw new NotFoundError(`User with ID '${id}' was not found`);
}
return user;
}
public async listUsers(): Promise<User[]> {
return Array.from(this.users.values());
}
}
export const userService = new UserService();
Presentation Controller Layer (src/controllers/user.controller.ts)
Notice how the controller contains zero DB query logic or schema evaluation. It accepts structured requests and emits standardized REST payloads.
import { Request, Response, NextFunction } from 'express';
import { userService } from '../services/user.service';
export class UserController {
public async createUser(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const user = await userService.createUser(req.body);
res.status(201).json({
status: 'success',
data: { user },
});
} catch (error) {
next(error);
}
}
public async getUserById(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const user = await userService.getUserById(req.params.id);
res.status(200).json({
status: 'success',
data: { user },
});
} catch (error) {
next(error);
}
}
public async listUsers(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const users = await userService.listUsers();
res.status(200).json({
status: 'success',
results: users.length,
data: { users },
});
} catch (error) {
next(error);
}
}
}
export const userController = new UserController();
Routing & Middleware Pipeline Assembly
We build scalable routing structures using Express Routers and apply route-level validation.
Logging Infrastructure (src/utils/logger.ts)
In modern cloud environments, structured JSON logging (via libraries like Pino) is required for aggregation tools like Datadog, Splunk, or Elastic.
import pino from 'pino';
import { config } from '../config/env.config';
export const logger = pino({
level: config.LOG_LEVEL,
transport:
config.NODE_ENV === 'development'
? { target: 'pino-pretty', options: { colorize: true } }
: undefined,
base: {
env: config.NODE_ENV,
},
});
Correlation ID Middleware (src/middlewares/correlation.middleware.ts)
Request tracing across distributed microservices requires a correlation ID attached to every request context.
import { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
export const correlationIdMiddleware = (req: Request, res: Response, next: NextFunction): void => {
const headerName = 'x-request-id';
const requestId = (req.headers[headerName] as string) || crypto.randomUUID();
req.headers[headerName] = requestId;
res.setHeader(headerName, requestId);
next();
};
Routing Table (src/routes/user.routes.ts)
import { Router } from 'express';
import { userController } from '../controllers/user.controller';
import { validateRequest } from '../middlewares/validate.middleware';
import { CreateUserSchema, GetUserParamsSchema } from '../schemas/user.schema';
const router = Router();
router
.route('/')
.post(validateRequest(CreateUserSchema), userController.createUser)
.get(userController.listUsers);
router
.route('/:id')
.get(validateRequest(GetUserParamsSchema), userController.getUserById);
export const userRoutes = router;
Main Application Assembly (src/app.ts)
Separating the Express application setup (app.ts) from server lifecycle listener (server.ts) allows automated end-to-end testing without binding to real TCP ports.
import express, { Application } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import { config } from './config/env.config';
import { correlationIdMiddleware } from './middlewares/correlation.middleware';
import { errorHandler } from './middlewares/error.middleware';
import { userRoutes } from './routes/user.routes';
import { NotFoundError } from './errors/app-error';
class App {
public app: Application;
constructor() {
this.app = express();
this.configureMiddleware();
this.configureRoutes();
this.configureErrorHandling();
}
private configureMiddleware(): void {
// Basic Security Hardening
this.app.use(helmet());
this.app.use(cors({ origin: config.CORS_ORIGIN }));
// Request Parsers
this.app.use(express.json({ limit: '10kb' }));
this.app.use(express.urlencoded({ extended: true }));
// Observability & Tracing
this.app.use(correlationIdMiddleware);
}
private configureRoutes(): void {
// Health Check Endpoint
this.app.get('/health', (req, res) => {
res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() });
});
// API Routes Mapping
this.app.use(`${config.API_PREFIX}/users`, userRoutes);
// Fallthrough Handler for Undefined Routes (404)
this.app.all('*', (req, res, next) => {
next(new NotFoundError(`Cannot find route ${req.originalUrl} on this server`));
});
}
private configureErrorHandling(): void {
// Centralized Global Error Handler
this.app.use(errorHandler);
}
}
export default new App().app;
Enterprise Server Bootstrap & Graceful Shutdown
Handling unhandled exceptions, unhandled promises, and OS signals (SIGTERM, SIGINT) cleanly ensures your API terminates gracefully without dropping pending HTTP connections or leaving open database sockets.
Production Bootstrapper (src/server.ts)
import http from 'http';
import app from './app';
import { config } from './config/env.config';
import { logger } from './utils/logger';
const server = http.createServer(app);
const startServer = () => {
server.listen(config.PORT, () => {
logger.info(`🚀 Server operating in [${config.NODE_ENV}] environment on port ${config.PORT}`);
});
};
// Graceful Shutdown Mechanics
const shutdown = (signal: string) => {
logger.info(`Received ${signal}. Initiating graceful shutdown sequence...`);
server.close(() => {
logger.info('HTTP server terminated. Closing active connections...');
// Close Database Pools / Redis connections here
// e.g., await db.disconnect();
logger.info('Process cleanup complete. Exiting gracefully.');
process.exit(0);
});
// Force Exit if Shutdown Hangs
setTimeout(() => {
logger.error('Forced shutdown invoked due to hung connection timeouts.');
process.exit(1);
}, 10000);
};
// Unhandled Promise Rejections & Global Exceptions Handling
process.on('unhandledRejection', (reason: Error) => {
logger.fatal({ err: reason }, 'UNHANDLED PROMISE REJECTION! Shutting down process...');
// Forceful exit recommended on unhandled rejections to prevent state corruption
process.exit(1);
});
process.on('uncaughtException', (error: Error) => {
logger.fatal({ err: error }, 'UNCAUGHT EXCEPTION! Shutting down process...');
process.exit(1);
});
// OS Signal Listening
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
startServer();
Production Readiness Checklist
Deploying Node.js Express APIs into modern enterprise infrastructure (Kubernetes, AWS ECS, GCP Cloud Run) requires adherence to structural readiness standards:
| Architectural Concern | Implementation Strategy | Enterprise Rationale |
|---|---|---|
| Type Safety | TypeScript (strict: true) |
Eliminates class of runtime type mismatch errors. |
| Input Validation | Runtime Schema Parsing (Zod) | Prevents malicious payloads and injection attacks at system boundary. |
| Security Hardening | helmet, cors, Request Payload limits |
Sets HTTP security headers (HSTS, CSP, X-Frame-Options) out-of-the-box. |
| Process Management | Handled SIGTERM / SIGINT |
Enables zero-downtime rolling updates in Kubernetes clusters. |
| Observability | JSON Telemetry with Pino & Correlation IDs | Allows tracing requests end-to-end across microservice networks. |
| Error Handling | Operational vs Non-Operational Errors | Prevents sensitive stack traces from leaking to end users. |
Summary
Building enterprise REST APIs with Node.js and Express requires moving beyond simplistic implementations. By separating concerns into logical layers (Controller, Service, Schema validation), implementing structured error handling, validating configuration early, and listening for lifecycle shutdown signals, we ensure our applications remain robust, secure, and maintainable under production workloads.