0

In my express app, I am trying to display an svg on the client side from the server side. The SVGs I'm serving come from the directory, /svg_library, which contains 3 svgs:

/svg_library

  • svg1.svg
  • svg2.svg
  • svg3.svg

In order to serve svg1.svg to the client, I use app.use(express.static('svg_library')).

The client then has access at localhost:3000/svg1.svg.

Question 1: how do I serve just a single file (svg1.svg), so that a user cannot have access to the other files (svg2.svg and svg3.svg) in svg_library?

Question 2: From an efficiency and security perspective, is it better to use express.static or directly serve the svg in the http response (changing the content-type to img/svg+xml)?

mmm42
  • 47
  • 7

1 Answers1

1

Answer for Q1: You can create a middleware to filter the static resources.

E.g.

import express from 'express';
import path from 'path';

const app = express();
const port = 3000;

const ignoreFiles = ['/svg2.svg', '/svg3.svg'];

app.use(function (req, res, next) {
  console.log(req.url);
  if (ignoreFiles.includes(req.url)) {
    return res.sendStatus(403);
  }
  next();
});
app.use(express.static(path.resolve(__dirname, 'svg_library')));

app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));

Testing via curl:

⚡  curl http://localhost:3000/svg1.svg                              
<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
  Sorry, your browser does not support inline SVG.  
</svg> %                                                                                                                                    
⚡  curl http://localhost:3000/svg2.svg
Forbidden%                                                                                                                                  
⚡  curl http://localhost:3000/svg3.svg
Forbidden%  

Answer for Q2: From Serving static files in Express doc:

For best results, use a reverse proxy cache to improve the performance of serving static assets.

Also, see this

Lin Du
  • 88,126
  • 95
  • 281
  • 483