Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any issues with setting custom properties on the node.js request object?

Tags:

node.js

Are the node.js built in objects available for adding custom properties?

var http = require('http');
var server = http.createServer(function(request, response) {
    request.myObj = {'lots of info':true};  <-- is it ok to add this object to request?
    response.writeHead(200, {
        'Content-type':'text/plain'
    });
    response.end('Hello World!');
});
server.listen(8888);
console.log('Listening on http://127.0.0.1:8888');

Is this considered acceptable or off limits?


1 Answers

This is very commonly done, especially in express/connect apps. Just watch out for name collisions, but otherwise the node community seems mostly totally OK with this based on my experience. If you are paranoid, use a unique namespace like req.MY_APP = {}; and stick all your stuff there.

I did one time encounter a bug when both my application and the strongloop agent tried to set req.graph, but I contacted them and they agreed they should use a less common name for their property.

like image 107
Peter Lyons Avatar answered Oct 19 '25 12:10

Peter Lyons