📂 Prerendering

Prerender with Angular Universal using a vanilla JS script

Create a script that can prerender specific routes using Angular Universal.

Note, make sure you have enabled Universal with the schematic from the previous video or with ng add @nestjs/ng-universal.

command line
npm install --save-dev fs-extra http-server@0.9.0

package.json Scripts

Add the following scripts to your package.json.

file_type_npm package.json
    // ...
"scripts": {
    "build:prerender": "npm run build:client-and-server-bundles && node prerender.js",
    "serve:prerender": "http-server dist/browser -c-1"

Prerender Script

file_type_js prerender.js

const { join } = require('path');

const { enableProdMode } = require('@angular/core');

// Import module map for lazy loading
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

const { renderModuleFactory } = require('@angular/platform-server');

// leave this as require(), imported via webpack
const {
} = require(`./dist/server/main`);

const fs = require('fs-extra');

// Must manually define routes to prerender
const ROUTES = [

// START prerender script

(async function() {
  // Get the app index
  const views = 'dist/browser';
  const index = await fs.readFile(join(views, 'index.html'), 'utf8');

  // Loop over each route
  for (const route of ROUTES) {
    const pageDir = join(views, route);
    await fs.ensureDir(pageDir);

    // Render with Universal
    const html = await renderModuleFactory(AppServerModuleNgFactory, {
      document: index,
      url: route,
      extraProviders: [provideModuleMap(LAZY_MODULE_MAP)]

    await fs.writeFile(join(pageDir, 'index.html'), html);

  console.log('prerendering complete');

Questions? Let's chat

Open Discord