Back
Backend
Wed Jul 08 2026

Express.js Backend Guidelines: Best Practices for Project Structure, Validation, and Error Handling

Project Structure and File Naming Conventions

Sample Directory Structure:/project-root
├── /controllers
├── /models
├── /routes
├── /middlewares
├── /utils
├── /validations
├── app.ts
└── server.ts
  • File Naming Conventions:
  • Controllers: camelCase.controller.ts
  • Models: camelCase.model.ts
  • Routes: camelCase.routes.ts
  • Middlewares: camelCase.middleware.ts
  • Utils: camelCase.utils.ts
  • Validations: camelCase.validation.ts

Consistent Response Structure

Success Response:

{
  "success": true,
  "message": "Request processed successfully",
  "data": { ... }
}

Note: The message should be simple enough to be able to be displayed in feedback in the frontend.

Error Response:

{
  "success": false,
  "message": "Error processing request", // generalised error
  "error": "Detailed error message",
  "validationErrors": [ ... ] // only for validation errors

}

Centralising Status Codes

  • Use the http-status-codes package for status codes.
  • Alternatively, centralise status codes in a file (e.g., statusCodes.js).

Payload Validation

  • Can Use the Zod library for validation schemas.
  • Or use proper errorHandling to handle all the database related and validation related errors
  • Ensure validation errors contain detailed messages for each field.

Middleware for Request Validation

  • Implement middleware to validate requests
  • Return validation errors with the following structure:
{
  "success": false,
  "message": "Validation errors",
  "error": "Invalid request payload",
  "validationErrors": [
    { "path": "field1", "message": "Error message" },
    { "path": "field2", "message": "Error message" }
  ]
}

Error Handling Middleware

  • Handle validation errors, database errors, and unexpected errors.
  • Ensure all errors follow the consistent error response structure.

Example Workflow

  1. Controller: Defines the request handling logic.
  2. Model: Defines the data schema and interactions with the database.
  3. Routes: Maps endpoints to controller functions.
  4. Middlewares: Validates requests and handles errors.
  5. Utils: Contains utility functions like response formatting and centralised status codes.
  6. Validations: Defines Zod schemas for request payload validation.

By following this guideline, your Express.js backend will have a consistent structure, centralised status codes, uniform response formatting, and robust error handling using Zod and Mongoose.