← Back to JavaScript
56

REST APIs with Express and Middleware

Build cleaner REST APIs with Express by separating routes, controllers, services, and middleware instead of collapsing everything into one large file.

📘 Theory

Separate HTTP Concerns from Business Logic

Routes should describe entry points, not contain the whole system.

A common and practical structure is to keep routes thin, controllers focused on HTTP translation, services focused on business rules, and middleware focused on cross-cutting concerns.

That separation makes testing easier because each piece has a clearer reason to change.

  • `routes/` define endpoints
  • `controllers/` translate request to use case
  • `services/` hold the business rules
  • `middlewares/` handle concerns like validation, auth, and logging

Middleware Works Best When Each Step Has One Job

A good middleware chain feels deliberate, not accidental.

1

Middleware is ideal for concerns that repeat across endpoints: request parsing, validation, auth checks, rate limiting, or logging.

2

The mistake is not using middleware. The mistake is creating middleware that also hides business behavior that belongs elsewhere.

Centralized Error Handling Prevents Repeated Chaos

If every route improvises errors differently, the API stops feeling consistent.

1

Express error middleware gives you one place to standardize failure responses and log useful information.

2

That is much healthier than writing slightly different `try/catch` blocks inside every route and returning a new JSON shape every time something breaks.

Express Helps You Move Faster, but Bad Structure Still Hurts

Framework convenience does not automatically produce a healthy architecture.

1

Express removes native Node boilerplate, but it does not decide your project boundaries, naming, or contracts for you.

2

That means the best Express apps still rely on the same discipline you learned earlier: clean modules, explicit rules, and stable response design.

🧪 Learn by doing

Example Guided Example: A Small Route with Validation Middleware Validate the payload before the controller runs.

🏁 Challenges

Challenge Challenge: Add a Central Error Handler Create one middleware that turns thrown errors into a consistent JSON response.

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com