Serve Static Files on a Dynamic Route using Express

node.jsExpress

node.js Problem Overview


I want to serve static files as is commonly done with express.static(static_path) but on a dynamic route as is commonly done with

app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

A solution is hinted at in this comment by one of the developers but it isn't immediately clear to me what he means.

node.js Solutions


Solution 1 - node.js

Okay. I found an example in the source code for Express' response object. This is a slightly modified version of that example.

app.get('/user/:uid/files/*', function(req, res){
	var uid = req.params.uid,
	    path = req.params[0] ? req.params[0] : 'index.html';
	res.sendFile(path, {root: './public'});
});

It uses the res.sendFile method.

NOTE: security changes to sendFile require the use of the root option.

Solution 2 - node.js

I use below code to serve the same static files requested by different urls:

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));

Although this is not your case, it may help others who got here.

Solution 3 - node.js

You can use res.sendfile or you could still utilize express.static:

const path = require('path');
const express = require('express');
const app = express();

// Dynamic path, but only match asset at specific segment.
app.use('/website/:foo/:bar/:asset', (req, res, next) => {
  req.url = req.params.asset; // <-- programmatically update url yourself
  express.static(__dirname + '/static')(req, res, next);
});         

// Or just the asset.
app.use('/website/*', (req, res, next) => {
  req.url = path.basename(req.originalUrl);
  express.static(__dirname + '/static')(req, res, next);
});

Solution 4 - node.js

This should work:

app.use('/my/dynamic/:route', express.static('/static'));
app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

Documentation states that dynamic routes with app.use() works. See https://expressjs.com/en/guide/routing.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWaylon FlinnView Question on Stackoverflow
Solution 1 - node.jsWaylon FlinnView Answer on Stackoverflow
Solution 2 - node.jsJeff TianView Answer on Stackoverflow
Solution 3 - node.jsprograhammerView Answer on Stackoverflow
Solution 4 - node.jsfvlindenView Answer on Stackoverflow