Search code examples
node.jsexpressreact-routersubdomain

How to serve a react app on express subdomain?


we have a Single Page React App that we're currently hosting within a public endpoint like awesomewebsite.com/app . It initially did work but the server would redirect to a 404 page if refreshed. We tackled the problem by including a wildcard route under the main router. We now want to carry the whole thing to a sub-domain but applying the same trick there just doesn't seem to make it.

When served under public this one works

  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/webapp/*',function(req,res){
    res.sendFile(path.join(__dirname,'public/webapp/index.html'))
})

But this one doesn't

app.use(subdomain('app', express.static(path.join(__dirname, 'reactApp'))));
app.use(subdomain('app', express.Router().use('/*',function(req,res){
    res.sendFile(path.join(__dirname,'reactApp/index.html'))
})));

Anyone has any idea as to why this happens and how can we tackle it by using express-subdomain? Thanks in advance, respectfully.


Solution

  • If you merge them, it should work.

    app.use(subdomain('app', express.Router()
        .use(express.static(path.join(__dirname, 'reactApp')))
        .use('/',function(req,res){
             res.sendFile(path.join(__dirname, 'reactApp/index.html'))
            //res.sendFile(path.join(__dirname,'public/webappbeta/index.html'))
        })
    ));