Nine spreads, from an empty folder to a deployed, tested API with a database and logins. Examples use Node.js, Express and PostgreSQL. The ideas carry to Python, Go, Java, and the rest.
"A stateless REST API with validation, a database behind a data layer, token auth, structured logging, tests, and a container in CI."
Use the tabs or the ← → keys to turn pages.
A backend is a program that listens on a port and answers HTTP requests. Each request has a method, a path, headers, and maybe a body. Each response has a status code and usually JSON.
// The smallest possible backend (Node 20+)
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(404); res.end();
}).listen(3000);
$ curl -i localhost:3000/health
"Thin handlers, a service layer for the rules, and middleware for the cross-cutting stuff."
$ mkdir my-api && cd my-api && git init $ npm init -y $ npm install express pg zod bcrypt jsonwebtoken pino dotenv $ npm install -D jest supertest nodemon $ printf "node_modules\n.env\n" > .gitignore
// app.js: build the app (importable by tests)
const express = require('express');
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.json({ ok: true }));
module.exports = app;
// server.js: start listening
const app = require('./app');
const { port } = require('./config');
app.listen(port, () => console.log(`listening on ${port}`));require('dotenv').config();
const need = (k) => { if (!process.env[k]) throw new Error(`missing ${k}`); return process.env[k]; };
module.exports = {
port: Number(process.env.PORT) || 3000,
databaseUrl: need('DATABASE_URL'),
jwtSecret: need('JWT_SECRET'),
};"Separate the app from the server so tests can import it, and fail fast if config is missing."
// src/routes/tasks.js
const router = require('express').Router();
const tasks = require('../services/tasks');
router.get('/', async (req, res) => {
res.json(await tasks.list(req.user.id, req.query));
});
router.post('/', async (req, res) => {
res.status(201).json(await tasks.create(req.user.id, req.body));
});
router.get('/:id', async (req, res) => {
const t = await tasks.get(req.user.id, req.params.id);
if (!t) return res.sendStatus(404);
res.json(t);
});
router.delete('/:id', async (req, res) => {
await tasks.remove(req.user.id, req.params.id);
res.sendStatus(204);
});
module.exports = router;
// app.js: app.use('/api/v1/tasks', requireAuth, require('./routes/tasks'));
/api/v1/… so you can evolve safely"Plural nouns, correct verbs, honest status codes, and pagination from day one."
// src/middleware/validate.js
const { z } = require('zod');
const taskInput = z.object({
title: z.string().trim().min(1).max(200),
done: z.boolean().default(false),
}).strict();
const validate = (schema) => (req, res, next) => {
const r = schema.safeParse(req.body);
if (!r.success)
return res.status(400).json({ error: { code: 'VALIDATION', issues: r.error.issues } });
req.body = r.data;
next();
};
// router.post('/', validate(taskInput), handler)
// src/middleware/errors.js: register LAST
class HttpError extends Error { constructor(s, m) { super(m); this.status = s; } }
app.use((err, req, res, next) => {
const status = err.status || 500;
if (status === 500) req.log.error({ err }, 'unhandled');
res.status(status).json({ error: { message: status === 500 ? 'Internal error' : err.message } });
});
express-async-errorsIdempotency-Key so retries don't double-charge"Schema validation at the edge, typed errors, and a single handler that never leaks internals."
// src/db/index.js
const { Pool } = require('pg');
const { databaseUrl } = require('../config');
const pool = new Pool({ connectionString: databaseUrl, max: 10 });
module.exports = { query: (text, params) => pool.query(text, params), pool };
// src/services/tasks.js: parameters only, scoped to the user
const db = require('../db');
exports.list = async (userId, { done, limit = 20 }) => {
const { rows } = await db.query(
`SELECT id, title, done FROM tasks
WHERE user_id = $1 AND ($2::boolean IS NULL OR done = $2)
ORDER BY id DESC LIMIT $3`,
[userId, done === undefined ? null : done === 'true', Math.min(Number(limit), 100)]);
return rows;
};
exports.create = async (userId, { title, done }) =>
(await db.query(
'INSERT INTO tasks (user_id, title, done) VALUES ($1,$2,$3) RETURNING *',
[userId, title, done])).rows[0];
-- migrations/001_tasks.sql
CREATE TABLE tasks (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
title TEXT NOT NULL, done BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now());
CREATE INDEX ON tasks (user_id, id DESC);
"Parameterized queries, a bounded pool, every query scoped by user, and migrations in version control."
// src/routes/auth.js
const bcrypt = require('bcrypt'), jwt = require('jsonwebtoken');
const db = require('../db'), { jwtSecret } = require('../config');
router.post('/signup', validate(creds), async (req, res) => {
const hash = await bcrypt.hash(req.body.password, 12);
const { rows } = await db.query(
'INSERT INTO users (email, pw_hash) VALUES ($1,$2) RETURNING id', [req.body.email, hash]);
res.status(201).json({ id: rows[0].id });
});
router.post('/login', validate(creds), async (req, res) => {
const { rows } = await db.query('SELECT * FROM users WHERE email=$1', [req.body.email]);
const u = rows[0];
if (!u || !(await bcrypt.compare(req.body.password, u.pw_hash)))
return res.status(401).json({ error: { message: 'Invalid credentials' } }); // same msg both ways
res.json({ token: jwt.sign({ sub: u.id }, jwtSecret, { expiresIn: '15m' }) });
});
// src/middleware/auth.js
exports.requireAuth = (req, res, next) => {
try {
const t = (req.headers.authorization || '').replace('Bearer ', '');
req.user = { id: jwt.verify(t, jwtSecret).sub };
next();
} catch { res.sendStatus(401); }
};
req.user.id, so users can't read each other's rows"bcrypt hashes, short-lived tokens, a uniform login error, and ownership checks on every query."
// src/app.js: structured logs with pino-http
const pino = require('pino-http')({ redact: ['req.headers.authorization'] });
app.use(pino); // adds req.log + a request id
app.get('/health', (req, res) => res.json({ ok: true })); // liveness
app.get('/ready', async (req, res) => { // readiness
try { await db.query('SELECT 1'); res.json({ ready: true }); }
catch { res.status(503).json({ ready: false }); }
});
// graceful shutdown: finish in-flight requests, then exit
const server = app.listen(port);
process.on('SIGTERM', () => server.close(() => db.pool.end().then(() => process.exit(0))));
error needs action · warn odd · info normal · debug off in prodexpress-rate-limit protects login and expensive routes"Structured logs with request IDs, liveness and readiness probes, and graceful shutdown."
// test/tasks.test.js
const request = require('supertest');
const app = require('../src/app');
const db = require('../src/db');
let token;
beforeAll(async () => {
await request(app).post('/api/v1/auth/signup').send({ email: 't@x.com', password: 'longpassword1' });
token = (await request(app).post('/api/v1/auth/login')
.send({ email: 't@x.com', password: 'longpassword1' })).body.token;
});
afterAll(() => db.pool.end());
test('create then list a task', async () => {
const auth = { Authorization: `Bearer ${token}` };
const c = await request(app).post('/api/v1/tasks').set(auth).send({ title: 'Ship it' });
expect(c.status).toBe(201);
const l = await request(app).get('/api/v1/tasks').set(auth);
expect(l.body.map(t => t.title)).toContain('Ship it');
});
test('rejects missing token', async () => {
expect((await request(app).get('/api/v1/tasks')).status).toBe(401);
});
$ npm test -- --coverage
"Integration tests over HTTP against a real test database, plus unit tests for the rules."
FROM node:20-slim WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev COPY src ./src USER node EXPOSE 3000 CMD ["node", "src/server.js"]
☐ config and secrets from env vars, not code ☐ HTTPS and a reverse proxy / load balancer ☐ migrations run as a deploy step ☐ CORS limited to your front end's origin ☐ rate limits on login and write routes ☐ helmet() headers, body size limit ☐ /health and /ready wired to the platform ☐ backups of the database, restore tested ☐ logs shipped somewhere searchable + an alert ☐ CI runs lint, tests, build, image scan
$ docker build -t my-api:1.0 . && docker run -p 3000:3000 --env-file .env my-api:1.0
"Stateless containers behind a load balancer, indexed queries, a cache for hot reads, and a queue for slow work."