Skip to content

Commit 6569bbc

Browse files
fix(router): remove server-rendered route meta tags after hydration (#2773)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 706a3b0 commit 6569bbc

2 files changed

Lines changed: 84 additions & 39 deletions

File tree

‎packages/router/src/lib/meta-tags.spec.ts‎

Lines changed: 39 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ describe('updateMetaTagsOnRouteChange', () => {
267267
expect(metaElements.itempropDescription).toBeNull();
268268
});
269269

270-
it('restores the original document meta tags when a route no longer sets them', async () => {
270+
function setupPages(headTag: string) {
271271
@Component({ selector: 'analogjs-meta-tags-page', template: '' })
272272
class PageComponent {}
273273

@@ -289,26 +289,48 @@ describe('updateMetaTagsOnRouteChange', () => {
289289
provideAppInitializer(() => updateMetaTagsOnRouteChange()),
290290
],
291291
});
292-
const router = TestBed.inject(Router);
293292
const document = TestBed.inject(DOCUMENT);
294-
const indexDescription = document.createElement('meta');
295-
indexDescription.name = 'description';
296-
indexDescription.content = 'Index Description';
297-
document.head.appendChild(indexDescription);
293+
document.head.insertAdjacentHTML('beforeend', headTag);
294+
const getDescriptions = () =>
295+
Array.from(
296+
document.querySelectorAll('meta[name="description"]'),
297+
(meta) => meta.getAttribute('content'),
298+
);
299+
300+
return { router: TestBed.inject(Router), getDescriptions };
301+
}
302+
303+
it('restores the original document meta tags when a route no longer sets them', async () => {
304+
const { router, getDescriptions } = setupPages(
305+
'<meta name="description" content="Index Description">',
306+
);
298307

299308
await router.navigateByUrl('/');
300-
expect(
301-
document
302-
.querySelector('meta[name="description"]')
303-
?.getAttribute('content'),
304-
).toBe('Home Description');
309+
expect(getDescriptions()).toEqual(['Home Description']);
305310

306311
await router.navigateByUrl('/about');
307-
expect(
308-
Array.from(
309-
document.querySelectorAll('meta[name="description"]'),
310-
(meta) => meta.getAttribute('content'),
311-
),
312-
).toEqual(['Index Description']);
312+
expect(getDescriptions()).toEqual(['Index Description']);
313+
});
314+
315+
it('removes server-rendered route meta tags after hydration', async () => {
316+
const { router, getDescriptions } = setupPages(
317+
'<meta name="description" content="Home Description" data-analog-route-meta="">',
318+
);
319+
320+
await router.navigateByUrl('/');
321+
await router.navigateByUrl('/about');
322+
323+
expect(getDescriptions()).toEqual([]);
324+
});
325+
326+
it('restores document meta tags replaced during server rendering', async () => {
327+
const { router, getDescriptions } = setupPages(
328+
`<meta name="description" content="Home Description" data-analog-route-meta='{"name":"description","content":"Index Description"}'>`,
329+
);
330+
331+
await router.navigateByUrl('/');
332+
await router.navigateByUrl('/about');
333+
334+
expect(getDescriptions()).toEqual(['Index Description']);
313335
});
314336
});

‎packages/router/src/lib/meta-tags.ts‎

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const NAME_KEY = 'name';
1515
const PROPERTY_KEY = 'property';
1616
const CONTENT_KEY = 'content';
1717
const ITEMPROP_KEY = 'itemprop';
18+
const ROUTE_META_ATTR = 'data-analog-route-meta';
1819

1920
export type MetaTag =
2021
| (CharsetMetaTag & ExcludeRestMetaTagKeys<typeof CHARSET_KEY>)
@@ -52,43 +53,65 @@ export function updateMetaTagsOnRouteChange(
5253
router: Router = inject(Router),
5354
metaService: Meta = inject(Meta),
5455
): void {
55-
const originalTags = new Map<string, HTMLMetaElement | null>();
56-
5756
router.events
5857
.pipe(filter((event) => event instanceof NavigationEnd))
5958
.subscribe(() => {
6059
const metaTagMap = getMetaTagMap(router.routerState.snapshot.root);
61-
62-
for (const [metaTagSelector, originalTag] of originalTags) {
63-
if (metaTagSelector in metaTagMap) {
64-
continue;
65-
}
66-
67-
if (originalTag) {
68-
metaService.getTag(metaTagSelector)?.replaceWith(originalTag);
69-
} else {
70-
metaService.removeTag(metaTagSelector);
60+
const metaTagSelectors = Object.keys(metaTagMap);
61+
62+
for (const ownedTag of metaService.getTags(ROUTE_META_ATTR)) {
63+
if (
64+
!metaTagSelectors.some((selector) =>
65+
ownedTag.matches(`meta[${selector}]`),
66+
)
67+
) {
68+
releaseMetaTag(ownedTag, metaService);
7169
}
72-
originalTags.delete(metaTagSelector);
7370
}
7471

7572
for (const metaTagSelector in metaTagMap) {
76-
if (!originalTags.has(metaTagSelector)) {
77-
const originalTag = metaService.getTag(metaTagSelector);
78-
originalTags.set(
79-
metaTagSelector,
80-
(originalTag?.cloneNode() as HTMLMetaElement | undefined) ?? null,
81-
);
82-
}
83-
73+
const existingTag = metaService.getTag(metaTagSelector);
74+
const originalAttributes =
75+
existingTag?.getAttribute(ROUTE_META_ATTR) ??
76+
serializeAttributes(existingTag);
8477
const metaTag = metaTagMap[
8578
metaTagSelector as MetaTagSelector
8679
] as NgMetaTag;
87-
metaService.updateTag(metaTag, metaTagSelector);
80+
metaService
81+
.updateTag(metaTag, metaTagSelector)
82+
?.setAttribute(ROUTE_META_ATTR, originalAttributes);
8883
}
8984
});
9085
}
9186

87+
function serializeAttributes(tag: HTMLMetaElement | null): string {
88+
if (!tag) {
89+
return '';
90+
}
91+
92+
return JSON.stringify(
93+
Object.fromEntries(
94+
tag.getAttributeNames().map((name) => [name, tag.getAttribute(name)]),
95+
),
96+
);
97+
}
98+
99+
function releaseMetaTag(tag: HTMLMetaElement, metaService: Meta): void {
100+
const originalAttributes = tag.getAttribute(ROUTE_META_ATTR);
101+
if (!originalAttributes) {
102+
metaService.removeTagElement(tag);
103+
return;
104+
}
105+
106+
for (const name of tag.getAttributeNames()) {
107+
tag.removeAttribute(name);
108+
}
109+
const attributes: Record<string, string> = JSON.parse(originalAttributes);
110+
for (const [name, value] of Object.entries(attributes)) {
111+
tag.setAttribute(name, value);
112+
}
113+
}
114+
92115
function getMetaTagMap(route: ActivatedRouteSnapshot): MetaTagMap {
93116
const metaTagMap = {} as MetaTagMap;
94117
let currentRoute: ActivatedRouteSnapshot | null = route;

0 commit comments

Comments
 (0)