0
0
ExpressHow-ToBeginner · 4 min read

How to Use Service Layer in Express for Cleaner Code

In Express, use a service layer by creating separate modules that handle business logic, then call these services from your route handlers. This keeps your routes clean and focused on HTTP concerns while the service layer manages data processing and rules.
📐

Syntax

The service layer in Express typically involves creating a separate JavaScript module that exports functions for business logic. Your route handlers then import and call these service functions.

Key parts:

  • service.js: Contains business logic functions.
  • routes.js: Calls service functions inside route handlers.
  • module.exports: Exports service functions for reuse.
javascript
/* service.js */
function getData() {
  // business logic here
  return 'Hello from service';
}

module.exports = { getData };

/* routes.js */
const express = require('express');
const router = express.Router();
const service = require('./service');

router.get('/', (req, res) => {
  const message = service.getData();
  res.send(message);
});

module.exports = router;
💻

Example

This example shows a simple Express app using a service layer to separate logic from routes. The service returns a greeting message, and the route sends it as a response.

javascript
/* service.js */
function getGreeting(name) {
  return `Hello, ${name}! Welcome to the service layer.`;
}

module.exports = { getGreeting };

/* app.js */
const express = require('express');
const app = express();
const service = require('./service');

app.get('/greet/:name', (req, res) => {
  const name = req.params.name;
  const greeting = service.getGreeting(name);
  res.send(greeting);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When you visit http://localhost:3000/greet/Alice in a browser, it shows: Hello, Alice! Welcome to the service layer.
⚠️

Common Pitfalls

Common mistakes when using a service layer in Express include:

  • Putting business logic directly in route handlers, making code hard to maintain.
  • Not handling asynchronous operations properly in services, causing unhandled promises.
  • Mixing HTTP concerns (like request/response) inside service functions instead of keeping them pure.

Always keep services focused on logic and data, and routes focused on HTTP.

javascript
/* Wrong way: business logic inside route */
const express = require('express');
const app = express();

app.get('/data', (req, res) => {
  // complex logic here
  const result = 'data processed';
  res.send(result);
});

/* Right way: business logic in service */
// service.js
function processData() {
  return 'data processed';
}
module.exports = { processData };

// routes.js
const express = require('express');
const router = express.Router();
const service = require('./service');

router.get('/data', (req, res) => {
  const result = service.processData();
  res.send(result);
});

module.exports = router;
📊

Quick Reference

Tips for using service layer in Express:

  • Keep services free of HTTP details like req and res.
  • Use async/await in services for database or API calls.
  • Import services in routes and call their functions to keep routes clean.
  • Organize services by feature or domain for better structure.

Key Takeaways

Use a service layer to separate business logic from Express route handlers.
Keep service functions free of HTTP request and response objects.
Call service functions inside routes to keep code organized and maintainable.
Handle asynchronous operations in services with async/await.
Organize service files by feature for clearer project structure.