jensengar
jensengar

Reputation: 6167

Express Request Post-Processing

I haven't been able to find anything in express's documentation, but is there such thing as request post processing? I am using a custom token authentication scheme using passport and I would like the ability to automatically update the token in a response header after making a request, mostly a hashed timestamp for authentication purposes. For discussion purposes, let's say I want the following function to execute after each request:

function requestPostProcess(req, res){
    if (res.status == 200)
    {
        res.token = updateToken();
    }
}

Ideally, I'd like to be able to do this without having to call next() in each of my routes. Is that even possible?

Upvotes: 1

Views: 1265

Answers (1)

Kop4lyf
Kop4lyf

Reputation: 4590

If you want to add the token to the response,

1) You can create a middleware that adds the token as soon as the request comes, and before it is processed. Put this before request handlers.

Example,

app.use(function(req, res, next){
  res.token = updateToken();
  next();
})

The glitch here is that, the token will come with all the responses but that can be something you may accept, since it is a timestamp. Plus you can even handle errors using middlewares, and remove the token when the status is not 200.

Advantage: minimal changes required, with proper error handling it works great.

Disadvantage: it tells the time when request was received and not when the response was ready.

2) If you want to put the response after the process is completed, meaning the time when the response was ready, then you may need to create a utility function that sends back all the responses, and you always call that function. That utility function will check the status and appends the token.

function sendResponseGateway(req, res){
    if (res.status == 200)
    {
        res.token = updateToken();
    }
    res.send()
}

Now whenever you are ready to send response, you can call this function.

Disadvantage: function needs to be called everywhere and you will not be writing "res.send" anywhere.

Advantage :you have a gateway of sending response, you can do additional stuff like encoding, adding more headers etc. in that function and all those response modification stuff happens at one place.

Upvotes: 2

Related Questions