Prerendering Prerender with Angular Universal using a vanilla JS script

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
SignUp for Unlimited PRO Access


*Enrollment provides full access to this course (and updates) for life.

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_official 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');

Q&A Chat