Angular ServerSide Rendering with Koa

One of my favorite features of Angular is server-side render. With server-side rendering, the client is sent a full HTML page. One that can display without any attention network request. Greatly importing the preserved load times.

https://github.com/HelixOne/koa-ssr

Angular App

To get started I used the angular-cli and ejected the webpack config. Then I created an “AppNodeModule” this will bootstrap the “AppComponent.” Creating an “AppSharedModule” is a good idea so the components can be used in both the “AppNodeModule” and the default “AppModule”

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.

Koa App

Now I created a “server.ts”. This will be the KOA app main file. To renderer, an angular app with we are going to use “renderModule” from “@angular/platform-server”. “renderModule” takes a NgModule in our case the AppNodeModule, also an object that has the index.html and the URL route. Then “renderModule” returns a promise that resolved to a string. The string we then send to the client.

“IMPORTANT”, the index.html is the built one, with the proper paths to the bundle.js and CSS files.

html = await renderModule(AppNodeModule, {

document: index,
     url: ctx.originalUrl,
});

Webpack

Starting with the “webpack.config.js” from angular-cli, I created “webpack.server.js”

The following changes are needed:

  • Set the entry points to server.ts
  • Set the entry module to “AppNodeModule
  • Set Target to node “target: ‘node’,
  • Set the outputs to “server.js