Rouz
Rouz

Reputation: 1357

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.

Upvotes: 2

Views: 732

Answers (2)

Jordonias
Jordonias

Reputation: 5848

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();
  }
}

Upvotes: 2

DevDig
DevDig

Reputation: 1018

In express, the execution order of middleware is defined by the order it has been attached to the app/router.

req.param being an exception, as it is executed before any route handler that matches the parameter.

The order in which your routes and middleware functions are declared is the order which they will be executed. I do not know of a way to change this, maybe fiddling with the internals of express router, but there is no documented/clean way to achive this by default.

To make sure your middleware has access to the cookie parsed by cookie-parser, attach the cookie parsing middleware before any route definitions.

        app.use(cookieParser());
        // all other middleware that uses cookies

Upvotes: 2

Related Questions