Repository navigation
feat: render hreflang alternates in page head for translated content - #1907
Conversation
Multilingual SEO previously stopped at the sitemap: translation siblings were cross-linked with xhtml alternates there, but rendered pages carried no hreflang annotations in their <head>. Add a getHreflangAlternates() helper that resolves the alternate set for a content entry with the same semantics as the sitemap route: one alternate per published translation sibling (including a self-referencing entry, per Google's recommendation), x-default on the default-locale variant (falling back to the first routable variant), unroutable locales dropped, drafts excluded, and an empty result when i18n is disabled (no queries run). URLs are built from the collection's urlPattern and localized through the Astro i18n routing config, so head and sitemap always agree. EmDashHead emits the links automatically when the page context carries a content reference, as base-layer contributions so plugins can override individual hreflang entries. The helper is also exported from "emdash" and "emdash/seo" for hand-rolled heads, with a *WithDb variant for callers that already hold a database handle. Result resolution is request-cached. Fixes emdash-cms#1690
🦋 Changeset detectedLatest commit: ddb4fb8 The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
The approach is sound: this adds the missing render-path hreflang piece on top of the existing i18n/URL-resolution helpers, keeps the public API minimal, request-caches the lookup, and emits the links through the established PageMetadataContribution pipeline. The code is well-tested for the helper and follows the package's import/export conventions.
The one real concern is a semantic gap versus the sitemap. The PR states that head and sitemap should "always agree," but getHreflangAlternatesWithDb only filters on status === "published" while handleSitemapData also respects _emdash_collections.has_seo and _emdash_seo.seo_no_index. That means a page marked noindex (or a collection with SEO disabled) will still emit self-referencing hreflang alternates in <EmDashHead>, which contradicts the noindex directive and the sitemap. It's a concrete SEO-correctness bug, not just an implementation detail.
I also noted that the helper falls back to settings.url without verifying it is absolute; a relative value silently produces invalid hreflang URLs in manual usage.
| let variants = await repo.findTranslations(collection, group); | ||
| if (variants.length === 0) variants = [item]; | ||
|
|
||
| const published = variants.filter((v) => v.status === "published"); |
There was a problem hiding this comment.
[needs fixing] The published filter only checks status === "published", so it diverges from the sitemap semantics the PR claims to mirror. handleSitemapData excludes collections with has_seo = 0 and entries whose _emdash_seo.seo_no_index = 1. A noindex page rendered by <EmDashHead> would therefore still emit self-referencing rel="alternate" links, sending search engines a contradictory signal.
Add the same _emdash_seo check the sitemap uses (or share the sitemap query logic) so that head and sitemap cannot disagree on which variants are discoverable.
There was a problem hiding this comment.
Fixed in ddb4fb8 — the alternate set now applies the same _emdash_seo filter as the sitemap: variants with seo_no_index = 1 are excluded via a batch lookup, and when the requested entry itself is noindex the helper returns an empty set (a page opting out of indexing shouldn't announce an hreflang set at all). Entries without an _emdash_seo row stay indexable by default, so has_seo = 0 collections behave consistently too. Two new tests cover the sibling-exclusion and self-noindex cases.
| const settings = await getSiteSettingsWithDb(db); | ||
| siteUrl = settings.url; | ||
| } | ||
| if (!siteUrl) return []; |
There was a problem hiding this comment.
[suggestion] This accepts any truthy siteUrl, including relative values from settings.url. A relative site URL yields invalid hreflang output like example.com/fr/blog/... and, in <EmDashHead>, the link is silently dropped by resolvePageMetadata's isSafeHref check. Validate that the resolved URL uses an absolute http(s):// scheme before stripping the trailing slash.
| if (!siteUrl) return []; | |
| if (!siteUrl || !/^https?:\/\//i.test(siteUrl)) return []; |
There was a problem hiding this comment.
Fixed in ddb4fb8 — the resolved site URL is now validated against ^https?:\/\//i before use; relative values (from settings or the option) yield an empty result instead of malformed alternates. Added a test for the relative-URL case.
Match the sitemap's _emdash_seo filter: variants flagged noindex are excluded from alternate sets, and a noindex entry emits no hreflang set at all, so head and sitemap can't disagree on which variants are discoverable. Also reject relative site URLs — hreflang requires fully-qualified URLs, and EmDashHead's isSafeHref would silently drop the malformed links.
What does this PR do?
Implements render-path hreflang alternates for translated content, per the acceptance criteria in #1690. Multilingual SEO previously stopped at the sitemap — translation siblings were cross-linked there, but rendered pages carried no
hreflangannotations in their<head>.Closes #1690
What's added:
getHreflangAlternates(collection, entryId, { siteUrl })— a public helper (exported fromemdashandemdash/seo, with a*WithDbvariant for callers that already hold a database handle) that resolves the alternate set for a content entry. Result resolution is request-cached.<EmDashHead>— when i18n is enabled and the page context carries acontentreference, it emits one<link rel="alternate" hreflang="...">per variant plusx-default. The links join the contribution pipeline at the base layer, so plugins can override individual hreflang entries (the existing dedup key is the hreflang value). Non-i18n sites skip this entirely — zero extra queries.Semantics deliberately mirror the sitemap route so head and sitemap always agree:
x-defaultpoints at the default-locale variant, falling back to the first routable variant when the default locale has no translation.i18n.localesare dropped — linking search engines to an unservable route is worse than no link.x-defaultwhen i18n is enabled (matching sitemap behaviour).urlPatternand localized through the resolved Astro i18n routing config (prefixDefaultLocale, custom localepathmappings), via the sameinterpolateUrlPattern/localizePathhelpers the sitemap uses.Acceptance criteria mapping: content pages emit
rel=alternateper translation (EmDashHead + helper) ✓ ·x-defaultdocumented and implemented consistently with the sitemap ✓ · locale routing honours Astro and EmDash i18n config (localizePath) ✓ · missing/unroutable translations handled safely (dropped; empty result for missing entries) ✓ · tests cover translated and untranslated entries ✓.Documentation: new "hreflang Alternates in the Page Head" section in the internationalization guide, covering the automatic EmDashHead path, the manual helper, and the
x-defaultfallback rules.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.AI-generated code disclosure
Screenshots / test output
New test suite
tests/integration/seo/hreflang.test.ts(10 tests): translated pair, resolution from a non-default sibling, untranslated entry (self + x-default), unpublished siblings excluded, unroutable locales dropped, x-default fallback when the default locale is missing, i18n disabled, missing site URL, missing entry, and the default/{collection}/{slug}pattern. Full seo + page test set passes (7 files, 130 tests); lint and typecheck clean.