Blog>
Snippets

Implementing Server-Side Rendering with Angular Universal

Present an example of setting up Angular Universal for server-side rendering to send pre-rendered pages to the client, enhancing mobile load times and SEO.
npm install @nguniversal/express-engine --save
Install the required packages for Angular Universal, which includes the '@nguniversal/express-engine' package for server-side rendering with Express.
ng add @nguniversal/express-engine --clientProject angular-universal-example
Use the Angular CLI to add Angular Universal to your project, specifying the client project name if it is different from the default.
const express = require('express');
const ngUniversal = require('@nguniversal/express-engine');
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

const app = express();
const port = process.env.PORT || 4000;
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

app.engine('html', ngUniversal.ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [provideModuleMap(LAZY_MODULE_MAP)]
}));

app.set('view engine', 'html');
app.set('views', 'dist/browser');

app.get('*.*', express.static('dist/browser', {
  maxAge: '1y'
}));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(port, () => {
  console.log(`Listening on http://localhost:${port}`);
});
Create a simple Express server that uses Angular Universal for rendering Angular applications server-side. We set up an engine for '.html' files to use the ngExpressEngine with AppServerModuleNgFactory and the lazy loading map. Static files are served from the 'dist/browser' directory, and all other requests are rendered server-side and returned as HTML responses.
npm run build:ssr && npm run serve:ssr
Build the server-side rendered version of the application and then serve it using Node.js.