4

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.

2 Answers 2

6

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());
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I actually ended up with just importing an array of all the react-router routes and replaced /* with that. Then I just had to move express.static below that handler to make it work. But this seems like a simple workaround. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.