0

So I need Express to always serve a static directory. These are a lot of guides on how to just serve index.html, for instance here. They use this code:

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

However the problem for me is that the '/*' route only serves index.html, not any files it pulls in, e.g main.js. I basically need my app to always serve 'build/' no matter which path the visitor is on, as the routing is handled by the frontend with React Router. So for instance:

app.get('/*', function (req, res) {
    res.redirect('/');
});

Does not work, because it removes the path. A user landing on '/aa/bb/cc' should be served the same content (express.static) as a user on '/'. I've tried app.use('/*', express.static(...), however this results in SyntaxError: expected expression, got '<' in the browser because seemingly every request is routed to the static index.html file?

Eden Moss
  • 3
  • 2

2 Answers2

0

Don't put it in an app.get do it on the main app.js file as app.use per the Express documentation: https://expressjs.com/en/starter/static-files.html

R Greenstreet
  • 719
  • 6
  • 21
0

To answer my own question, I found this answer: https://stackoverflow.com/a/43373134/11441482

To make all files use absolute paths (e.g src="/main.js") I had to set output.publicPath to '/' in my frontend Webpack configuration. This property is used by html-webpack-plugin. See this question for more details: HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

Eden Moss
  • 3
  • 2