Server Side Rendering Angular

img
hiprav
Hiprav WaghelaSoftware Developerauthor linkedin
Published On
Updated On
Table of Content
up_arrow

Introduction

In modern web development, performance and SEO (Search Engine Optimization) are two crucial factors that impact a website’s success. Angular, a powerful front end framework, primarily operates as a Single Page Application (SPA), which can sometimes pose challenges in terms of SEO and initial page load speed. This is where Server Side Rendering (SSR) comes into play.

In this comprehensive guide, we will explore the concept of SSR in Angular, its benefits, implementation using Angular Universal, and best practices for optimizing performance.

What is Server Side Rendering (SSR)?

Server Side Rendering (SSR) is a technique where a web page is rendered on the server instead of the client’s browser. The server sends a fully rendered HTML page to the client, which improves the initial loading speed and enhances SEO.

How SSR Differs from Client Side Rendering (CSR)?


Feature

Client Side

Server Side Rendering (SSR)

Rendering

Done in the Browser using JavaScript

Done on the Server Before sending HTML to the client

Initial Load Time

Slower due to JS execution

Faster as HTML is pre rendered

SEO Friendly?

Poor SEO(JS rendered content)

SEO friendly (content available instantly)

Interactivity

High after JS loads

Intermediate deisplay but may need hydration for interactivity


Why Use Server Side Rendering in Angular?

SSR in Angular is mainly used to tackle the challenges faced by SPAs, including:

Improved SEO

Search engines struggle to index JavaScript heavy SPAs. SSR ensures that content is fully available at the time of indexing, improving search rankings.

Faster Initial Load Time

Since HTML is pre rendered on the server, the user sees meaningful content much faster compared to CSR, where the browser must fetch and execute JavaScript first.

Better Performance on Low End Devices

Devices with limited processing power can benefit from SSR as less rendering work is required in the browser.

Improved Social Media Sharing

Social media platforms fetch metadata (title, description, and preview images) from HTML. SSR ensures that these details are correctly fetched, improving link previews.

Better Accessibility for Crawlers and Bots

SSR makes it easier for web crawlers, bots, and accessibility tools to process and interpret content, improving usability and indexing.

Preloaded Critical Resources

SSR can be optimized to preload critical resources like stylesheets, scripts, and fonts, enhancing perceived performance.

Server Side Rendering Angular

Optimizing Angular SSR Performance

While SSR improves performance, further optimizations ensure maximum efficiency:

1. Lazy Loading Modules

Lazy loading reduces the initial load time by splitting the application into smaller chunks.

ng new my-angular-ssr-app
cd my-angular-ssr-app


2: Add Angular Universal

Angular provides Angular Universal, a technology that enables SSR. To add it, run:

ng add @nguniversal/express-engine


This command:

  • Adds necessary SSR dependencies.
  • Modifies angular.json to support SSR.
  • Creates server.ts to configure an Express server.
  • Updates app.module.ts and app.server.module.ts.

3. Modify the server.ts file

The server.ts file is the entry point for SSR. Ensure it includes:

import 'zone.js/node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { existsSync } from 'fs';
import { AppServerModule } from './src/main.server';

const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/my-angular-ssr-app/browser');

app.engine('html', ngExpressEngine({ bootstrap: AppServerModule }));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

app.get('*.*', express.static(DIST_FOLDER, { maxAge: '1y' }));
app.get('*', (req, res) => {
res.render('index', { req });
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

4. Build and Serve the SSR Application

To build the application for SSR, run:

npm run build:ssr
npm run serve:ssr

Now, visit http://localhost:4000 to see your SSR Angular app in action.

Common Challenges in SSR and How to Overcome Them

Window is Undefined Error

Angular SSR runs in Node.js, where window is unavailable. Use conditional checks:

Handling Authentication

Use cookies or headers instead of localStorage for authentication, as localStorage is not accessible on the server.

Large Bundle Sizes

Use Angular’s built in tools like source map explorer to analyze and reduce bundle sizes.

if (typeof window !== 'undefined') {
console.log('Client-side code');
}


npm run build --stats-json
npx source-map-explorer dist/main.js

Conclusion

Server Side Rendering (SSR) in Angular significantly enhances performance, SEO, and user experience. By implementing SSR with Angular Universal, you can ensure faster load times, better indexing, and an overall improved application.

Key takeaways:

  • SSR helps with SEO and initial page load speeds.

  • Angular Universal is the go to tool for enabling SSR.

  • Optimizations like caching, lazy loading, and TransferState can further improve performance.

By following the best practices outlined in this guide, you can build high performance, SEO friendly Angular applications that deliver an exceptional user experience.

Schedule a call now
Start your offshore web & mobile app team with a free consultation from our solutions engineer.

We respect your privacy, and be assured that your data will not be shared