Skip to content

How to separate CRUD routes on Node.js and Express?

when you want to have all CRUD operations of your model in one file it’s done in such a way as our 1st method:

routes.js

const express = require("express");
const users = require("../routes/users");

module.exports = function (app) {
    app.use(express.json());
    app.use("/api/user", users);
};

users.js

router.patch("/", auth, async (req, res) => {
    // create and update operations ...
})

router.delete("/:id", auth, async (req, res) => {
    // delete operations ...
})
module.exports = router



BUT what if we want to want to have separate files for CRUD in this form as a 2nd method ?
users
|__patchUser.js
|__deleteUser.js
|__index.js

I expect the index file to be similar to :
index.js

const express = require("express");
const router = express.Router();
module.exports = router;

other separated files like this:
patchUser.js

const router = require("./index");

router.patch("/", auth, async (req, res) => {

})

but this doesn’t work.

How to correct the 2nd method to have separated CRUD routing files?

Answer

You should follow this architecture. In index.js file you should only call routes. like, userRoutes, productRoutes.

index.js

 const express = require('express');
 const userRoutes = require('./routes/user);
    
 const app = express();
 app.use('/api/user',userRoutes);

In routes Folder
user.js

const router = require('express')().Router;
const patchUser = require('./controllers/user/PatchUser');
const deleteUser = require('./controllers/user/DeleteUser');
const auth = require('./middleware/auth);
//keep middlewares in middleware files

router.patch('/',auth,patchUser);
router.delete('/:id',auth,deleteUser);

module.exports = router;

In controllers folder
user folder

PatchUser.js

const patchUser = async(req,res,next)=>{
//todo
}

module.exports = patchUser;

DeleteUser.js

const deleteUser = async(req,res,next)=>{
//todo
}
module.exports = deleteUser;

For easy, you should follow following steps:

  1. Create PatchUser.js file in controllers/user/.
  2. Create userRoutes.js file in routes.
  3. Modify index.js file.
  4. Create DeleteUser.js file in controllers/user/.
  5. Modify userRoutes.js file
  6. Modify index.js file

At first,you may find this difficult but with time and practice you will find it very easy and it is the first step for clean architecture.

I hope you were looking for same.