@ingram-tech/nk-seo 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -316,21 +316,12 @@ import { HreflangLinks } from "@ingram-tech/nk-seo/components";
316
316
  />
317
317
  ```
318
318
 
319
- Sites that prefix **every** locale — where `/about` redirects to `/en/about`
320
- and no bare path exists — pass `prefixDefaultLocale`, which prefixes the default
321
- locale too and points `x-default` at that prefixed URL. Without it the bare path
322
- is emitted for both `en` and `x-default`, annotating URLs that redirect (Google
323
- wants every hreflang target to answer 200 directly).
324
-
325
- ```tsx
326
- <HreflangLinks
327
- baseUrl="https://example.com"
328
- locales={["en", "fr", "nl"]}
329
- strategy="prefix"
330
- defaultLocale="en"
331
- prefixDefaultLocale
332
- />
333
- ```
319
+ The cluster's **shape** is fixed and not configurable: every locale gets its own
320
+ address, the default included, and the bare path belongs to no locale — it is
321
+ the negotiating entry point that `x-default` names. `strategy` picks only the
322
+ encoding. `@ingram-tech/nk-i18n`'s `defineLocaleRouting` produces a valid config
323
+ for this, and `hreflangConfigFor(routing)` fills in `currentLocale` and the
324
+ pathname header correctly; prefer that over assembling a config by hand.
334
325
 
335
326
  Pass `pathname` explicitly if you don't use the `x-pathname` header. When
336
327
  neither is available the component **throws** instead of guessing — a silent
@@ -10,42 +10,35 @@ export interface HreflangConfig {
10
10
  locales: readonly string[];
11
11
  /**
12
12
  * How locale is encoded in the alternate URLs:
13
- * - `"query"` (default): `${baseUrl}${path}?${param}=${locale}` for every locale.
14
- * - `"prefix"`: the default locale stays at the bare path; others get
15
- * `/${locale}${path}` (matches a localized-rewrite setup). Set
16
- * {@link HreflangConfig.prefixDefaultLocale} for sites that prefix every
17
- * locale instead.
13
+ * - `"query"` (default): `${baseUrl}${path}?${param}=${locale}`
14
+ * - `"prefix"`: `/${locale}${path}`
15
+ *
16
+ * The cluster's SHAPE is the same either way and is not configurable: every
17
+ * locale gets its own address, the default included, and the bare path
18
+ * belongs to no locale — it is the negotiating entry point that `x-default`
19
+ * names. `@ingram-tech/nk-i18n`'s `defineLocaleRouting` produces a valid
20
+ * config for this; prefer passing that over assembling one by hand.
18
21
  */
19
22
  strategy?: "query" | "prefix";
20
23
  /** Query-param name for the `"query"` strategy. Default `"hl"`. */
21
24
  param?: string;
22
- /** Default locale. Required for `"prefix"`; it is what `x-default` resolves to. */
23
- defaultLocale?: string;
24
- /**
25
- * `"prefix"` only: prefix the default locale too (`/en/about`, never
26
- * `/about`), and point `x-default` at that prefixed URL. For sites whose
27
- * locale negotiation redirects every bare path — emitting the bare path as
28
- * an alternate would annotate a URL that 3xx-redirects, which is the bug the
29
- * mandatory `defaultLocale` exists to prevent.
30
- */
31
- prefixDefaultLocale?: boolean;
32
25
  /**
33
26
  * The locale **the URL names**, which is not always the locale that rendered.
34
27
  * It determines the self-referencing canonical, and a canonical is a claim
35
- * about an address: under `"query"`, `/pricing` canonicalizes to `/pricing`
36
- * even while content negotiation renders it in French for a French visitor,
37
- * because `/pricing` is the negotiating entry point and belongs to no locale.
38
- * Passing the negotiated locale here instead makes the bare path claim to be
39
- * the French URL, and the real French URL then looks like a duplicate.
28
+ * about an address: `/pricing` canonicalizes to `/pricing` even while content
29
+ * negotiation renders it in French for a French visitor, because `/pricing`
30
+ * belongs to no locale. Passing the negotiated locale here instead makes the
31
+ * bare path claim to be the French URL, and the real French URL then looks
32
+ * like a duplicate of it.
40
33
  *
41
- * Leave it unset on a negotiating bare path. Under `"prefix"` it is detected
42
- * from the pathname; under `"query"` the server cannot see the query string,
43
- * so pass it — `hreflangConfigFor(routing)` from
44
- * "@ingram-tech/nk-i18n/next" fills it in correctly.
34
+ * Leave it unset on the bare path. Under `"prefix"` it is detected from the
35
+ * pathname; under `"query"` the server cannot see the query string, so pass
36
+ * it — `hreflangConfigFor(routing)` from "@ingram-tech/nk-i18n/next" fills it
37
+ * in correctly.
45
38
  */
46
39
  currentLocale?: string;
47
40
  /** Optional locale → hreflang tag map, e.g. `{ en: "en-BE", fr: "fr-BE" }`. */
48
- hrefLangTags?: Record<string, string>;
41
+ hrefLangTags?: Readonly<Partial<Record<string, string>>>;
49
42
  }
50
43
  export interface HreflangLink {
51
44
  /** The `hreflang` attribute value ("fr-BE", "x-default", …). */
@@ -1 +1 @@
1
- {"version":3,"file":"alternates.d.ts","sourceRoot":"","sources":["../src/alternates.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B,yDAAyD;IACzD,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC9B,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,YAAY;IAC5B,gEAAgE;IAChE,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IAClC,oDAAoD;IACpD,SAAS,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,MAAM,GACd,kBAAkB,CAuFpB"}
1
+ {"version":3,"file":"alternates.d.ts","sourceRoot":"","sources":["../src/alternates.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B,yDAAyD;IACzD,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC9B,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;CACzD;AAED,MAAM,WAAW,YAAY;IAC5B,gEAAgE;IAChE,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IAClC,oDAAoD;IACpD,SAAS,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,MAAM,GACd,kBAAkB,CAuDpB"}
@@ -4,18 +4,10 @@ import { absoluteUrl } from "./url.js";
4
4
  * URLs (and an `x-default`) for `pathname`.
5
5
  */
6
6
  export function hreflangAlternates(config, pathname) {
7
- const { strategy = "query", param = "hl", defaultLocale, prefixDefaultLocale, hrefLangTags, } = config;
8
- if (strategy === "prefix" && !defaultLocale) {
9
- // Without it canonical/x-default point at a bare path that is no
10
- // locale's URL — a silent SEO bug. (With `prefixDefaultLocale` no bare
11
- // path is emitted at all, but x-default still has to resolve to *some*
12
- // locale, so the requirement stands.)
13
- throw new Error("hreflangAlternates: `defaultLocale` is required for the prefix strategy.");
14
- }
15
- // Prefix strategy: accept both the bare and the locale-prefixed form of the
16
- // path (middleware's `x-pathname` carries the latter on a real localized
17
- // route — blindly prepending would emit /fr/fr/about) and detect the
18
- // current locale from it.
7
+ const { strategy = "query", param = "hl", hrefLangTags } = config;
8
+ // Accept both the bare and the locale-prefixed form of the path (middleware's
9
+ // `x-pathname` carries the latter on a real localized route — blindly
10
+ // prepending would emit /fr/fr/about) and detect the current locale from it.
19
11
  let basePath = pathname;
20
12
  let currentLocale = config.currentLocale;
21
13
  if (strategy === "prefix") {
@@ -26,46 +18,30 @@ export function hreflangAlternates(config, pathname) {
26
18
  break;
27
19
  }
28
20
  }
29
- currentLocale ??= defaultLocale;
21
+ // Deliberately no fallback to a default locale: a bare path names none.
30
22
  }
31
- /** The bare (locale-free) URL of the path. */
23
+ /** The bare (locale-free) URL — the negotiating entry point, `x-default`. */
32
24
  const bareUrl = absoluteUrl(basePath, config.baseUrl);
33
- const prefixedUrl = (locale) => absoluteUrl(`/${locale}${basePath === "/" ? "" : basePath}`, config.baseUrl);
25
+ /** Every locale has its own address, the default included. */
34
26
  const hrefFor = (locale) => {
35
27
  if (strategy === "prefix") {
36
- if (locale === defaultLocale && !prefixDefaultLocale)
37
- return bareUrl;
38
- return prefixedUrl(locale);
28
+ return absoluteUrl(`/${locale}${basePath === "/" ? "" : basePath}`, config.baseUrl);
39
29
  }
40
30
  return `${bareUrl}${bareUrl.includes("?") ? "&" : "?"}${param}=${locale}`;
41
31
  };
42
- /** x-default: the default locale's own URL, prefixed or not. */
43
- const defaultUrl = strategy === "prefix" && prefixDefaultLocale && defaultLocale
44
- ? prefixedUrl(defaultLocale)
45
- : bareUrl;
46
- // Self-referencing canonical: the current variant's own URL. Canonicalizing
47
- // a localized variant to the bare path makes Google treat the variants as
48
- // duplicates and ignore the hreflang annotations entirely.
49
- //
50
- // Whether the default locale has a URL of its own is strategy-dependent, and
51
- // conflating the two is a silent way to delete the default locale from the
52
- // cluster. Under `"prefix"` it shares the bare path (unless every locale is
53
- // prefixed), so its canonical IS the bare path. Under `"query"` every locale
54
- // gets its own `?param=` address and the bare path belongs to none of them:
55
- // it is the negotiating entry point that `x-default` names. So `?hl=en` must
56
- // canonicalize to `?hl=en`, never to the bare path.
57
- const defaultLocaleOwnsBarePath = strategy === "prefix" && !prefixDefaultLocale;
58
- const canonical = currentLocale &&
59
- config.locales.includes(currentLocale) &&
60
- !(defaultLocaleOwnsBarePath && currentLocale === defaultLocale)
32
+ // Self-referencing canonical: the current variant's own URL, or the bare path
33
+ // when the URL names no locale. Canonicalizing a localized variant to the
34
+ // bare path makes Google treat the variants as duplicates and ignore the
35
+ // hreflang annotations entirely.
36
+ const canonical = currentLocale && config.locales.includes(currentLocale)
61
37
  ? hrefFor(currentLocale)
62
- : defaultUrl;
38
+ : bareUrl;
63
39
  const links = [
64
40
  ...config.locales.map((locale) => ({
65
41
  hrefLang: hrefLangTags?.[locale] ?? locale,
66
42
  href: hrefFor(locale),
67
43
  })),
68
- { hrefLang: "x-default", href: defaultUrl },
44
+ { hrefLang: "x-default", href: bareUrl },
69
45
  ];
70
46
  return {
71
47
  canonical,
@@ -1 +1 @@
1
- {"version":3,"file":"alternates.js","sourceRoot":"","sources":["../src/alternates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAuEvC;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,MAAsB,EACtB,QAAgB;IAEhB,MAAM,EACL,QAAQ,GAAG,OAAO,EAClB,KAAK,GAAG,IAAI,EACZ,aAAa,EACb,mBAAmB,EACnB,YAAY,GACZ,GAAG,MAAM,CAAC;IACX,IAAI,QAAQ,KAAK,QAAQ,IAAI,CAAC,aAAa,EAAE,CAAC;QAC7C,iEAAiE;QACjE,uEAAuE;QACvE,uEAAuE;QACvE,sCAAsC;QACtC,MAAM,IAAI,KAAK,CACd,0EAA0E,CAC1E,CAAC;IACH,C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AC,GAAG,GAAG,KAAK,IAAI,MAAM,EAAE,CAAC;IAC3E,CAAC,CAAC;IAEF,8EAA8E;IAC9E,0EAA0E;IAC1E,yEAAyE;IACzE,iCAAiC;IACjC,MAAM,SAAS,GACd,aAAa,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC;QACtD,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC;QACxB,CAAC,CAAC,OAAO,CAAC;IAEZ,MAAM,KAAK,GAAG;QACb,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YAClC,QAAQ,EAAE,YAAY,EAAE,CAAC,MAAM,CAAC,IAAI,MAAM;YAC1C,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC;SACrB,CAAC,CAAC;QACH,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE;KACxC,CAAC;IAEF,OAAO;QACN,SAAS;QACT,KAAK;QACL,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;KAC9E,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ingram-tech/nk-seo",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "SEO primitives for Next.js sites: typed schema.org JSON-LD builders, a <JsonLd> tag, a Metadata factory (canonical + OG + Twitter), and configurable hreflang alternates.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,7 +14,10 @@
14
14
  },
15
15
  "sideEffects": false,
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ "src",
19
+ "!src/**/*.test.ts",
20
+ "!src/**/*.test.tsx"
18
21
  ],
19
22
  "exports": {
20
23
  ".": {
@@ -40,14 +43,14 @@
40
43
  "test": "vitest run"
41
44
  },
42
45
  "devDependencies": {
43
- "@ingram-tech/nk-dev": "0.11.1",
46
+ "@ingram-tech/nk-dev": "0.13.0",
44
47
  "@types/node": "^26.2.0",
45
48
  "@types/react": "^19.2.18",
46
49
  "next": "^16.3.1",
47
50
  "react": "^19.2.8",
48
51
  "typescript": "^7.0.2",
49
52
  "vitest": "^4.1.10",
50
- "@ingram-tech/nk-i18n": "0.4.0"
53
+ "@ingram-tech/nk-i18n": "0.5.0"
51
54
  },
52
55
  "peerDependencies": {
53
56
  "next": ">=14.0.0",
@@ -0,0 +1,127 @@
1
+ import { absoluteUrl } from "./url.js";
2
+
3
+ /**
4
+ * Pure hreflang computation behind `<HreflangLinks>` (from
5
+ * "@ingram-tech/nk-seo/components"). Usable directly wherever a component
6
+ * doesn't fit (e.g. building `Metadata.alternates` in `generateMetadata`).
7
+ */
8
+ export interface HreflangConfig {
9
+ /** Absolute site origin, e.g. "https://acme.example". */
10
+ baseUrl: string;
11
+ /** Locales to emit alternates for, e.g. ["en", "fr", "nl"]. */
12
+ locales: readonly string[];
13
+ /**
14
+ * How locale is encoded in the alternate URLs:
15
+ * - `"query"` (default): `${baseUrl}${path}?${param}=${locale}`
16
+ * - `"prefix"`: `/${locale}${path}`
17
+ *
18
+ * The cluster's SHAPE is the same either way and is not configurable: every
19
+ * locale gets its own address, the default included, and the bare path
20
+ * belongs to no locale — it is the negotiating entry point that `x-default`
21
+ * names. `@ingram-tech/nk-i18n`'s `defineLocaleRouting` produces a valid
22
+ * config for this; prefer passing that over assembling one by hand.
23
+ */
24
+ strategy?: "query" | "prefix";
25
+ /** Query-param name for the `"query"` strategy. Default `"hl"`. */
26
+ param?: string;
27
+ /**
28
+ * The locale **the URL names**, which is not always the locale that rendered.
29
+ * It determines the self-referencing canonical, and a canonical is a claim
30
+ * about an address: `/pricing` canonicalizes to `/pricing` even while content
31
+ * negotiation renders it in French for a French visitor, because `/pricing`
32
+ * belongs to no locale. Passing the negotiated locale here instead makes the
33
+ * bare path claim to be the French URL, and the real French URL then looks
34
+ * like a duplicate of it.
35
+ *
36
+ * Leave it unset on the bare path. Under `"prefix"` it is detected from the
37
+ * pathname; under `"query"` the server cannot see the query string, so pass
38
+ * it — `hreflangConfigFor(routing)` from "@ingram-tech/nk-i18n/next" fills it
39
+ * in correctly.
40
+ */
41
+ currentLocale?: string;
42
+ /** Optional locale → hreflang tag map, e.g. `{ en: "en-BE", fr: "fr-BE" }`. */
43
+ hrefLangTags?: Readonly<Partial<Record<string, string>>>;
44
+ }
45
+
46
+ export interface HreflangLink {
47
+ /** The `hreflang` attribute value ("fr-BE", "x-default", …). */
48
+ hrefLang: string;
49
+ href: string;
50
+ }
51
+
52
+ export interface HreflangAlternates {
53
+ /** Self-referencing canonical URL of `pathname`. */
54
+ canonical: string;
55
+ /** One link per locale, plus the trailing `x-default`. */
56
+ links: HreflangLink[];
57
+ /**
58
+ * The same links keyed by `hrefLang` (`x-default` included) — the shape Next
59
+ * wants for `Metadata.alternates.languages` / `createMetadata`'s
60
+ * `alternates`.
61
+ */
62
+ languages: Record<string, string>;
63
+ }
64
+
65
+ /**
66
+ * Computes the self-referencing canonical plus per-locale hreflang alternate
67
+ * URLs (and an `x-default`) for `pathname`.
68
+ */
69
+ export function hreflangAlternates(
70
+ config: HreflangConfig,
71
+ pathname: string,
72
+ ): HreflangAlternates {
73
+ const { strategy = "query", param = "hl", hrefLangTags } = config;
74
+
75
+ // Accept both the bare and the locale-prefixed form of the path (middleware's
76
+ // `x-pathname` carries the latter on a real localized route — blindly
77
+ // prepending would emit /fr/fr/about) and detect the current locale from it.
78
+ let basePath = pathname;
79
+ let currentLocale = config.currentLocale;
80
+ if (strategy === "prefix") {
81
+ for (const locale of config.locales) {
82
+ if (pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)) {
83
+ basePath = pathname.slice(locale.length + 1) || "/";
84
+ currentLocale ??= locale;
85
+ break;
86
+ }
87
+ }
88
+ // Deliberately no fallback to a default locale: a bare path names none.
89
+ }
90
+
91
+ /** The bare (locale-free) URL — the negotiating entry point, `x-default`. */
92
+ const bareUrl = absoluteUrl(basePath, config.baseUrl);
93
+
94
+ /** Every locale has its own address, the default included. */
95
+ const hrefFor = (locale: string): string => {
96
+ if (strategy === "prefix") {
97
+ return absoluteUrl(
98
+ `/${locale}${basePath === "/" ? "" : basePath}`,
99
+ config.baseUrl,
100
+ );
101
+ }
102
+ return `${bareUrl}${bareUrl.includes("?") ? "&" : "?"}${param}=${locale}`;
103
+ };
104
+
105
+ // Self-referencing canonical: the current variant's own URL, or the bare path
106
+ // when the URL names no locale. Canonicalizing a localized variant to the
107
+ // bare path makes Google treat the variants as duplicates and ignore the
108
+ // hreflang annotations entirely.
109
+ const canonical =
110
+ currentLocale && config.locales.includes(currentLocale)
111
+ ? hrefFor(currentLocale)
112
+ : bareUrl;
113
+
114
+ const links = [
115
+ ...config.locales.map((locale) => ({
116
+ hrefLang: hrefLangTags?.[locale] ?? locale,
117
+ href: hrefFor(locale),
118
+ })),
119
+ { hrefLang: "x-default", href: bareUrl },
120
+ ];
121
+
122
+ return {
123
+ canonical,
124
+ links,
125
+ languages: Object.fromEntries(links.map((link) => [link.hrefLang, link.href])),
126
+ };
127
+ }
@@ -0,0 +1,4 @@
1
+ // React entry: the rendering components. Kept out of the package root so server
2
+ // code that only needs the builders/metadata never imports React or next/headers.
3
+ export { JsonLd, serializeJsonLd } from "./json-ld.js";
4
+ export { HreflangLinks, type HreflangLinksProps } from "./hreflang.js";
@@ -0,0 +1,70 @@
1
+ import { headers } from "next/headers";
2
+ import { hreflangAlternates, type HreflangConfig } from "./alternates.js";
3
+
4
+ export interface HreflangLinksProps extends HreflangConfig {
5
+ /**
6
+ * Path being rendered. Defaults to the `x-pathname` REQUEST header — it must
7
+ * be set on the forwarded request in middleware (a response header is
8
+ * invisible to `headers()`):
9
+ *
10
+ * ```ts
11
+ * const requestHeaders = new Headers(req.headers);
12
+ * requestHeaders.set("x-pathname", req.nextUrl.pathname);
13
+ * return NextResponse.next({ request: { headers: requestHeaders } });
14
+ * ```
15
+ *
16
+ * Pass explicitly if you don't use that header (e.g. from route params) —
17
+ * also the only way to keep the page statically renderable, since reading
18
+ * `headers()` opts the page into dynamic rendering.
19
+ */
20
+ pathname?: string;
21
+ /**
22
+ * Emit a self-referencing `<link rel="canonical">`. Default `true`.
23
+ * Disable it if the page's metadata already sets `alternates.canonical`
24
+ * (e.g. via `createMetadata`) — a page must not declare two canonicals.
25
+ */
26
+ canonical?: boolean;
27
+ }
28
+
29
+ /**
30
+ * Emits `<link rel="canonical">` plus per-locale `<link rel="alternate" hreflang>`
31
+ * (and an `x-default`) for the current path. Render inside `<head>` (e.g. from
32
+ * the root layout). Server component — reads the `x-pathname` header by default.
33
+ *
34
+ * Throws when neither `pathname` nor the header is available: silently falling
35
+ * back would canonicalize every page to the homepage, a site-wide
36
+ * duplicate-content bug that is otherwise invisible.
37
+ */
38
+ export async function HreflangLinks({
39
+ pathname,
40
+ canonical = true,
41
+ ...config
42
+ }: HreflangLinksProps) {
43
+ const path = pathname ?? (await headers()).get("x-pathname");
44
+ if (!path) {
45
+ throw new Error(
46
+ "HreflangLinks: no `pathname` prop and no `x-pathname` request header. " +
47
+ "Set it on the forwarded REQUEST in middleware — " +
48
+ '`const h = new Headers(req.headers); h.set("x-pathname", req.nextUrl.pathname); ' +
49
+ "return NextResponse.next({ request: { headers: h } });` — " +
50
+ "(a response header is invisible to `headers()`), or pass `pathname` explicitly.",
51
+ );
52
+ }
53
+ const { canonical: canonicalUrl, links } = hreflangAlternates(config, path);
54
+
55
+ return (
56
+ <>
57
+ {canonical ? <link rel="canonical" href={canonicalUrl} /> : null}
58
+ {links.map((link) => (
59
+ <link
60
+ // hrefLang alone can collide (two locales mapped to one tag via
61
+ // hrefLangTags), and colliding keys silently drop links.
62
+ key={`${link.hrefLang} ${link.href}`}
63
+ rel="alternate"
64
+ hrefLang={link.hrefLang}
65
+ href={link.href}
66
+ />
67
+ ))}
68
+ </>
69
+ );
70
+ }
package/src/index.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Server entry: pure schema.org builders + the Metadata factory. No React, so
2
+ // route handlers / sitemap.ts can import these without pulling in the renderer.
3
+ // The <JsonLd> and <HreflangLinks> components live at
4
+ // "@ingram-tech/nk-seo/components".
5
+ export {
6
+ type AggregateOfferNode,
7
+ type AggregateRatingInput,
8
+ type AggregateRatingNode,
9
+ article,
10
+ type ArticleAuthor,
11
+ type ArticleAuthorNode,
12
+ type ArticleInput,
13
+ type ArticleNode,
14
+ type ArticleType,
15
+ breadcrumbList,
16
+ type BreadcrumbItem,
17
+ type BreadcrumbListNode,
18
+ type BreadcrumbPath,
19
+ createSeo,
20
+ type DataDownloadInput,
21
+ type DataDownloadNode,
22
+ dataset,
23
+ type DatasetInput,
24
+ type DatasetNode,
25
+ definedTerm,
26
+ type DefinedTermInput,
27
+ type DefinedTermNode,
28
+ definedTermSet,
29
+ type DefinedTermSetInput,
30
+ type DefinedTermSetNode,
31
+ event,
32
+ type EventInput,
33
+ type EventLocationInput,
34
+ type EventNode,
35
+ faqPage,
36
+ type FaqItem,
37
+ type FaqPageNode,
38
+ type GeoCoordinatesNode,
39
+ type GeoInput,
40
+ type ImageObjectNode,
41
+ type JsonLdNode,
42
+ type ListItemNode,
43
+ localBusiness,
44
+ type LocalBusinessInput,
45
+ type LocalBusinessNode,
46
+ type OfferInput,
47
+ type OfferNode,
48
+ organization,
49
+ type OrganizationInput,
50
+ type OrganizationNode,
51
+ person,
52
+ type PersonInput,
53
+ type PersonNode,
54
+ type PlaceNode,
55
+ type PostalAddressInput,
56
+ type PostalAddressNode,
57
+ type QuestionNode,
58
+ type Seo,
59
+ type SeoConfig,
60
+ softwareApplication,
61
+ type SoftwareApplicationInput,
62
+ type SoftwareApplicationNode,
63
+ type VirtualLocationNode,
64
+ website,
65
+ type WebsiteInput,
66
+ type WebsiteNode,
67
+ type WithContext,
68
+ type WithExtra,
69
+ } from "./schema.js";
70
+ export {
71
+ createMetadata,
72
+ type MetadataSiteConfig,
73
+ ogImageMetadata,
74
+ type OgImageMetadataInput,
75
+ type PageMetadata,
76
+ type PageMetadataInput,
77
+ type RootMetadataInput,
78
+ } from "./metadata.js";
79
+ export {
80
+ createRobots,
81
+ createSitemap,
82
+ type RobotsConfig,
83
+ type SitemapConfig,
84
+ type SitemapLanguages,
85
+ type SitemapRoute,
86
+ } from "./routes.js";
87
+ export {
88
+ hreflangAlternates,
89
+ type HreflangAlternates,
90
+ type HreflangConfig,
91
+ type HreflangLink,
92
+ } from "./alternates.js";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * JSON.stringify hardened for inline `<script>` bodies. `<` is escaped so a
3
+ * string value containing `</script>` (FAQ answers and article headlines often
4
+ * come from a CMS) cannot terminate the tag and inject markup; U+2028/2029 are
5
+ * escaped because they are valid JSON but not valid JS source.
6
+ */
7
+ // U+2028/U+2029 via RegExp() so the source stays ASCII (a literal invisible
8
+ // character would be one editor "normalization" away from silently vanishing).
9
+ const LINE_SEPARATORS = new RegExp("[\\u2028\\u2029]", "g");
10
+
11
+ export const serializeJsonLd = (data: object | object[]): string =>
12
+ JSON.stringify(data)
13
+ .replace(/</g, "\\u003c")
14
+ .replace(LINE_SEPARATORS, (char) => {
15
+ const hex = char.codePointAt(0)?.toString(16) ?? "";
16
+ return "\\u" + hex;
17
+ });
18
+
19
+ /**
20
+ * Renders one or more schema.org JSON-LD nodes into a
21
+ * `<script type="application/ld+json">`. Works in server and client components.
22
+ *
23
+ * @example
24
+ * <JsonLd data={faqPage(items)} />
25
+ * <JsonLd data={[organization(org), website(site)]} />
26
+ */
27
+ export function JsonLd({ data }: { data: object | object[] }) {
28
+ return (
29
+ <script
30
+ type="application/ld+json"
31
+ // oxlint-disable-next-line no-danger -- serializeJsonLd escapes `<`, so content strings cannot break out of the script tag
32
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
33
+ />
34
+ );
35
+ }