← Back to blog

Building a Clean REST API with Express.js

During my time as a Backend Developer at Badr Interactive, I built RESTful APIs consumed by frontend developers and third-party services. Here's the structure I keep coming back to for a Node.js + Express.js project.

1. Keep routes, logic, and data separate

A common mistake is stuffing everything into a single app.js. Instead, split responsibilities:

routes/    → define endpoints
controllers/ → handle requests & responses
services/   → business logic
models/     → database schemas

2. Use middleware for cross-cutting concerns

Authentication, logging, and error handling belong in middleware — not repeated in every route. This keeps handlers focused and your code DRY.

3. Consistent error responses

Frontend devs love a predictable API. Wrap errors in a standard shape:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid email format"
  }
}

4. Don't forget the database

Whether you use SQL or a NoSQL store, design your schema around the queries you'll actually run. Index the fields you filter on, and keep migrations in version control.

The goal isn't clever code — it's an API that's easy to consume, easy to test, and easy to grow. That's what makes the frontend team (and your future self) happy.

— Fegi Sucepto Priawan · UI/UX Designer & Backend Developer