Martin Harris
Martin Harris

Reputation: 23

What express route can I use for any file in a directory?

I have a directory of PDF files that I only want authorized users to access. Currently, the issue is when I navigate to the URL that contains a given file in the folder the get callback isn't running. For example, I expect when I go to localhost:3000/Buyer_templates/file.pdf it will run the callback in the get. Currently, it allows me to view the pdf and the callback is not executed.

app.get('/Buyer_templates/*', (req,res) => {
    res.redirect('/')
})

The above code works if the url isn't a file (e.g /Buyer_templates/blahblahblah)

However, when I put in a file name (e.g. Buyer_templates/file.pdf) the callback isn't activated.

I also tried these paths in the get

/Buyer_templates/*.*

/Buyer_templates/(.*)

The issue is the callback isn't being executed. How can I make it so when I put in any PDF file name within the URL the callback is run?

Upvotes: 0

Views: 102

Answers (1)

James
James

Reputation: 82096

When you configure static route in Express, any files from within the hierarchy from the root folder are served automatically. For example, if I had a folder structure like so:

root
- public
-- css
-- js
-- img

And my server looked like

app.use(express.static('public'));
app.use((req, res, next) => {
  console.log(`REQUEST LOGGED: ${req.url}`);
  return next();
});
...

When I access any file URL that resides within that static root e.g.

/css/somefile.css
/js/somefile.js
/img/somefile.jpg

Then you would notice that the request never hits the console.log, that's because Express understands that these are a. files and b. reside within the static directory, and thus don't require any further processing (hence why you notice if you try non-file URLs they do process further).

In terms of adding some form of authorization to static files, there are a couple of ways you can do it e.g.

  • exclude this particular folder from the static route and process the authorization that you would do in any other route
app.get('/Buyer_templates/*', (req, res, next) => 
  if (/* some authorization check */) {
    return res.sendFile('...');
  } else {
    return res.status(403).send('Unauthorized');
  }
});
  • add your authorization middleware before you setup the static route (although it would mean a bit more work determining which URLs to check etc.)
app.use((req, res, next) => {
  if (req.path.startsWith('/Buyer_templates')) {
    return res.status(403).send('Unauthorized');
  }
  return next();
})
app.use(express.static(__dirname));

The examples above are just simplistic for demonstration, but they should give you the desired effect. Also, worth pointing out that express.static(__dirname) isn't advisable as it would make all files accessible from the root of your app, which would include any code you may have hosted on the server. Be more specific i.e. express.static('Buyer_templates')

Upvotes: 1

Related Questions