How to Separate Routers and Controllers in Node.js ?

In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the application easier to understand and manage.

Table of Content

  • What Are Routers and Controllers?
  • Separate Routers
  • Separate Controllers

What Are Routers and Controllers?

  • Routers: Handle the routing of HTTP requests to the appropriate controller functions. They define the endpoints and HTTP methods (GET, POST, PUT, DELETE) for your application.
  • Controllers: Contain the business logic for handling requests and generating responses. They perform tasks like querying the database, processing data, and returning responses to the client.

Approach

We will create a simple Node.js application, using Express. This application returns the “Home” string for the main route, “About” for the About the route, and “Contact” for the contact route. Then we will separate the routers and controller into different javascript files.

Steps to Create NodeJS Application

Step 1: Initialize Node.js application by using the following command.

npm init -y

Step 2: Install the necessary packages/libraries in your project using the following commands.

npm install express

Step 3: Create Server File

Create an ‘app.js’ file, inside this file require an express Module, and create a constant ‘app’ for creating an instance of the express module.

const express = require('express')
const app = express()

Step 4: Creating Routers

Now let’s set up three get routes for ‘/’, ‘/about’, and ‘/contact, inside this route, we will set up a callback function that sends the string, “Home”, “About” and “Contact” respectively.

app.get('/', (req, res) => {
res.send("Home");
});

app.get('/about', (req, res) => {
res.send("About");
});

app.get('/contact', (req, res) => {
res.send("Contact");
});

Step 5: Set up a port to run our server

We will do it by using the express, listen to the method.

app.listen(3000, () => {
console.log("listening on http://localhost:3000");
})

Example: Implementation to separate routers and controllers in Node.js

Node
// index.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send("Home");
});

app.get('/about', (req, res) => {
    res.send("About");
});

app.get('/contact', (req, res) => {
    res.send("Contact");
});

app.listen(3000, () => {
    console.log("listening on http://localhost:3000");
});

Step to run the application: Inside the terminal type the  following command

node app.js

Output: 

Separate Routers

Step 1: Create a folder for Routers

Let’s create a folder inside the project folder, let’s call it routers, inside this folder, create three files, homerouter.js, aboutrouter.js, and contactrouter.js. 

Step 2: Setup Routers files

Inside each file, we have to import the Routers from the express. Then create an instance of that router, we will again call it an app, then copy the respected routers from the app.js to the respective file and simply export it.

JavaScript
// homerouter.js

const { Router } = require('express');
const app = Router();

app.get('/', (req, res) => {
    res.send("Home");
});

module.exports = app;
JavaScript
// aboutrouter.js

const { Router } = require('express');
const app = Router();

app.get('/about', (req, res) => {
    res.send("About");
});

module.exports = app;
JavaScript
// contactrouter.js

const { Router } = require('express');
const app = Router();

app.get('/contact', (req, res) => {
    res.send("Contact");
});

module.exports = app;
Node
// app.js

const express = require('express');
const home = require('./routers/homerouter');
const about = require('./routers/aboutrouter');
const contact = require('./routers/contactrouter');

const app = express();

app.use(home);
app.use(about);
app.use(contact);

app.listen(3000, () => {
    console.log("listening on http://localhost:3000");
});

Separate Controllers

Step 1: Create a folder for Controllers

Let’s create a folder inside the project folder, let’s call it controllers, inside this folder, create three files, homecontroller.js, aboutcontrollerr.js, and contactcontroller.js.

Step 2: Setup Controller files

Inside each file, we have to copy the respective controller from the app.js to the respective file and simply export it.

JavaScript
// homecontroller.js

module.exports = (req, res) => {
    res.send("Home")
};
JavaScript
// aboutcontroller.js

module.exports = (req, res) => {
    res.send("About")
};
JavaScript
// contactcontroller

module.exports = (req, res) => {
    res.send("Contact")
};

Step 3: Import the controller in each router file respectively, then replace the callback function with it

const { Router } = require('express');
const home = require('../controllers/homecontroller')

const app = Router();
app.get('/', home);
module.exports = app;

Output:



Contact Us