Conditionally serve two React builds with Node.js

Viewed 82

I have two React apps that are served to the client based on the device. I'm using Node.js and Express to achieve this. I borrowed the static assets handling part from this question here but it is needed to add a middleware that serves the index.html to the * route if you're using client side routing.

However when I do this, I get nothing on the page. Below is the code I'm using.

const mobileStaticHandler = express.static(path.join(__dirname, MOBILE_APP_BUILD_FOLDER));
const desktopStaticHandler = express.static(path.join(__dirname, DESKTOP_APP_BUILD_FOLDER));

const serveStaticAssets = (req, res, next) => {
    const isMobile = /Mobi/i.test(req.headers["user-agent"]);
    if (isMobile) {
        mobileStaticHandler(req, res, next);
    } else {
        desktopStaticHandler(req, res, next);
    }
};
const serveIndexFile = (req, res, next) => {
    const isMobile = /Mobi/i.test(req.headers["user-agent"]);
    const BUILD_FOLDER = isMobile ? MOBILE_APP_BUILD_FOLDER : DESKTOP_APP_BUILD_FOLDER;

    res.sendFile(path.join(__dirname, BUILD_FOLDER, "index.html"));
};
app.use("*", [serveStaticAssets, serveIndexFile]);

Adding the following line in the same middleware, gives an "headers sent" error.

res.sendFile(path.join(__dirname, BUILD_FOLDER, "index.html"));

P.S. I know I shouldn't ask two questions in one, but the real problem is here is to serve two React Apps (with client side routing, but only among themselves) on a single domain.

0 Answers
Related