Frosty CMS: Refactoring Middleware

Intro

One of the things that we can do to DRY up our code a bit is instead of repeating our middleware functions in every route file, we can put all of them into a separate file and then require that file.

File Structure

We’ll make a new folder in our base and put a new index file in that folder.

middleware index

and then inside of that index file we will create a new module.

Middleware Object

First we’ll create an object, and then for every function we add we can call it as a method on the middleware object. We are only creating one method right now. Then we export the module.

// middleware functions object
const middlewareObj = {};

middlewareObj.isLoggedIn = (req, res, next)=>{
    if(req.isAuthenticated()){
        return next();
    }
    res.redirect("/login");
};


// export module
module.exports = middlewareObj;

Require the Module

Like all modules we must require them in all the files that need them. So we can add that requirement to every route file that is using middleware.

const express           = require("express"),
      router            = express.Router({mergeParams: true}),
      middleware        = require('../middleware'),
      Blog              = require('../models/blogs');

Middleware Methods

And now we simply replace all of our middleware function calls with calling the method on the middleware object.

// new blog: receive and save
router.post("/", middleware.isLoggedIn, (req, res) => {

// etc etc....

If you are getting errors for things like your Mongoose Schemas not being defined, it’s because you need to add those as requirements in your middleware file. All done.