'several react apps with express server

The idea is to make a lot of separate react apps on the one express server, so each of them should appear using the url something like mysite.com/app1, mysite.com/app2 etc

my express code:

const path = require('path');
const app = express();

app.use('/',express.static(path.join(__dirname, './public'))); // just a simple html, not a react
app.use('/app1',express.static(path.join(__dirname, './public/build-1'))); // react
app.use('/app2',express.static(path.join(__dirname, './public/build-2'))); // react

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/app1/*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/build-1', 'index.html'));
});

app.get('/app2/*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/build-2', 'index.html'));
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`)
});

so, actually this works

but there's a problem - when visiting the root url of the site - mysite.com - I get the ordinary index.html file, not a react one, as expected, but using the path - mysite.com/app1 or mysite.com/app2 - the url changes to just mysite.com and the app1 or app2 launches from the root of the site, not staying on the route mysite.com/app1 or mysite.com/app2

and yep, I did configure the react's package.json file for both of the apps

{"homepage": "http://localhost:3000/app1"}

and

{"homepage": "http://localhost:3000/app2"}

the problem has been found: the route I configured in the React App rewrote the url path to the root, so that's why the bug occured



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source