Search code examples
node.jsreactjsexpresscreate-react-appserver-side-rendering

Exclude index.html from express.static when serving React app with Express


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.


Solution

  • 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);
    });