I'm serving a create-react-app build using Express and appending some script tags to index.html before serving it. Since I'm manipulating the index.html file before serving, I don't want my express.static middleware to handle requests for / or /index.html. Here's what I've tried to make this work:
app.use(
  [/^\/index\.html/, /^\//],
  express.static(path.join(__dirname, "../../build"))
);
app.get("/*", function (req, res) {
  // logic to manipulate index.html
  res.send($.html());
});
But this just gives me a blank white screen even though the original html code gets inserted so I'm assuming that the static middleware is still handling the / request, it just stopped serving the other static assets.
How do I configure this code so my express.static stops overriding my /* route?
It's important that I keep the route as /* because I want that to handle all routes defined in react-router in the client application. So I can't move express.static middleware below the /* route otherwise that will override all requests for static assets.
You can pass {index: false} as the second argument of express.static, this will exclude index.html to be sent from the build directory.
app.use(express.static(path.join(__dirname, "../../build"), {index: false}));
app.get("*", (req, res) => {  
    // logic to manipulate index.html
    res.send($.html());
});
                        You could simply add a seperate handler for index.html and / before the static middleware:
function serveIndex(res) {
  res.send($.html());
}
app.get(["/index.html", "/"], (req, res) => {
    serveIndex(res);
});
app.use(express.static(path.join(__dirname, "../../build")));
app.get("/*", (req, res) => {  
    serveIndex(res);
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With