0
0
Expressframework~5 mins

Dependency injection in Express

Choose your learning style9 modes available
Introduction

Dependency injection helps you organize your code by giving parts what they need instead of making them find it themselves. This makes your app easier to manage and test.

When you want to share a database connection across different routes without creating it multiple times.
When you want to swap out a service (like a logger or email sender) easily for testing or different environments.
When you want to keep your route handlers simple and focused on their job, not on creating dependencies.
When you want to write unit tests for your routes by providing fake or mock services.
When your app grows and you want to avoid tightly coupling parts of your code.
Syntax
Express
function createRouter(dependency) {
  const router = require('express').Router();
  router.get('/', (req, res) => {
    const data = dependency.getData();
    res.send(data);
  });
  return router;
}

const myDependency = {
  getData: () => 'Hello from dependency!'
};

const app = require('express')();
app.use('/path', createRouter(myDependency));

You create functions that accept dependencies as parameters.

Then you pass the actual dependencies when you use those functions.

Examples
This example shows injecting a logger service into a router.
Express
function createLogger() {
  return {
    log: (msg) => console.log('LOG:', msg)
  };
}

function createRouter(logger) {
  const router = require('express').Router();
  router.get('/', (req, res) => {
    logger.log('Route accessed');
    res.send('Check console for log');
  });
  return router;
}

const logger = createLogger();
const app = require('express')();
app.use('/', createRouter(logger));
This example injects a database object into a user service used by a route.
Express
function createUserService(db) {
  return {
    getUser: (id) => db.findUserById(id)
  };
}

const fakeDb = {
  findUserById: (id) => ({ id, name: 'Test User' })
};

const userService = createUserService(fakeDb);

const app = require('express')();
app.get('/user/:id', (req, res) => {
  const user = userService.getUser(req.params.id);
  res.json(user);
});
Sample Program

This program creates a message service and injects it into a router. The router uses the service to send a message when you visit /message.

Express
const express = require('express');

// Dependency: simple message service
function createMessageService() {
  return {
    getMessage: () => 'Hello from the message service!'
  };
}

// Router factory that injects the message service
function createMessageRouter(messageService) {
  const router = express.Router();
  router.get('/', (req, res) => {
    const message = messageService.getMessage();
    res.send(message);
  });
  return router;
}

const app = express();
const messageService = createMessageService();
app.use('/message', createMessageRouter(messageService));

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000/message');
});
OutputSuccess
Important Notes

Dependency injection helps keep your code clean and easy to test.

Always inject dependencies instead of requiring them inside modules to improve flexibility.

Use this pattern especially when your app grows bigger and has many parts.

Summary

Dependency injection means giving parts of your app what they need instead of making them find it.

It helps keep code organized, testable, and flexible.

In Express, you can inject dependencies by passing them to router or service factory functions.