expressjs / serve-static

Serve static files
MIT License
1.38k stars 227 forks source link

how to prevent a file from being served #126

Closed cekvenich closed 4 years ago

cekvenich commented 4 years ago

Hi, lets say I have a file with extension .ts or file mysecret.yaml and I don't want it served. How can I filter/prevent some file extensions and some files from being served?

dougwilson commented 4 years ago

Hi @cekvenich ! So this is just yet another Express middleware. As such, it will only serve requests that make it into the middleware in the first place. This means to prevent this middleware from, say, serving requests where the file as .ts extension as your example, just set up the routing to not route those into this middleware instance and you're good to go! Here is a simple example:

var staticMiddleware = serveStatic('/path/to/directory')

app.use((req, res, next) => {
  if (req.path.endsWith('.ts')) next() // whatever condition you don't want to serve the file
  else staticMiddleware(req, res, next)
})

You can make the condition whatever you desire, of course. I hope this helps!

cekvenich commented 4 years ago

thx. it was obvious after your response.