8

In Express under Node.js, I'd like to inspect a request under a specific path (say, /restricted) and if it is acceptable, have the request be handled by the static provider, which handles the caching headers etc.

If I simply use app.get('/restricted/:file', ...) and then use res.sendfile to send the static file if approved, it will ignore any caching headers and always send the file.

I can't use a blanket logged-in check because different users should only get different files.

What is the best way to implement this?

w00t
  • 17,944
  • 8
  • 54
  • 62

1 Answers1

14
var express = require("express");
var app = express.createServer();

var staticMiddleware = express.static(__dirname + "/public");

app.get("/restricted/:file", function(req, res, next) {
  var authorized = true;
  //Compute authorization appropriately here
  if (authorized) {
    staticMiddleware(req, res, next);
  } else {
    res.send(401);
  }
});
app.listen(3456);

This will use the static middleware when appropriate including all of its functionality. Otherwise you can handle unauthorized requests as appropriate.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Normally (unprotected) I am serving the page via `app.use(express.static('public'));`. When using your approach, the HTML loads but all styles and scripts are gone (404). – SCBuergel Aug 01 '16 at 19:54