Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
Abhijeet Singh Avatar asked Oct 30 '25 12:10

Abhijeet Singh


2 Answers

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());
});
like image 185
Shivam Sharma Avatar answered Nov 01 '25 08:11

Shivam Sharma


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);
});
like image 44
eol Avatar answered Nov 01 '25 07:11

eol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!