Skip to main content

Lesson 7 of 8

Mini Project: Task Manager - Part 8 (Node.js REST API)

Build the complete Task Manager REST API - typed Express app with env validation at startup, request-id middleware, auth middleware with JWT, typed controllers and service layer, comprehensive error handling, and a clean router structure.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Task Manager Part 8 - Complete Express API

Task Manager Part 8 - Complete Express API
// src/app.ts - Express application factory
import express               from "express";
import cors                  from "cors";
import { config }            from "@/config/env";
import { requestIdMiddleware } from "@/middleware/requestId";
import { errorHandler }      from "@/middleware/errorHandler";
import { taskRouter }        from "@/routes/tasks";
import { authRouter }        from "@/routes/auth";

export function createApp(): express.Application {
  const app = express();

  // ── Parse JSON bodies ─────────────────────────────────────
  app.use(express.json());

  // ── CORS ─────────────────────────────────────────────────
  app.use(cors({ origin: config.CORS_ORIGIN, credentials: true }));

  // ── Request ID on every request ───────────────────────────
  app.use(requestIdMiddleware);

  // ── Routes ────────────────────────────────────────────────
  app.use("/api/v1/auth",  authRouter);
  app.use("/api/v1/tasks", taskRouter);

  // ── Health check (untyped - intentionally simple) ─────────
  app.get("/health", (_req, res) => {
    res.json({ status: "ok", env: config.NODE_ENV, uptime: process.uptime() });
  });

  // ── 404 handler ───────────────────────────────────────────
  app.use((_req, res) => {
    res.status(404).json({ error: "Route not found" });
  });

  // ── Error handler (last!) ─────────────────────────────────
  app.use(errorHandler);

  return app;
}

// src/server.ts - entry point
import { createApp } from "./app";
import { config }    from "@/config/env";

const app = createApp();
const server = app.listen(config.PORT, () => {
  console.log(`✅ API running → http://localhost:${config.PORT}/api/v1`);
  console.log(`   Environment : ${config.NODE_ENV}`);
});

// Graceful shutdown
process.on("SIGTERM", () => {
  console.log("SIGTERM received - shutting down...");
  server.close(() => process.exit(0));
});

// src/routes/tasks.ts - task router
import { Router }         from "express";
import { authMiddleware } from "@/middleware/auth";
import { TaskController } from "@/controllers/taskController";
import { TaskService }    from "@/services/taskService";
import { InMemoryTaskRepository } from "@/repositories/InMemoryTaskRepository";
import { eventBus }       from "@/lib/eventBus";
import { logger }         from "@/lib/logger";

const repo       = new InMemoryTaskRepository();
const service    = new TaskService(repo, eventBus, logger);
const controller = new TaskController(service);

export const taskRouter: Router = Router();

taskRouter.get   ("/",    controller.list);
taskRouter.get   ("/:id", controller.getById);
taskRouter.post  ("/",    authMiddleware, controller.create);
taskRouter.patch ("/:id", authMiddleware, controller.update);
taskRouter.delete("/:id", authMiddleware, controller.delete);

Common Mistakes

  • Not registering the error handler last - Express matches middleware in registration order. The error handler must come after all routes. A misplaced error handler silently fails to catch errors from routes registered after it.
  • Returning JSON from health check with sensitive info - health checks are often public. Never expose DB connection strings, secrets, or internal version details. Just `{ status: 'ok' }` is sufficient.
  • Not implementing graceful shutdown - a SIGTERM without graceful shutdown drops in-flight requests. `server.close(() => process.exit(0))` waits for all requests to complete before exiting.

Tip

Tip

Practice Mini Project Task Manager Part 8 Nodejs REST API in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Task Manager - Part 8 (Node.js REST API)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Task Manager Part 8 Nodejs REST API from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Task Manager Part 8 Nodejs REST API is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Build the complete Task Manager REST API - typed Express app with env validation at startup, request-id middleware, auth middleware with JWT, typed controllers and service layer, comprehensive error handling, and a clean router structure.
  • Not registering the error handler last - Express matches middleware in registration order. The error handler must come after all routes. A misplaced error handler silently fails to catch errors from routes registered after it.
  • Returning JSON from health check with sensitive info - health checks are often public. Never expose DB connection strings, secrets, or internal version details. Just `{ status: 'ok' }` is sufficient.
  • Not implementing graceful shutdown - a SIGTERM without graceful shutdown drops in-flight requests. `server.close(() => process.exit(0))` waits for all requests to complete before exiting.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done