Sometimes, we want to serve static files on a dynamic route using Express.
In this article, we’ll look at how to serve static files on a dynamic route using Express.
How to serve static files on a dynamic route using Express?
To serve static files on a dynamic route using Express, we can use the req.params
property to get route parameters in our route handler.
For instance, we write
app.get("/user/:uid/files/*", (req, res) => {
const uid = req.params.uid;
const path = req.params[0] ? req.params[0] : "index.html";
res.sendFile(path, { root: "./public" });
});
to get the value of the uid
route parameter with req.params.uid
.
And we get the value of the *
parameter with req.params[0]
.
Finally, we call res.sendFile
to return the file response for the file at the path
relative to the root
folder.
Conclusion
To serve static files on a dynamic route using Express, we can use the req.params
property to get route parameters in our route handler.