Getting Started

Initial Set Up

There are many different potential configurations for Angular Universal. For this QuickStart, we are going to focus on the most common setup which includes:

  • Angular 2 (obviously!)
  • Node.js back end
  • Webpack

So, make sure you download and install Node.js before getting started.

1. Angular 2 App

We won't go over how to create a basic Angular 2 app in this guide. If you don't already have an Angular 2 app, then use the Angular 2 Webpack Starter.

2. Install Dependencies

In the root directory of your project run the following commands:

> npm install body-parser angular2-universal preboot express --save
> typings install node express body-parser serve-static express-serve-static-core mime --ambient

3. Add a Server

Create a file called server.js in the root of your application with the following code. Read through the comments in this code and make the appropriate adjustments to work with your Angular 2 app.

// These polyfills must be the first thing imported in node

import 'angular2-universal/polyfills';
import * as path from 'path';
import * as express from 'express';

// Angular 2 Universal
import {provideRouter} from '@angular/router';
import {enableProdMode} from '@angular/core';
import {
} from 'angular2-universal';

// replace this line with your Angular 2 root component
import {App, routes} from './app';

const app = express();
const ROOT = path.join(path.resolve(__dirname, '..'));


// Express View
app.engine('.html', expressEngine);
app.set('views', __dirname);
app.set('view engine', 'html');

function ngApp(req, res) {
  let baseUrl = '/';
  let url = req.originalUrl || '/';

  let config: ExpressEngineConfig = {
    directives: [ App ],

    // dependencies shared among all requests to server
    platformProviders: [
      {provide: ORIGIN_URL, useValue: 'http://localhost:3000'},
      {provide: BASE_URL, useValue: baseUrl},

    // dependencies re-created for each request
    providers: [
      {provide: REQUEST_URL, useValue: url},

    // if true, server will wait for all async to resolve before returning response
    async: true,

    // if you want preboot, you need to set selector for the app root
    // you can also include various preboot options here (explained in separate document)
    preboot: false // { appRoot: 'app' }

  res.render('index', config);

// Serve static files
app.use(express.static(ROOT, {index: false}));

// send all requests to Angular Universal
// if you want Express to handle certain routes (ex. for an API) make sure you adjust this
app.get('/', ngApp);
app.get('/home', ngApp);
app.get('/about', ngApp);

// Server
app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');

4. Start the Server

> node server.js