Home » Nodejs » Redirecting to a static file in express.js

Redirecting to a static file in express.js

Posted by: admin December 21, 2017 Leave a comment

Questions:

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?

Answers:
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.