How to securely upload files in Node with Express? How to securely upload files in Node with Express? express express

How to securely upload files in Node with Express?


Approach 2 actually works. The problem I had was that

app.use(passport.session());

was stopping it from working. So, if you are using passport.js for authentication this might be the issue. If you use this approach just make sure to add the security on the actual route.


I ended up using this plugin

https://github.com/tih-ra/alleup

which works great with image uploads and automatically resizes the files to multiple versions and uploads them to amazon s3. Using this plugin would be inline with using approach 3, but the files are uploaded to the tmp folder first and then deleted.


I am using multiparty for uploading (and streaming) files.

var form = new multiparty.Form();

To 1:

form.on('progress', function (bytesReceived) {  if (262144000 < bytesReceived) {   abortConnection('filesizeexeeded');  }});

implement your own abort Connection function; e.g.:

function abortConnection(reason) {  res.writeHead(413, { 'Connection': 'close' });  return res.end(reason);}

warning: the browser will most probably retry the upload (up to 4 times). I am using a websocket connection to cancel the upload on the client side.

To 2: (use multiparty)

To 3: I created a gist that shows how to check the mime-type on the fly using mmmagic.

If you are using passport in combination with multiparty you might find this useful:

https://github.com/jaredhanson/passport/pull/106#issuecomment-14188999