You may already notice yourself scrolling through an increasingly long file to find specific endpoints, or copying and pasting the same validation code between routes. This single-file approach becomes problematic as APIs grow.

Working with smaller, focused files provides several benefits:

  • Easier navigation: Find specific functionality quickly instead of scrolling through hundreds of lines.
  • Reduced conflicts: Team members can work on different files without merge conflicts.
  • Better testing: Test individual components in isolation.
  • Clearer responsibility: Each file has a single, clear purpose.
  • Improved readability: Less cognitive load when working on specific features.

Let’s examine the specific problems with our current single-file approach:

Everything Mixed Together

The current index.ts file contains:

  • Express app setup and JSON middleware.
  • All user endpoints (GET, POST, PUT, PATCH, DELETE).
  • All posts endpoints (GET, plus user-posts relationships).
  • Server startup code.

This creates a file with over 300 lines where user routes are mixed with post routes, making it hard to find the specific endpoint you need to modify.

Repeated Validation Code

Every endpoint that uses a user ID repeats this pattern:

const userId = Number(req.params.id);
if (isNaN(userId)) {
  return res.status(400).json({ error: "Invalid user ID" });
}

The same validation appears in multiple routes. If you need to change this validation logic, you must update it in multiple places.

Tags: