7

Here's an example (Express 3) middleware setup thats worked for me globally:

app.configure(function () {
    app.use(express.static(__dirname + "/public"));
    app.use(express.bodyParser({
          keepExtensions: true,
          limit: 10000000, // set 10MB limit
          defer: true              
    }));
    //... more config stuff
}

For security reasons, I don't want to allow 500GB+ posts on routes other than /upload, so I'm trying to figure out how to specify the limit on specific routes, rather than globally in the middleware.

I know the multipart middleware in bodyParser() already sniffs out content types, but I want to limit it even further.

This does not seem to work in express 3:

app.use('/', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 10,
  defer: true              
}));
app.use('/upload', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 1024 * 500,
  defer: true              
}));

I get an error Error: Request Entity Too Large when I try to upload a 3MB file on the upload URL.

How do you do this correctly?

Chenmunka
  • 685
  • 4
  • 21
  • 25
qodeninja
  • 10,946
  • 30
  • 98
  • 152

2 Answers2

14

Actually as suggested by hexacyanide above, app.use() works on limiting single route.
The problem comes from the ordering of route paths.
Going to example above, if you put '/upload' first, then the bodyParser should match that rule first.

So put the code like so (I am using Express 4.0 +):

app.use("/PATH_WITH_LIMIT", bodyParser({ 
    limit: 1024 * 1000
}));
app.use("/",bodyParser());

You can see how express binds the middleware on app.use() method call here.

Plyto
  • 741
  • 1
  • 9
  • 18
  • 1
    I'd like to note that body parser detects if body has already been parsed for the current request and doesn't do double parsing. That's actually why it works in this case, otherwise second rule would still throw an error unless request would end earlier. – Konstantin Mar 09 '17 at 15:51
1

Just specify the optional path option when using app.use().

app.use('/', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 10,
  defer: true              
}));
app.use('/upload', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 1024 * 500,
  defer: true              
}));
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • 4
    Are you sure this works? I got an error saying `Error: Request Entity Too Large` when I tried to upload a 3MB file, where according to your code it should accept 500GBs – qodeninja Sep 23 '13 at 07:57
  • 1
    Doesn't work. And somehow 'defer:true' creates problems for me to access req.body. – Isilmë O. Jan 25 '14 at 15:18
  • This should work if you reverse the order -- the `/upload` path needs to come first – taxilian Jul 29 '22 at 18:46