Create a Production-Ready Node.js REST API (Express + Error Handling + Docker)

Build a Fast REST API with Node.js & Express — Step-by-Step

Contents

Why Node.js + Express?

Lightweight, fast startup, huge ecosystem. This guide gives a minimal production-ready layout: routes, JSON input validation, error handling and a Dockerfile so you can deploy quickly.

1) Project setup

Run locally:

mkdir todo-api && cd todo-api
npm init -y
npm i express dotenv joi
npm i -D nodemon

Create a minimal package.json scripts section:

// package.json (scripts)
"scripts": {
  "start": "node src/index.js",
  "dev": "nodemon src/index.js"
}

2) Server & routes (src/index.js)

// src/index.js
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());

// simple in-memory store (replace with DB in prod)
const todos = [];

// routes
app.get('/api/todos', (req, res) => res.json(todos));
app.post('/api/todos', (req, res, next) => {
  const { title } = req.body;
  if (!title) return res.status(400).json({ error: 'title is required' });
  const todo = { id: Date.now().toString(), title, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

app.use((req, res) => res.status(404).json({ error: 'not found' }));

// centralized error handler
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: 'internal server error' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on :${PORT}`));

3) Input validation & better errors

Use joi for validation. Example:

// validate middleware (src/middleware/validate.js)
const Joi = require('joi');
module.exports = (schema) => (req, res, next) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });
  next();
};

4) Dockerfile (optional, but recommended)

# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
EXPOSE 3000
CMD ["node","src/index.js"]

5) Quick curl tests

# create
curl -X POST http://localhost:3000/api/todos -H "Content-Type: application/json" -d '{"title":"Buy milk"}'
# list
curl http://localhost:3000/api/todos

Comments

Popular posts from this blog

How to Center a Div - The 3 Modern Ways (2026)

Build a Simple Calculator with HTML, CSS & JavaScript

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples