If you are like me i am a big fan of generators. It makes lifes of us developers easier, by easily generating the boiler plate code. For angular 2, the recommended generator comes from google Angular-cli. You can very quickly create a client side project using the cli. It by default comes with a server lite-server, which is basically some wrapper on browser-sync to serve index.html on any route. Well this is fine if you don’t have need for server side code, but most projects do need server side code.

There are different ways to have server side code. You can maintain it in a completely new project. You can serve the angular 2 code from nginx or apache and proxy in the server side URLs to avoid CORS issues. Another way of doing it keep both the server side and client side in one project and use express to serve them. In this post i am going to talk about setting up express to serve angular 2 code generated by cli.

These are the steps to get express setup with cli in 5 minutes

Follow the steps mentioned in Angular-cli to setup a new angular 2 project. Once done go to root of the folder and install express (and its nice to haves) using npm install express --save npm install cookie-parser body-parser morgan --save Add a file called app.js under src. Add the following code to your app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(__dirname)); app.get('/*', function (req, res) { res.sendFile(path.join(__dirname,'index.html')); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); if (app.get('env') === 'development') { app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); } else{ app.listen(8080, function () { console.log('Example app listening on port 8080!'); }); } module.exports = app; In the above code i am initializing a standard express server , and using the current directory (where all your ng 2 code is) as the static directory. As you can see the app.get on /* redirect requests to the index.html which is the starting point for your ng 2 app. run ng build which will create the dist folder, and you will see the app.js in your dist folder. start the server using node dist/app . Open the browser and go to http://localhost:3000 and vola you have your angular 2 app served by express.