Modern API Development with Node.js, Express, and TypeScript using Clean Architecture

Dipak AhiravDipak Ahirav
13 min read

APIs are the backbone of modern web applications. As the complexity of applications grows, it's crucial to adopt an architecture that promotes scalability, maintainability, and testability. In this blog, we'll explore how to build a modern API using Node.js, Express, and TypeScript, all while adhering to Clean Architecture principles.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

1. ๐Ÿงฉ Introduction to Clean Architecture

Back to Table of Contents

Clean Architecture, introduced by Robert C. Martin (Uncle Bob), emphasizes the separation of concerns within an application. It promotes the idea that the business logic should be independent of any frameworks, databases, or external systems. This makes the application more modular, easier to test, and adaptable to changes.

Key principles of Clean Architecture:

  • Independence: The core business logic should not depend on external libraries, UI, databases, or frameworks.

  • Testability: The application should be easy to test without relying on external systems.

  • Flexibility: It should be easy to change or replace parts of the application without affecting others.

2. ๐Ÿ’ก Why Node.js, Express, and TypeScript?

Back to Table of Contents

Node.js

Node.js is a powerful JavaScript runtime that allows you to build scalable network applications. It's non-blocking and event-driven, making it ideal for building APIs that handle a large number of requests.

Express

Express is a minimalistic web framework for Node.js. It provides a robust set of features for building web and mobile applications and APIs. Its simplicity makes it easy to start with, and it's highly extensible.

TypeScript

TypeScript is a superset of JavaScript that adds static types. Using TypeScript in your Node.js application helps catch errors early in the development process, improves code readability, and enhances the overall developer experience.

3. ๐Ÿšง Setting Up the Project

Back to Table of Contents

First, let's create a new Node.js project and set up TypeScript.

mkdir clean-architecture-api
cd clean-architecture-api
npm init -y
npm install express
npm install typescript @types/node @types/express ts-node-dev --save-dev
npx tsc --init

Next, configure your tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

4. ๐Ÿ—๏ธ Structuring the Project with Clean Architecture

Back to Table of Contents

A typical Clean Architecture project is divided into the following layers:

  1. Domain Layer: Contains the business logic, entities, and interfaces. This layer is independent of any other layers.

  2. Use Cases Layer: Contains the application's use cases or business rules.

  3. Infrastructure Layer: Contains implementations of the interfaces defined in the domain layer, such as database connections.

  4. Interface Layer: Contains controllers, routes, and any other web framework-related code.

The directory structure might look like this:

src/
โ”œโ”€โ”€ domain/
โ”‚   โ”œโ”€โ”€ entities/
โ”‚   โ””โ”€โ”€ interfaces/
โ”œโ”€โ”€ use-cases/
โ”œโ”€โ”€ infrastructure/
โ”‚   โ”œโ”€โ”€ database/
โ”‚   โ””โ”€โ”€ repositories/
โ””โ”€โ”€ interface/
    โ”œโ”€โ”€ controllers/
    โ””โ”€โ”€ routes/

5. ๐Ÿ“‚ Implementing the Domain Layer

Back to Table of Contents

In the domain layer, define your entities and interfaces. Let's say we're building a simple API for managing books.

Entity (Book):

// src/domain/entities/Book.ts
export class Book {
  constructor(
    public readonly id: string,
    public title: string,
    public author: string,
    public publishedDate: Date
  ) {}
}

Repository Interface:

// src/domain/interfaces/BookRepository.ts
import { Book } from "../entities/Book";

export interface BookRepository {
  findAll(): Promise<Book[]>;
  findById(id: string): Promise<Book | null>;
  create(book: Book): Promise<Book>;
  update(book: Book): Promise<void>;
  delete(id: string): Promise<void>;
}

6. ๐Ÿ”ง Implementing the Use Cases

Back to Table of Contents

Use cases define the actions that can be performed in the system. They interact with the domain layer and are agnostic to the framework or database used.

Use Case (GetAllBooks):

// src/use-cases/GetAllBooks.ts
import { BookRepository } from "../domain/interfaces/BookRepository";

export class GetAllBooks {
  constructor(private bookRepository: BookRepository) {}

  async execute() {
    return await this.bookRepository.findAll();
  }
}

7. ๐Ÿ—‚๏ธ Implementing the Infrastructure Layer

Back to Table of Contents

In the infrastructure layer, implement the interfaces defined in the domain layer. This is where you interact with databases or external services.

In-Memory Repository (for simplicity):

// src/infrastructure/repositories/InMemoryBookRepository.ts
import { Book } from "../../domain/entities/Book";
import { BookRepository } from "../../domain/interfaces/BookRepository";

export class InMemoryBookRepository implements BookRepository {
  private books: Book[] = [];

  async findAll(): Promise<Book[]> {
    return this.books;
  }

  async findById(id: string): Promise<Book | null> {
    return this.books.find(book => book.id === id) || null;
  }

  async create(book: Book): Promise<Book> {
    this.books.push(book);
    return book;
  }

  async update(book: Book): Promise<void> {
    const index = this.books.findIndex(b => b.id === book.id);
    if (index !== -1) {
      this.books[index] = book;
    }
  }

  async delete(id: string): Promise<void> {
    this.books = this.books.filter(book => book.id !== id);
  }
}

8. ๐ŸŒ Implementing the Interface Layer

Back to Table of Contents

The interface layer contains the controllers and routes that handle HTTP requests and map them to use cases.

Book Controller:

// src/interface/controllers/BookController.ts
import { Request, Response } from "express";
import { GetAllBooks } from "../../use-cases/GetAllBooks";

export class BookController {
  constructor(private getAllBooks: GetAllBooks) {}

  async getAll(req: Request, res: Response) {
    const books = await this.getAllBooks.execute();
    res.json(books);
  }
}

Routes:

// src/interface/routes/bookRoutes.ts
import { Router } from "express";
import { InMemoryBookRepository } from "../../infrastructure/repositories/InMemoryBookRepository";
import { GetAllBooks }

 from "../../use-cases/GetAllBooks";
import { BookController } from "../controllers/BookController";

const router = Router();

const bookRepository = new InMemoryBookRepository();
const getAllBooks = new GetAllBooks(bookRepository);
const bookController = new BookController(getAllBooks);

router.get("/books", (req, res) => bookController.getAll(req, res));

export { router as bookRoutes };

Main Application:

// src/index.ts
import express from "express";
import { bookRoutes } from "./interface/routes/bookRoutes";

const app = express();

app.use(express.json());
app.use("/api", bookRoutes);

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

9. ๐Ÿ”Œ Dependency Injection

Back to Table of Contents

Dependency Injection (DI) is a technique where an object's dependencies are provided rather than hardcoded inside the object. This promotes loose coupling and makes your application easier to test.

Example:

Let's implement a simple DI mechanism using TypeScript.

// src/infrastructure/DIContainer.ts
import { InMemoryBookRepository } from "./repositories/InMemoryBookRepository";
import { GetAllBooks } from "../use-cases/GetAllBooks";

class DIContainer {
  private static _bookRepository = new InMemoryBookRepository();

  static getBookRepository() {
    return this._bookRepository;
  }

  static getGetAllBooksUseCase() {
    return new GetAllBooks(this.getBookRepository());
  }
}

export { DIContainer };

Use the DIContainer in your controllers:

// src/interface/controllers/BookController.ts
import { Request, Response } from "express";
import { DIContainer } from "../../infrastructure/DIContainer";

export class BookController {
  private getAllBooks = DIContainer.getGetAllBooksUseCase();

  async getAll(req: Request, res: Response) {
    const books = await this.getAllBooks.execute();
    res.json(books);
  }
}

10. ๐Ÿšจ Error Handling

Back to Table of Contents

Proper error handling ensures that your API can gracefully handle unexpected situations and provide meaningful error messages to clients.

Example:

Create a centralized error-handling middleware:

// src/interface/middleware/errorHandler.ts
import { Request, Response, NextFunction } from "express";

export function errorHandler(err: any, req: Request, res: Response, next: NextFunction) {
  console.error(err.stack);
  res.status(500).json({ message: "Internal Server Error" });
}

Use this middleware in your main application:

// src/index.ts
import express from "express";
import { bookRoutes } from "./interface/routes/bookRoutes";
import { errorHandler } from "./interface/middleware/errorHandler";

const app = express();

app.use(express.json());
app.use("/api", bookRoutes);
app.use(errorHandler);

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

11. โœ”๏ธ Validation

Back to Table of Contents

Validation is crucial for ensuring that the data entering your application is correct and secure.

Example:

Integrate class-validator to validate incoming requests:

npm install class-validator class-transformer

Create a DTO (Data Transfer Object) for book creation:

// src/interface/dto/CreateBookDto.ts
import { IsString, IsDate } from "class-validator";

export class CreateBookDto {
  @IsString()
  title!: string;

  @IsString()
  author!: string;

  @IsDate()
  publishedDate!: Date;
}

Validate the DTO in your controller:

// src/interface/controllers/BookController.ts
import { Request, Response } from "express";
import { validate } from "class-validator";
import { CreateBookDto } from "../dto/CreateBookDto";
import { DIContainer } from "../../infrastructure/DIContainer";

export class BookController {
  private getAllBooks = DIContainer.getGetAllBooksUseCase();

  async create(req: Request, res: Response) {
    const dto = Object.assign(new CreateBookDto(), req.body);
    const errors = await validate(dto);

    if (errors.length > 0) {
      return res.status(400).json({ errors });
    }

    // Proceed with the creation logic...
  }
}

12. ๐Ÿ’พ Real Database Integration

Back to Table of Contents

Switching from an in-memory database to a real database like MongoDB or PostgreSQL makes your application production-ready.

Example:

Integrate MongoDB:

npm install mongoose @types/mongoose

Create a Mongoose model for Book:

// src/infrastructure/models/BookModel.ts
import mongoose, { Schema, Document } from "mongoose";

interface IBook extends Document {
  title: string;
  author: string;
  publishedDate: Date;
}

const BookSchema: Schema = new Schema({
  title: { type: String, required: true },
  author: { type: String, required: true },
  publishedDate: { type: Date, required: true },
});

const BookModel = mongoose.model<IBook>("Book", BookSchema);
export { BookModel, IBook };

Implement the repository:

// src/infrastructure/repositories/MongoBookRepository.ts
import { Book } from "../../domain/entities/Book";
import { BookRepository } from "../../domain/interfaces/BookRepository";
import { BookModel } from "../models/BookModel";

export class MongoBookRepository implements BookRepository {
  async findAll(): Promise<Book[]> {
    return await BookModel.find();
  }

  async findById(id: string): Promise<Book | null> {
    return await BookModel.findById(id);
  }

  async create(book: Book): Promise<Book> {
    const newBook = new BookModel(book);
    await newBook.save();
    return newBook;
  }

  async update(book: Book): Promise<void> {
    await BookModel.findByIdAndUpdate(book.id, book);
  }

  async delete(id: string): Promise<void> {
    await BookModel.findByIdAndDelete(id);
  }
}

Update the DIContainer to use the MongoBookRepository:

// src/infrastructure/DIContainer.ts
import { MongoBookRepository } from "./repositories/MongoBookRepository";
import { GetAllBooks } from "../use-cases/GetAllBooks";

class DIContainer {
  private static _bookRepository = new MongoBookRepository();

  static getBookRepository() {
    return this._bookRepository;
  }

  static getGetAllBooksUseCase() {
    return new GetAllBooks(this.getBookRepository());
  }
}

export { DIContainer };

13. ๐Ÿ”’ Authentication and Authorization

Back to Table of Contents

Securing your API is essential. JWT (JSON Web Tokens) is a common approach for stateless authentication.

Example:

Integrate JWT for authentication:

npm install jsonwebtoken @types/jsonwebtoken

Create an authentication middleware:

// src/interface/middleware/auth.ts
import jwt from "jsonwebtoken";
import { Request, Response, NextFunction } from "express";

export function authenticateToken(req: Request, res: Response, next: NextFunction) {
  const token = req.header("Authorization")?.split(" ")[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, process.env.JWT_SECRET as string, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

Use this middleware to protect routes:

// src/interface/routes/bookRoutes.ts
import { Router } from "express";
import { BookController } from "../controllers/BookController";
import { authenticateToken } from "../middleware/auth";

const router = Router();

router.get("/books", authenticateToken, (req, res) => bookController.getAll(req, res));

export { router as bookRoutes };

14. ๐Ÿ“ Logging and Monitoring

Back to Table of Contents

Logging is crucial for debugging and monitoring your application in production.

Example:

Integrate winston for logging:

npm install winston

Create a logger:

// src/infrastructure/logger.ts
import { createLogger, transports, format } from "winston";

const logger = createLogger({
  level: "info",
  format: format.combine(format.timestamp(), format.json()),
  transports: [new transports.Console()],
});

export { logger };

Use the logger in your application:

// src/index.ts
import express from "express";
import { bookRoutes } from "./interface/routes/bookRoutes";
import { errorHandler } from "./interface/middleware/errorHandler";
import { logger } from "./infrastructure/logger";

const app = express();

app.use(express.json());
app.use("/api", bookRoutes);
app.use(errorHandler);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  logger.info(`Server is running on port ${PORT}`);
});

15. โš™๏ธ Environment Configuration

Back to Table of Contents

Managing different environments is crucial for ensuring that your application runs correctly in development, testing, and production.

Example:

Use `

dotenv` for environment configuration:

npm install dotenv

Create a .env file:

PORT=3000
JWT_SECRET=your_jwt_secret

Load environment variables in your application:

// src/index.ts
import express from "express";
import dotenv from "dotenv";
dotenv.config();

import { bookRoutes } from "./interface/routes/bookRoutes";
import { errorHandler } from "./interface/middleware/errorHandler";
import { logger } from "./infrastructure/logger";

const app = express();

app.use(express.json());
app.use("/api", bookRoutes);
app.use(errorHandler);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  logger.info(`Server is running on port ${PORT}`);
});

16. ๐Ÿš€ CI/CD and Deployment

Back to Table of Contents

Automating the testing, building, and deployment of your API ensures consistency and reliability.

Example:

Set up GitHub Actions for CI/CD:

Create a .github/workflows/ci.yml file:

name: Node.js CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x, 16.x]

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

17. ๐Ÿงน Code Quality and Linting

Back to Table of Contents

Maintaining consistent code quality is crucial in collaborative environments.

Example:

Integrate ESLint and Prettier:

npm install eslint prettier eslint-config-prettier eslint-plugin-prettier --save-dev

Create an ESLint configuration:

// .eslintrc.json
{
  "env": {
    "node": true,
    "es6": true
  },
  "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
  "plugins": ["@typescript-eslint", "prettier"],
  "parser": "@typescript-eslint/parser",
  "rules": {
    "prettier/prettier": "error"
  }
}

Add Prettier configuration:

// .prettierrc
{
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 80
}

18. ๐Ÿ› ๏ธ Project Documentation

Back to Table of Contents

Documenting your API is crucial for both developers and end-users.

Example:

Generate API documentation with Swagger:

npm install swagger-jsdoc swagger-ui-express

Create Swagger documentation:

// src/interface/swagger.ts
import swaggerJSDoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";
import { Express } from "express";

const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Clean Architecture API",
      version: "1.0.0",
    },
  },
  apis: ["./src/interface/routes/*.ts"],
};

const swaggerSpec = swaggerJSDoc(options);

function setupSwagger(app: Express) {
  app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}

export { setupSwagger };

Set up Swagger in your main application:

// src/index.ts
import express from "express";
import dotenv from "dotenv";
dotenv.config();

import { bookRoutes } from "./interface/routes/bookRoutes";
import { errorHandler } from "./interface/middleware/errorHandler";
import { logger } from "./infrastructure/logger";
import { setupSwagger } from "./interface/swagger";

const app = express();

app.use(express.json());
app.use("/api", bookRoutes);
app.use(errorHandler);
setupSwagger(app);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  logger.info(`Server is running on port ${PORT}`);
});

19. ๐Ÿ Conclusion

Back to Table of Contents

In this blog, we explored how to build a modern API using Node.js, Express, and TypeScript while adhering to Clean Architecture principles. We expanded on the initial implementation by adding key features such as Dependency Injection, Error Handling, Validation, Real Database Integration, Authentication and Authorization, Logging and Monitoring, Environment Configuration, CI/CD, Code Quality and Linting, and Project Documentation.

By following these practices, you'll ensure that your API is not only functional but also maintainable, scalable, and ready for production. As you continue to develop, feel free to explore additional patterns and tools to further enhance your application.

Start Your JavaScript Journey

If you're new to JavaScript or want a refresher, visit my blog on BuyMeACoffee to get started with the basics.

๐Ÿ‘‰ Introduction to JavaScript: Your First Steps in Coding

![](https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=โ˜•&slug=dipakahirav&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff align="left")

Series Index

PartTitleLink
1Ditch Passwords: Add Facial Recognition to Your Website with FACEIORead
2The Ultimate Git Command CheatsheetRead
3Top 12 JavaScript Resources for Learning and MasteryRead
4Angular vs. React: A Comprehensive ComparisonRead
5Top 10 JavaScript Best Practices for Writing Clean CodeRead
6Top 20 JavaScript Tricks and Tips for Every Developer ๐Ÿš€Read
78 Exciting New JavaScript Concepts You Need to KnowRead
8Top 7 Tips for Managing State in JavaScript ApplicationsRead
9๐Ÿ”’ Essential Node.js Security Best PracticesRead
1010 Best Practices for Optimizing Angular PerformanceRead
11Top 10 React Performance Optimization TechniquesRead
12Top 15 JavaScript Projects to Boost Your PortfolioRead
136 Repositories To Master Node.jsRead
14Best 6 Repositories To Master Next.jsRead
15Top 5 JavaScript Libraries for Building Interactive UIRead
16Top 3 JavaScript Concepts Every Developer Should KnowRead
1720 Ways to Improve Node.js Performance at ScaleRead
18Boost Your Node.js App Performance with Compression MiddlewareRead
19Understanding Dijkstra's Algorithm: A Step-by-Step GuideRead
20Understanding NPM and NVM: Essential Tools for Node.js DevelopmentRead

Follow and Subscribe:

0
Subscribe to my newsletter

Read articles from Dipak Ahirav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dipak Ahirav
Dipak Ahirav

Full Stack Developer | Angular & MEAN Stack Specialist | Tech Enthusiast Iโ€™m currently a MEAN Stack Developer at Varahi Technologies, where I leverage Angular, Node.js, and MongoDB