Skip to content

feat(blog): handle link hreflang tags #454

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions libs/blog-contracts/articles/src/lib/articles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,8 @@ export const articleLangToLocaleMap = {
[DbLang.English]: 'en_GB',
[DbLang.Polish]: 'pl_PL',
} as const satisfies Record<DbLang, ArticleLocale>;

export const articleLocaleToLangMap = {
en_GB: 'en',
pl_PL: 'pl',
} as const satisfies Record<ArticleLocale, Lang>;
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { filter, pipe, switchMap, tap } from 'rxjs';

import { withLangState } from '@angular-love/blog/i18n/data-access';
import { Article } from '@angular-love/contracts/articles';
import { withSeo } from '@angular-love/seo';
import {
Article,
articleLocaleToLangMap,
} from '@angular-love/contracts/articles';
import { HreflangEntry, withSeo } from '@angular-love/seo';
import {
LoadingState,
withCallState,
Expand Down Expand Up @@ -72,6 +75,16 @@ export const ArticleDetailsStore = signalStore(
next: (articleDetails) => {
store.setMeta(articleDetails.seo);
store.setTitle(articleDetails.seo.title);

const hreflangEntries =
buildArticleHreflangEntries(articleDetails);

if (hreflangEntries) {
store.setHreflang(hreflangEntries);
} else {
store.clearHreflang();
}

return patchState(store, {
articleDetails,
slug: slug,
Expand All @@ -93,3 +106,29 @@ export const ArticleDetailsStore = signalStore(
}),
})),
);

export function buildArticleHreflangEntries(
article: Article,
): HreflangEntry[] | null {
if (!article.otherTranslations || article.otherTranslations.length < 2) {
return null;
}

return article.otherTranslations.map((translation) => {
const langCode = articleLocaleToLangMap[translation.locale];
const url = buildArticlePath(translation.slug, langCode);

return {
locale: langCode,
url: url,
} satisfies HreflangEntry;
});
}
Comment on lines +110 to +126
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Missing current article language in hreflang entries

The hreflang implementation should include ALL language versions of the article, including the current one. Currently, it only maps otherTranslations which excludes the current article's language.

Additionally, the length check seems incorrect. If otherTranslations contains only other languages, you'd want hreflang entries even with 1 translation (current + 1 other = 2 languages total).

export function buildArticleHreflangEntries(
  article: Article,
): HreflangEntry[] | null {
-  if (!article.otherTranslations || article.otherTranslations.length < 2) {
+  if (!article.otherTranslations || article.otherTranslations.length === 0) {
    return null;
  }

-  return article.otherTranslations.map((translation) => {
+  // Include current article
+  const allTranslations = [
+    { locale: article.language, slug: article.slug },
+    ...article.otherTranslations,
+  ];
+
+  return allTranslations.map((translation) => {
    const langCode = articleLocaleToLangMap[translation.locale];
    const url = buildArticlePath(translation.slug, langCode);

    return {
      locale: langCode,
      url: url,
    } satisfies HreflangEntry;
  });
}

Note: You'll need to verify that article.language type matches ArticleLocale for the mapping to work correctly.

🤖 Prompt for AI Agents
In libs/blog/articles/data-access/src/lib/state/article-details.store.ts around
lines 110 to 126, the function buildArticleHreflangEntries only includes
otherTranslations and excludes the current article language, and the length
check incorrectly requires at least 2 other translations. Modify the function to
include the current article's language and URL in the hreflang entries along
with otherTranslations, and adjust the length check to allow hreflang entries
when there is at least one other translation. Also, verify that article.language
matches the expected locale type for the mapping to work correctly.


function buildArticlePath(slug: string, langCode: string): string {
if (langCode === 'en') {
return `/${slug}`;
}

return `/${langCode}/${slug}`;
}
8 changes: 4 additions & 4 deletions libs/blog/articles/feature-shell/src/lib/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const articleRoutes: Routes = [
(await import('@angular-love/blog/articles/feature-category'))
.CategoryArticlesComponent,
data: {
seo: { title: 'News' },
seo: { title: 'News', autoHrefLang: true },
category: 'news',
title: 'Angular News',
id: 'angular-news',
Expand All @@ -25,7 +25,7 @@ export const articleRoutes: Routes = [
(await import('@angular-love/blog/articles/feature-category'))
.CategoryArticlesComponent,
data: {
seo: { title: 'Guides' },
seo: { title: 'Guides', autoHrefLang: true },
category: 'guides',
title: 'Angular Guides',
id: 'angular-guides-title',
Expand All @@ -37,7 +37,7 @@ export const articleRoutes: Routes = [
(await import('@angular-love/blog/articles/feature-category'))
.CategoryArticlesComponent,
data: {
seo: { title: 'Latest Articles' },
seo: { title: 'Latest Articles', autoHrefLang: true },
excludeCategory: 'angular-in-depth-en',
title: 'Latest Articles',
id: 'latest-articles',
Expand All @@ -49,7 +49,7 @@ export const articleRoutes: Routes = [
(await import('@angular-love/blog/articles/feature-category'))
.CategoryArticlesComponent,
data: {
seo: { title: 'Angular In Depth' },
seo: { title: 'Angular In Depth', autoHrefLang: true },
category: 'angular-in-depth',
title: 'Angular In Depth',
id: 'angular-in-depth-title',
Expand Down
78 changes: 77 additions & 1 deletion libs/blog/shared/util-seo/src/lib/services/seo.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@ import { inject, Injectable } from '@angular/core';
import { Meta, MetaDefinition, Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { TranslocoService } from '@jsverse/transloco';
import { filter, map, switchMap } from 'rxjs';
import { filter, map, switchMap, take } from 'rxjs';

import { AlLocalizeService } from '@angular-love/blog/i18n/util';
import { SeoMetaData } from '@angular-love/contracts/articles';

import { SEO_CONFIG } from '../tokens';

import { SEO_META_KEYS, SeoMetaKeys } from './seo-meta-keys';
import { SEO_TITLE_KEYS, SeoTitleKeys } from './seo-title-keys';

export interface HreflangEntry {
locale: string;
url: string;
}

@Injectable()
export class SeoService {
private readonly _router = inject(Router);
Expand All @@ -21,7 +27,9 @@ export class SeoService {
private readonly _document = inject(DOCUMENT);
private readonly _seoConfig = inject(SEO_CONFIG);
private readonly _translocoService = inject(TranslocoService);
private readonly _localizeService = inject(AlLocalizeService);
private _url = '';
private _baseUrl = '';

init(): void {
this._router.events
Expand All @@ -41,6 +49,7 @@ export class SeoService {
)
.subscribe(({ routeData, seoConfig }) => {
this._url = this.getUrl(seoConfig.baseUrl, this._router.url);
this._baseUrl = seoConfig.baseUrl;

this.removeSeo();

Expand All @@ -57,6 +66,10 @@ export class SeoService {
}

this.handleCanonicalUrl(this._url);

if (routeData && routeData['seo'] && routeData['seo']['autoHrefLang']) {
this.handleAutoHreflang(seoConfig.baseUrl, this._router.url);
}
});
}

Expand Down Expand Up @@ -125,6 +138,31 @@ export class SeoService {
this.updateTag(title, 'name');
}

setHreflang(hreflangEntries: HreflangEntry[]): void {
this.removeHreflangTags();

for (const entry of hreflangEntries) {
const fullUrl = entry.url.startsWith('http')
? entry.url
: `${this._baseUrl}${entry.url}`;
this.appendHreflangLink(entry.locale, fullUrl);
}

const defaultEntry =
hreflangEntries.find((entry) => entry.locale === 'en') ||
hreflangEntries[0];
if (defaultEntry) {
const defaultUrl = defaultEntry.url.startsWith('http')
? defaultEntry.url
: `${this._baseUrl}${defaultEntry.url}`;
this.appendHreflangLink('x-default', defaultUrl);
}
}

clearHreflang(): void {
this.removeHreflangTags();
}

private setMetaTwitterMisc(miscData: object): void {
const entries = Object.entries(miscData);

Expand Down Expand Up @@ -204,6 +242,44 @@ export class SeoService {
}
},
);

this.removeHreflangTags();
}

private handleAutoHreflang(baseUrl: string, currentPath: string): void {
const availableLanguages =
this._translocoService.getAvailableLangs() as string[];
const hreflangEntries: HreflangEntry[] = [];

for (const lang of availableLanguages) {
const localizedPath = this._localizeService.localizeExplicitPath(
currentPath,
lang,
);
const fullUrl = `${baseUrl}${localizedPath}`;

hreflangEntries.push({
locale: lang,
url: fullUrl,
});
}

this.setHreflang(hreflangEntries);
}

private appendHreflangLink(hreflang: string, href: string): void {
const link = this._document.createElement('link');
link.setAttribute('rel', 'alternate');
link.setAttribute('hreflang', hreflang);
link.setAttribute('href', href);
this._document.head.appendChild(link);
}

private removeHreflangTags(): void {
const hreflangLinks = this._document.head.querySelectorAll(
'link[rel="alternate"][hreflang]',
);
hreflangLinks.forEach((link) => link.remove());
}

private handleCanonicalUrl(url: string): void {
Expand Down
8 changes: 7 additions & 1 deletion libs/blog/shared/util-seo/src/lib/state/seo.store-feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { signalStoreFeature, withMethods } from '@ngrx/signals';

import { SeoMetaData } from '@angular-love/contracts/articles';

import { SeoService } from '../services';
import { HreflangEntry, SeoService } from '../services';

export function withSeo() {
return signalStoreFeature(
Expand All @@ -14,6 +14,12 @@ export function withSeo() {
setTitle(title: string | undefined): void {
seoService.setTitle(title);
},
setHreflang(hreflangEntries: HreflangEntry[]): void {
seoService.setHreflang(hreflangEntries);
},
clearHreflang(): void {
seoService.clearHreflang();
},
})),
);
}
12 changes: 9 additions & 3 deletions libs/blog/shell/feature-shell-web/src/lib/blog-shell.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const commonRoutes: Route[] = [
(await import('@angular-love/blog/home/feature-home'))
.HomePageComponent,
data: {
seo: { title: 'seo.home' },
seo: { title: 'seo.home', autoHrefLang: true },
},
},
{
Expand All @@ -48,22 +48,25 @@ export const commonRoutes: Route[] = [
(await import('@angular-love/feature-about-us'))
.FeatureAboutUsComponent,
data: {
seo: { title: 'seo.aboutUs' },
seo: { title: 'seo.aboutUs', autoHrefLang: true },
},
},
{
path: 'author/:authorSlug',
loadComponent: async () =>
(await import('@angular-love/blog/authors/feature-author'))
.FeatureAuthorComponent,
data: {
seo: { autoHrefLang: true },
},
},
{
path: 'become-author',
loadComponent: async () =>
(await import('@angular-love/blog/become-author-page-feature'))
.BecomeAuthorPageFeatureComponent,
data: {
seo: { title: 'seo.becomeAuthor' },
seo: { title: 'seo.becomeAuthor', autoHrefLang: true },
},
},
{
Expand All @@ -77,6 +80,9 @@ export const commonRoutes: Route[] = [
loadComponent: async () =>
(await import('@angular-love/blog/feature-writing-rules'))
.WritingRulesComponent,
data: {
seo: { autoHrefLang: true },
},
},
{
path: '404',
Expand Down