Rouz Rouz - 9 days ago 4
Javascript Question

NodeJs and ExpressJs middleware that relies on another middleware being used

I am creating an express middleware. My index.js exports is a function that returns a function(req,res,next) {...}

function myMiddleware (options) {
//some stuff with options...
return function middleware(req, res, next) {
//stuff
}
}

module.exports = myMiddleware;


So the user would could start using my middleware like this:

var express = require('express'),
myMiddleware = require('my-middleware'),

app = express();
app.use(myMiddleware());


The important thing is that I must make sure that middleware has access to cookies. Of course I could parse req.header.cookie myself but there exists a cookie-parser module that does the parsing for me.

So I would like to make sure that cookie-parser middleware is already being used when my middleware starts up. I could probably instruct the user to first use cookieParser() but I dislike it.

Is there a way to do it easily?

EDIT

I could even port cookie-parser since it is not a huge module. But that is probably the least thing I would do since it can introduce a lot of maintenance work that I would normally not do.

Answer

You have two options:

Force the cookie-parser middleware if req.cookies is undefined. If cookie-parser has already been called, this call will be ignored. See: https://github.com/expressjs/cookie-parser/blob/master/index.js

The downfall to this approach is that the cookieParser middleware will only have the default options.

var cookieParser = require('cookie-parser');

function myMiddleware(options) {
  return function(req, res, next) {
    return cookieParser()(req, res, function() {
      // Your middleware code
      return next();
    });
  }
}

Give a warning if req.cookies is undefined

function myMiddleware(options) {
  return function(req, res, next) {
    if(!req.cookies) {
      // Some warning
    }
    // Your middleware code
    return next();
  }
}