Node.js and Express: Build Production APIs

Why Node.js for APIs

Node.js handles thousands of concurrent connections efficiently. Combined with Express, it is the fastest way to build APIs.

Basic Express API

const express = require("express");
const app = express();
app.use(express.json());

let tasks = [];

app.get("/api/tasks", (req, res) => {
    res.json(tasks);
});

app.post("/api/tasks", (req, res) => {
    const task = { id: Date.now(), ...req.body, done: false };
    tasks.push(task);
    res.status(201).json(task);
});

app.put("/api/tasks/:id", (req, res) => {
    const task = tasks.find(t => t.id == req.params.id);
    if (!task) return res.status(404).json({ error: "Not found" });
    Object.assign(task, req.body);
    res.json(task);
});

app.delete("/api/tasks/:id", (req, res) => {
    tasks = tasks.filter(t => t.id != req.params.id);
    res.status(204).send();
});

app.listen(3000, () => console.log("API running on 3000"));

Middleware

// Logging middleware
app.use((req, res, next) => {
    console.log(`${req.method} ${req.path}`);
    next();
});

// Auth middleware
const auth = (req, res, next) => {
    const token = req.headers.authorization;
    if (!token) return res.status(401).json({ error: "Unauthorized" });
    req.user = verifyToken(token);
    next();
};

Error Handling

// Global error handler
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: "Internal server error" });
});

Production Tips

  • Use helmet for security headers
  • Rate limit with express-rate-limit
  • Validate input with Joi or express-validator
  • Use PM2 for process management
  • Add CORS configuration

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top