Host Angular App and NodeJS App on Same Domain

In this tutorial, we will discuss the steps to host angular app (front-end) and NodeJS App (back-end API) on same domain. The idea is that we will have a folder named as ‘public’ in the root folder of the app which will have all files associated to the angular app. The NodeJS app handles the routes for API calls (e.g http://domain.com/api/…) and authentication calls (e.g http://domain.com/auth/…) internally using the get/post methods. The remaining routes other than the ‘/api/’ and ‘/auth/’ are forwarded to the public folder containing the angular app.

Following code snippet can be used in the NodeJS app to implement the described functionality.

var app = express();
var distDir = __dirname + "/public/dist/frontend"; //change it to the folder //generated by the ng build --prod command

app.get('*.*', express.static(distDir));
app.all([ '/api/:param', '/auth/:param', '/api/users/:param' ], (req, res, next) => {
    req.isSpecial = true;
    next();
});
app.all('*', function (req, res, next) {
    if (!req.isSpecial){
        res.status(200).sendFile('/', {root: distDir});
    }else{
        next();
    }
});

The code is self explanatory. The first app.all method receives the routes for api and auth requests and make the isSpecial variable true. The next app.all method sends the requests to the public folder if the isSpecial variable is false and handle the requests internally otherwise.

Leave a Comment

Your email address will not be published.