@ingram-tech/nk-seo 0.8.0 → 0.8.1
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/package.json +7 -4
- package/src/alternates.ts +166 -0
- package/src/components.ts +4 -0
- package/src/hreflang.tsx +70 -0
- package/src/index.ts +92 -0
- package/src/json-ld.tsx +35 -0
- package/src/metadata.ts +203 -0
- package/src/og.tsx +155 -0
- package/src/routes.ts +170 -0
- package/src/schema.ts +980 -0
- package/src/url.ts +23 -0
- package/src/verify.ts +195 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ingram-tech/nk-seo",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.1",
|
|
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.
|
|
46
|
+
"@ingram-tech/nk-dev": "0.12.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.
|
|
53
|
+
"@ingram-tech/nk-i18n": "0.4.1"
|
|
51
54
|
},
|
|
52
55
|
"peerDependencies": {
|
|
53
56
|
"next": ">=14.0.0",
|
|
@@ -0,0 +1,166 @@
|
|
|
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}` for every locale.
|
|
16
|
+
* - `"prefix"`: the default locale stays at the bare path; others get
|
|
17
|
+
* `/${locale}${path}` (matches a localized-rewrite setup). Set
|
|
18
|
+
* {@link HreflangConfig.prefixDefaultLocale} for sites that prefix every
|
|
19
|
+
* locale instead.
|
|
20
|
+
*/
|
|
21
|
+
strategy?: "query" | "prefix";
|
|
22
|
+
/** Query-param name for the `"query"` strategy. Default `"hl"`. */
|
|
23
|
+
param?: string;
|
|
24
|
+
/** Default locale. Required for `"prefix"`; it is what `x-default` resolves to. */
|
|
25
|
+
defaultLocale?: string;
|
|
26
|
+
/**
|
|
27
|
+
* `"prefix"` only: prefix the default locale too (`/en/about`, never
|
|
28
|
+
* `/about`), and point `x-default` at that prefixed URL. For sites whose
|
|
29
|
+
* locale negotiation redirects every bare path — emitting the bare path as
|
|
30
|
+
* an alternate would annotate a URL that 3xx-redirects, which is the bug the
|
|
31
|
+
* mandatory `defaultLocale` exists to prevent.
|
|
32
|
+
*/
|
|
33
|
+
prefixDefaultLocale?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* The locale **the URL names**, which is not always the locale that rendered.
|
|
36
|
+
* It determines the self-referencing canonical, and a canonical is a claim
|
|
37
|
+
* about an address: under `"query"`, `/pricing` canonicalizes to `/pricing`
|
|
38
|
+
* even while content negotiation renders it in French for a French visitor,
|
|
39
|
+
* because `/pricing` is the negotiating entry point and belongs to no locale.
|
|
40
|
+
* Passing the negotiated locale here instead makes the bare path claim to be
|
|
41
|
+
* the French URL, and the real French URL then looks like a duplicate.
|
|
42
|
+
*
|
|
43
|
+
* Leave it unset on a negotiating bare path. Under `"prefix"` it is detected
|
|
44
|
+
* from the pathname; under `"query"` the server cannot see the query string,
|
|
45
|
+
* so pass it — `hreflangConfigFor(routing)` from
|
|
46
|
+
* "@ingram-tech/nk-i18n/next" fills it in correctly.
|
|
47
|
+
*/
|
|
48
|
+
currentLocale?: string;
|
|
49
|
+
/** Optional locale → hreflang tag map, e.g. `{ en: "en-BE", fr: "fr-BE" }`. */
|
|
50
|
+
hrefLangTags?: Record<string, string>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface HreflangLink {
|
|
54
|
+
/** The `hreflang` attribute value ("fr-BE", "x-default", …). */
|
|
55
|
+
hrefLang: string;
|
|
56
|
+
href: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface HreflangAlternates {
|
|
60
|
+
/** Self-referencing canonical URL of `pathname`. */
|
|
61
|
+
canonical: string;
|
|
62
|
+
/** One link per locale, plus the trailing `x-default`. */
|
|
63
|
+
links: HreflangLink[];
|
|
64
|
+
/**
|
|
65
|
+
* The same links keyed by `hrefLang` (`x-default` included) — the shape Next
|
|
66
|
+
* wants for `Metadata.alternates.languages` / `createMetadata`'s
|
|
67
|
+
* `alternates`.
|
|
68
|
+
*/
|
|
69
|
+
languages: Record<string, string>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Computes the self-referencing canonical plus per-locale hreflang alternate
|
|
74
|
+
* URLs (and an `x-default`) for `pathname`.
|
|
75
|
+
*/
|
|
76
|
+
export function hreflangAlternates(
|
|
77
|
+
config: HreflangConfig,
|
|
78
|
+
pathname: string,
|
|
79
|
+
): HreflangAlternates {
|
|
80
|
+
const {
|
|
81
|
+
strategy = "query",
|
|
82
|
+
param = "hl",
|
|
83
|
+
defaultLocale,
|
|
84
|
+
prefixDefaultLocale,
|
|
85
|
+
hrefLangTags,
|
|
86
|
+
} = config;
|
|
87
|
+
if (strategy === "prefix" && !defaultLocale) {
|
|
88
|
+
// Without it canonical/x-default point at a bare path that is no
|
|
89
|
+
// locale's URL — a silent SEO bug. (With `prefixDefaultLocale` no bare
|
|
90
|
+
// path is emitted at all, but x-default still has to resolve to *some*
|
|
91
|
+
// locale, so the requirement stands.)
|
|
92
|
+
throw new Error(
|
|
93
|
+
"hreflangAlternates: `defaultLocale` is required for the prefix strategy.",
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Prefix strategy: accept both the bare and the locale-prefixed form of the
|
|
98
|
+
// path (middleware's `x-pathname` carries the latter on a real localized
|
|
99
|
+
// route — blindly prepending would emit /fr/fr/about) and detect the
|
|
100
|
+
// current locale from it.
|
|
101
|
+
let basePath = pathname;
|
|
102
|
+
let currentLocale = config.currentLocale;
|
|
103
|
+
if (strategy === "prefix") {
|
|
104
|
+
for (const locale of config.locales) {
|
|
105
|
+
if (pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)) {
|
|
106
|
+
basePath = pathname.slice(locale.length + 1) || "/";
|
|
107
|
+
currentLocale ??= locale;
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
currentLocale ??= defaultLocale;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The bare (locale-free) URL of the path. */
|
|
115
|
+
const bareUrl = absoluteUrl(basePath, config.baseUrl);
|
|
116
|
+
|
|
117
|
+
const prefixedUrl = (locale: string): string =>
|
|
118
|
+
absoluteUrl(`/${locale}${basePath === "/" ? "" : basePath}`, config.baseUrl);
|
|
119
|
+
|
|
120
|
+
const hrefFor = (locale: string): string => {
|
|
121
|
+
if (strategy === "prefix") {
|
|
122
|
+
if (locale === defaultLocale && !prefixDefaultLocale) return bareUrl;
|
|
123
|
+
return prefixedUrl(locale);
|
|
124
|
+
}
|
|
125
|
+
return `${bareUrl}${bareUrl.includes("?") ? "&" : "?"}${param}=${locale}`;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/** x-default: the default locale's own URL, prefixed or not. */
|
|
129
|
+
const defaultUrl =
|
|
130
|
+
strategy === "prefix" && prefixDefaultLocale && defaultLocale
|
|
131
|
+
? prefixedUrl(defaultLocale)
|
|
132
|
+
: bareUrl;
|
|
133
|
+
|
|
134
|
+
// Self-referencing canonical: the current variant's own URL. Canonicalizing
|
|
135
|
+
// a localized variant to the bare path makes Google treat the variants as
|
|
136
|
+
// duplicates and ignore the hreflang annotations entirely.
|
|
137
|
+
//
|
|
138
|
+
// Whether the default locale has a URL of its own is strategy-dependent, and
|
|
139
|
+
// conflating the two is a silent way to delete the default locale from the
|
|
140
|
+
// cluster. Under `"prefix"` it shares the bare path (unless every locale is
|
|
141
|
+
// prefixed), so its canonical IS the bare path. Under `"query"` every locale
|
|
142
|
+
// gets its own `?param=` address and the bare path belongs to none of them:
|
|
143
|
+
// it is the negotiating entry point that `x-default` names. So `?hl=en` must
|
|
144
|
+
// canonicalize to `?hl=en`, never to the bare path.
|
|
145
|
+
const defaultLocaleOwnsBarePath = strategy === "prefix" && !prefixDefaultLocale;
|
|
146
|
+
const canonical =
|
|
147
|
+
currentLocale &&
|
|
148
|
+
config.locales.includes(currentLocale) &&
|
|
149
|
+
!(defaultLocaleOwnsBarePath && currentLocale === defaultLocale)
|
|
150
|
+
? hrefFor(currentLocale)
|
|
151
|
+
: defaultUrl;
|
|
152
|
+
|
|
153
|
+
const links = [
|
|
154
|
+
...config.locales.map((locale) => ({
|
|
155
|
+
hrefLang: hrefLangTags?.[locale] ?? locale,
|
|
156
|
+
href: hrefFor(locale),
|
|
157
|
+
})),
|
|
158
|
+
{ hrefLang: "x-default", href: defaultUrl },
|
|
159
|
+
];
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
canonical,
|
|
163
|
+
links,
|
|
164
|
+
languages: Object.fromEntries(links.map((link) => [link.hrefLang, link.href])),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -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";
|
package/src/hreflang.tsx
ADDED
|
@@ -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";
|
package/src/json-ld.tsx
ADDED
|
@@ -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
|
+
}
|
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import type { Metadata } from "next";
|
|
2
|
+
import { absoluteUrl } from "./url.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Per-site defaults for {@link createMetadata}. Set once, reuse on every page.
|
|
6
|
+
*/
|
|
7
|
+
export interface MetadataSiteConfig {
|
|
8
|
+
/** Absolute site origin, e.g. "https://ingram.tech". */
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
/** OpenGraph `siteName`. */
|
|
11
|
+
siteName: string;
|
|
12
|
+
/**
|
|
13
|
+
* `title.template` emitted by `pageMetadata.root()`, e.g. "%s | Acme".
|
|
14
|
+
* Applies to every child page whose title is a plain string.
|
|
15
|
+
*/
|
|
16
|
+
titleTemplate?: string;
|
|
17
|
+
/** Site-relative or absolute default OG/Twitter image. */
|
|
18
|
+
defaultImage?: string;
|
|
19
|
+
defaultImageWidth?: number;
|
|
20
|
+
defaultImageHeight?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Default OpenGraph locale, e.g. "en_US". On a multilingual site set the
|
|
23
|
+
* per-page `locale` instead (or as well, as the fallback).
|
|
24
|
+
*/
|
|
25
|
+
locale?: string;
|
|
26
|
+
/** Twitter `@handle` for `site`. */
|
|
27
|
+
twitterSite?: string;
|
|
28
|
+
/** Twitter `@handle` for `creator`. */
|
|
29
|
+
twitterCreator?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Per-page inputs for the bound `pageMetadata` function. */
|
|
33
|
+
export interface PageMetadataInput {
|
|
34
|
+
title: string;
|
|
35
|
+
description: string;
|
|
36
|
+
/** Site-relative path of the page, e.g. "/blog/post". Used for canonical + OG url. */
|
|
37
|
+
path: string;
|
|
38
|
+
/** Overrides the site default image (site-relative or absolute). */
|
|
39
|
+
image?: string;
|
|
40
|
+
type?: "website" | "article";
|
|
41
|
+
keywords?: Metadata["keywords"];
|
|
42
|
+
noIndex?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* OpenGraph locale for this page, e.g. "fr_BE". Overrides `site.locale` —
|
|
45
|
+
* on a multilingual site `og:locale` has to vary per page.
|
|
46
|
+
*/
|
|
47
|
+
locale?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Merged into the generated `alternates` (wins on conflict). The reason it
|
|
50
|
+
* exists: `alternates.languages` is per-page on a localized site, and
|
|
51
|
+
* spreading the result to bolt it on drops the rest of the object.
|
|
52
|
+
* `hreflangAlternates()` returns a ready-made `languages` map.
|
|
53
|
+
*/
|
|
54
|
+
alternates?: Partial<NonNullable<Metadata["alternates"]>>;
|
|
55
|
+
/** Merged into the generated `openGraph` (wins on conflict). */
|
|
56
|
+
openGraph?: Partial<NonNullable<Metadata["openGraph"]>>;
|
|
57
|
+
/** Merged into the generated `twitter` (wins on conflict). */
|
|
58
|
+
twitter?: Partial<NonNullable<Metadata["twitter"]>>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Inputs for `pageMetadata.root()` — the root-layout metadata. */
|
|
62
|
+
export interface RootMetadataInput {
|
|
63
|
+
/** `title.default` for pages without their own. Defaults to `siteName`. */
|
|
64
|
+
title?: string;
|
|
65
|
+
description?: string;
|
|
66
|
+
/** Extra `Metadata` merged over the generated object (wins on conflict). */
|
|
67
|
+
overrides?: Metadata;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Returns a `pageMetadata(input)` builder that produces a Next `Metadata`
|
|
72
|
+
* object with a self-referencing canonical, OpenGraph, and Twitter card from
|
|
73
|
+
* one title/description/path. Collapses the boilerplate every site repeats.
|
|
74
|
+
*
|
|
75
|
+
* `pageMetadata.root(input?)` builds the root-layout metadata: `metadataBase`,
|
|
76
|
+
* the default title (plus `titleTemplate` when configured), and description —
|
|
77
|
+
* pages then only set their own title/description/path.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* export const pageMetadata = createMetadata({
|
|
81
|
+
* baseUrl: "https://ingram.tech",
|
|
82
|
+
* siteName: "Ingram Technologies",
|
|
83
|
+
* titleTemplate: "%s | Ingram Technologies",
|
|
84
|
+
* defaultImage: "/images/og.png",
|
|
85
|
+
* twitterSite: "@IngramTech",
|
|
86
|
+
* });
|
|
87
|
+
* // app/layout.tsx:
|
|
88
|
+
* export const metadata = pageMetadata.root({ description: "AI deployment." });
|
|
89
|
+
* // in a page:
|
|
90
|
+
* export const metadata = pageMetadata({ title, description, path: "/services" });
|
|
91
|
+
*/
|
|
92
|
+
export function createMetadata(site: MetadataSiteConfig) {
|
|
93
|
+
const absolute = (path: string): string => absoluteUrl(path, site.baseUrl);
|
|
94
|
+
|
|
95
|
+
function pageMetadata(input: PageMetadataInput): Metadata {
|
|
96
|
+
const imagePath = input.image ?? site.defaultImage;
|
|
97
|
+
const imageUrl = imagePath ? absolute(imagePath) : undefined;
|
|
98
|
+
const url = absolute(input.path);
|
|
99
|
+
const locale = input.locale ?? site.locale;
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
metadataBase: new URL(site.baseUrl),
|
|
103
|
+
title: input.title,
|
|
104
|
+
description: input.description,
|
|
105
|
+
...(input.keywords ? { keywords: input.keywords } : {}),
|
|
106
|
+
alternates: { canonical: url, ...input.alternates },
|
|
107
|
+
// noindex but follow: keep link equity flowing through the page. Use a
|
|
108
|
+
// full robots override in the page's own metadata for nofollow too.
|
|
109
|
+
...(input.noIndex ? { robots: { index: false, follow: true } } : {}),
|
|
110
|
+
openGraph: {
|
|
111
|
+
title: input.title,
|
|
112
|
+
description: input.description,
|
|
113
|
+
type: input.type ?? "website",
|
|
114
|
+
url,
|
|
115
|
+
siteName: site.siteName,
|
|
116
|
+
...(locale ? { locale } : {}),
|
|
117
|
+
...(imageUrl
|
|
118
|
+
? {
|
|
119
|
+
images: [
|
|
120
|
+
{
|
|
121
|
+
url: imageUrl,
|
|
122
|
+
width: site.defaultImageWidth ?? 1200,
|
|
123
|
+
height: site.defaultImageHeight ?? 630,
|
|
124
|
+
alt: input.title,
|
|
125
|
+
},
|
|
126
|
+
],
|
|
127
|
+
}
|
|
128
|
+
: {}),
|
|
129
|
+
...input.openGraph,
|
|
130
|
+
},
|
|
131
|
+
twitter: {
|
|
132
|
+
card: "summary_large_image",
|
|
133
|
+
title: input.title,
|
|
134
|
+
description: input.description,
|
|
135
|
+
...(site.twitterSite ? { site: site.twitterSite } : {}),
|
|
136
|
+
...(site.twitterCreator ? { creator: site.twitterCreator } : {}),
|
|
137
|
+
...(imageUrl ? { images: [imageUrl] } : {}),
|
|
138
|
+
...input.twitter,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pageMetadata.root = function rootMetadata(input: RootMetadataInput = {}): Metadata {
|
|
144
|
+
const title = input.title ?? site.siteName;
|
|
145
|
+
return {
|
|
146
|
+
metadataBase: new URL(site.baseUrl),
|
|
147
|
+
title: site.titleTemplate
|
|
148
|
+
? { default: title, template: site.titleTemplate }
|
|
149
|
+
: title,
|
|
150
|
+
...(input.description ? { description: input.description } : {}),
|
|
151
|
+
...input.overrides,
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return pageMetadata;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type PageMetadata = ReturnType<typeof createMetadata>;
|
|
159
|
+
|
|
160
|
+
/** Inputs for {@link ogImageMetadata}. */
|
|
161
|
+
export interface OgImageMetadataInput {
|
|
162
|
+
/** Absolute site origin, e.g. "https://acme.example". */
|
|
163
|
+
baseUrl: string;
|
|
164
|
+
/**
|
|
165
|
+
* Path of the image route — the route the `opengraph-image.tsx` file
|
|
166
|
+
* convention serves, e.g. "/opengraph-image" or "/en/opengraph-image" when
|
|
167
|
+
* the file sits under `app/[locale]/`.
|
|
168
|
+
*/
|
|
169
|
+
path: string;
|
|
170
|
+
alt: string;
|
|
171
|
+
/** Defaults to the 1200×630 the `/og` template renders. */
|
|
172
|
+
width?: number;
|
|
173
|
+
height?: number;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Builds the `openGraph.images` entry for a card served by Next's
|
|
178
|
+
* `opengraph-image` file convention.
|
|
179
|
+
*
|
|
180
|
+
* Next attaches a file-convention image only to the segment that declares it,
|
|
181
|
+
* and a page's own `openGraph` object *replaces* the inherited one rather than
|
|
182
|
+
* merging into it — so any page returning `openGraph` from `generateMetadata`
|
|
183
|
+
* silently loses the card. Build the list once and spread it into every page.
|
|
184
|
+
*
|
|
185
|
+
* `createMetadata`'s `defaultImage` / per-page `image` already do this; reach
|
|
186
|
+
* for the standalone helper when you assemble `Metadata` by hand.
|
|
187
|
+
*
|
|
188
|
+
* @example
|
|
189
|
+
* const images = ogImageMetadata({
|
|
190
|
+
* baseUrl, path: `/${locale}/opengraph-image`, alt: "Acme",
|
|
191
|
+
* });
|
|
192
|
+
* return { title, openGraph: { title, url, images } };
|
|
193
|
+
*/
|
|
194
|
+
export function ogImageMetadata(input: OgImageMetadataInput) {
|
|
195
|
+
return [
|
|
196
|
+
{
|
|
197
|
+
url: absoluteUrl(input.path, input.baseUrl),
|
|
198
|
+
width: input.width ?? 1200,
|
|
199
|
+
height: input.height ?? 630,
|
|
200
|
+
alt: input.alt,
|
|
201
|
+
},
|
|
202
|
+
];
|
|
203
|
+
}
|