Himmators Himmators - 7 months ago 52
Node.js Question

Adding methods to req?

librarys like express-validation and passport add methods to the req-variable, like

. I know I can do this from inside a route:

app.get('/', (req,res,next) => {
req.foo = bar;

But how can I do it from a library or external module?


In short: You expose a handler function which your consumers will need to app.use().

Here's the general approach. Consider the following module:

module.exports = function myExtension() {
  return function myExtensionHandler(req, res, next) {
    // This is called for every request - you can extend req or res here
    req.myFun = myFun

    // Make sure to call next() in order to continue the
    // chain of handlers
    return next()

function myFun() {
  // My magic function

Now, from a consumer perspective:

const express = require('express')
const myExtension = require('my-extension')
const app = express()

// Here you tell Express to use your extension for incoming requests
// ...