Angular 17 and SEO: Server-Side Rendering (SSR) Optimization

Search Engine Optimization (SEO) stands as a vital pillar in the realm of web development, notably when employing cutting-edge frameworks like Angular. With Angular 17, enhanced by the capabilities of Server-Side Rendering (SSR) through Angular SSR, developers have access to robust tools for elevating their application's visibility on search engines. This article is designed to serve as an in-depth tutorial on mastering SEO techniques specifically tailored for Angular SSR in its latest iteration, version 17.
Boosting SEO with Angular SSR: What you need to know
Angular SSR is a game-changer for improving your Angular app's search engine rankings. Here's why it works so well:
- Better Visibility for Search Engines: Angular SSR makes your website ready for search engines right off the bat by serving pages that are already fully made. This helps your site get noticed by search engines faster and easier.
- Quicker Loading Pages: It creates pages on the server before they even reach the user’s browser. This means users see your pages quicker because they don't have to wait as long for the site to start up. Fast-loading pages are great for SEO as search engines prefer websites that load quickly.
- Improved User Experience: Angular SSR delivers content quickly, making your website feel snappier, especially for people with slow internet or older devices. Since search engines rank user-friendly websites higher, this can help improve your SEO.
- Reduced JavaScript Reliance: While search engines are getting better at handling JavaScript, having too much of it can still slow things down. Angular SSR helps by handling a lot of the heavy lifting on the server, which means there's less work for the browser to do and less chance of running into issues.
- Better Social Media Sharing: When you share a link on social media, you want it to look good with a proper preview image and description. Angular SSR helps ensure that your shared links always look appealing because it includes all the needed details right in the HTML. This makes your posts more engaging and consistent across social platforms.
How SSR works with Angular 17?
- Request Handling: When a user visits a webpage using Angular with SSR, their browser sends a request directly to the server. Unlike traditional client-side rendering, the server handles this initial request.
- Server Executes Angular: Angular is executed on the server, where it processes the request, handles routing, and generates the components necessary for rendering the requested page. This includes executing logic and fetching any dynamic data needed for the components.
- HTML Rendering: The server then renders these components into HTML, incorporating all dynamic content. This complete HTML represents the fully formed page as it would appear after initial rendering by the browser in a client-side setup.
- State Transfer: To optimize performance and reduce duplicate data fetching, Angular includes a Transfer State feature. This mechanism allows the server to pass the state of the app (i.e., the data already fetched and used for server-side rendering) to the client. This state is serialized and embedded in the HTML as a script tag.
- Response Delivery: The pre-rendered HTML, along with the serialized state, is sent back to the client. This ensures that the user sees a fully loaded page immediately, significantly enhancing perceived load speed.
- Browser Hydration: Once the HTML and state are received, the client-side Angular application starts up and 'hydrates' the static content. During hydration, Angular reads the transferred state to initialize the client-side application to the same state as the server without needing to re-fetch the data.
- Client-Side Angular Activation: After hydration, Angular on the client side handles all subsequent user interactions and navigation, operating as a typical single-page application (SPA). This client-side Angular can utilize the state transferred from the server to avoid unnecessary API calls, thereby improving efficiency and response times.
Enable server-side rendering
To create a new application with SSR, run:
ng new --ssr
To add SSR to an existing project, use the Angular CLI ng add
command.
ng add @angular/ssr
Implementing SEO techniques with Angular 17
Use Semantic HTML
Semantic HTML helps search engines understand the structure and content of your web pages. With Angular, ensure your components use the correct HTML elements for headers, lists, and other structures.
Example:
<!-- Use semantic tags in your Angular components -->
<h1>Main Title of the Page</h1>
<p>Description or introductory content.</p>
<article>
<h2>Article Title</h2>
<p>Article content...</p>
</article>
Dynamic Meta Tags
Meta tags provide metadata about the HTML document that are used by search engines to display previews and understand content relevance. Angular's Meta service can dynamically manage meta tags based on the route or content viewed.
Example:
import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
@Component({
selector: 'app-home-page',
template: `<p>Welcome to our home page</p>`
})
export class HomePageComponent implements OnInit {
constructor(private meta: Meta, private titleService: Title) {}
ngOnInit() {
this.titleService.setTitle('Home Page - My Angular App');
this.meta.updateTag({ name: 'description', content: 'Learn more about our Angular app!' });
this.meta.updateTag({ name: 'keywords', content: 'Angular, SEO, Example' });
}
}
Structured Data
Structured data is a standardized format to provide information about a page and classify the page content. Use JSON-LD to add structured data, which helps search engines better understand the content of your site and provide rich snippets.
Example:
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Organization",
"name": "My Angular App",
"url": "https://www.myangularapp.com"
}
</script>
Optimize Route Configurations
Angular's router allows you to set path titles and metadata, which can be dynamically adjusted to improve SEO. Using route data to modify page titles and metadata ensures each page is uniquely optimized.
Example:
// In your routing module
{ path: 'about', component: AboutComponent, data: { title: 'About Us', description: 'Learn more about our team and mission.' } }
Link and Resource Optimization
Ensure that your Angular app uses <a href="...">
tags for navigation instead of JavaScript-only triggers, which helps search engines crawl your site more effectively. Also, ensure that static resources like images and CSS are optimizable and cacheable.
Optimizing Asynchronous Data Fetching
Asynchronous data fetching can be optimized by using Angular SSR for Server-Side Rendering. Ensure that data used to render your pages is fetched during server-side execution, so that search engines see the fully rendered page with all necessary content on the initial load.
Example:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey } from '@angular/core';
const DATA_KEY = makeStateKey('data');
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient, private transferState: TransferState) {}
getData() {
const existingData = this.transferState.get(DATA_KEY, null);
if (existingData) {
return of(existingData);
} else {
return this.http
.get('https://api.example.com/data')
.pipe(
tap(data => this.transferState.set(DATA_KEY, data))
);
}
}
}
Handling Canonical URLs
Canonical URLs prevent issues related to duplicate content, which can harm your SEO. Set a canonical URL for each page to help search engines understand which version of a page is the definitive one.
Example:
<link rel="canonical" href="https://www.yoursite.com/current-page-url" />
SEO-Friendly URLs and Redirects
Use Angular's router to create clean, readable URLs that are easy for both users and search engines to understand. Also, manage redirects properly to maintain SEO value.
Example:
{ path: 'old-page', redirectTo: '/new-page', pathMatch: 'full' }
Server-Side Redirects and HTTP Status Codes
Managing HTTP status codes properly, including setting 301 for permanent redirects and 404 for not found pages, is crucial for SEO. Implement these in your server-side logic.
In Angular 17 tokens express Request and Response are not exported anymore by @angular/ssr
. You can do it by creating the file express.tokens.ts
in src
folder of your Angular project with following content:
import { InjectionToken } from '@angular/core';
import { Request, Response } from 'express';
export const REQUEST = new InjectionToken<Request>('REQUEST');
export const RESPONSE = new InjectionToken<Response>('RESPONSE');
And you need to provide them in server.ts
:
import {RESPONSE} from "./src/express.tokens";
import {REQUEST} from "./src/express.tokens";
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
...
// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: RESPONSE, useValue: res },
{ provide: REQUEST, useValue: req }
],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
...
Configure route for your 404 page
{ path: '404', component: ErrorNotFoundComponents },
{ path: '**', redirectTo: '/404' }
Create component for your 404 page
import {Component, Inject, OnInit, Optional, PLATFORM_ID} from "@angular/core";
import {isPlatformServer} from "@angular/common";
import {RESPONSE} from "../../../../express.tokens";
import { Response } from 'express';
@Component({
selector: 'app-error-not-found',
templateUrl: './error-not-found.component.html',
styleUrls: ['./error-not-found.component.scss'],
standalone: true
})
export class ErrorNotFoundComponents implements OnInit {
constructor(@Inject(PLATFORM_ID) private platformId: any,
@Optional() @Inject(RESPONSE) private response: Response) {
}
ngOnInit() {
if (isPlatformServer(this.platformId)) {
if (this.response) {
this.response.status(404);
}
}
}
}
Conclusion
In conclusion, embracing Server-Side Rendering with Angular 17 presents a significant opportunity for developers to enhance their web applications' performance and SEO. By delivering fully rendered pages from the server, Angular SSR not only improves the load times and user experience but also ensures that search engines can more effectively index and rank the site. This article has outlined the key strategies to implement SSR effectively, from managing dynamic content and optimizing route configurations to handling meta tags and improving resource accessibility. As web technologies continue to evolve, staying abreast of these advancements and applying them judiciously will be pivotal in maintaining a competitive edge in search engine rankings. By adopting the practices discussed, developers can ensure their Angular applications are not only performant and user-friendly but also well-optimized for search engines.