Building Production-Ready APIs

RESTful APIs are the backbone of modern web applications. This guide shows you how to build robust, type-safe APIs with Node.js, Express, and TypeScript.

Step 1: Project Setup

mkdir my-api && cd my-api
npm init -y
npm install express cors helmet
npm install -D typescript @types/express @types/node ts-node nodemon

Step 2: TypeScript Configuration

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

Step 3: Express Server

import express from 'express';
import cors from 'cors';
import helmet from 'helmet';

const app = express();

app.use(helmet());
app.use(cors());
app.use(express.json());

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date() });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 4: Route Organization

Organize your routes into separate modules for better maintainability.

Step 5: Error Handling Middleware

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Internal Server Error' });
});

Conclusion

A well-structured API is crucial for any modern application. Follow these patterns to build scalable and maintainable APIs.