Part 3: Building REST APIs with Express.js and TypeScript

From Zero to Production-Ready API

Three years ago, I started my first Express.js API project. I wrote everything in one server.js fileβ€”routes, business logic, database queries, all mixed together. By day 3, the file was 800 lines. By week 2, I couldn't find anything. Adding a feature meant scrolling through spaghetti code.

Today, my microservices use a structured architecture: separate layers for routes, controllers, services, and repositories. Each component has one responsibility. Adding features takes minutes instead of hours.

This article shows you how to build production-ready REST APIs using the structure I wish I'd known from day one.

Project Setup

Initialize TypeScript Project

# Create project directory
mkdir user-service
cd user-service

# Initialize package.json
npm init -y

# Install dependencies
npm install express
npm install cors helmet morgan
npm install pg              # PostgreSQL client
npm install dotenv          # Environment variables

# Install TypeScript dependencies
npm install -D typescript @types/node @types/express
npm install -D @types/cors @types/morgan
npm install -D ts-node nodemon
npm install -D @types/pg

# Initialize TypeScript
npx tsc --init

TypeScript Configuration

Project Structure

Package.json Scripts

Environment Configuration

Database Configuration

Type Definitions

Repository Layer (Data Access)

Service Layer (Business Logic)

Controller Layer (Request Handling)

Routes

Middleware

Utility Functions

Application Setup

Testing the API

Key Takeaways

  1. Layered architecture: Routes β†’ Controllers β†’ Services β†’ Repositories

  2. TypeScript for type safety and better developer experience

  3. Dependency injection makes testing easier

  4. Consistent error handling across all endpoints

  5. Environment configuration separates dev/staging/prod settings

  6. Connection pooling for efficient database access

  7. Graceful shutdown prevents data loss

  8. Structured logging for debugging

  9. Security headers (helmet) by default

  10. Health checks for monitoring

Next in series: Authentication and Authorizationβ€”securing your REST API with JWT and role-based access control.


A well-structured codebase scales better than clever code. Start with good architecture, and maintenance becomes easier.

Last updated