feat: CMS head and one JSON-LD graph on every server-rendered page (tracer)
- Nitro middleware resolves page requests once and hands the answer to the render (event.context.seo); the route middleware reuses it - useCmsSeo: html lang, hreflang links, og:locale and exactly one JSON-LD script with one @graph (CMS nodes plus useSchemaNode nodes, merged by @id) - local module (configKey seo): cms (alias of public.seo.enabled), breadcrumbs, links.newTabHint, rootFiles, resolveFiles - GET /api/__seo__/resolve for client navigation through the Nuxt server - smoke harness: count=, exact header=, noheader=, reqheader=, repeated options, resolves/apicalls/noreport lines, --no-site; v0.1.1 suite runs unchanged against a backend without /site
This commit is contained in:
24
server/api/__seo__/resolve.get.ts
Normal file
24
server/api/__seo__/resolve.get.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
// GET /api/__seo__/resolve?url=<path and query>: the resolve answer through
|
||||
// the layer's server (and its cache), for client-side navigation on a site
|
||||
// whose proxy does not route /_seo/api/v1 to the backend. The browser uses
|
||||
// it when public.seo.apiBase (NUXT_PUBLIC_SEO_API_BASE) is "/api/__seo__";
|
||||
// the default stays the backend's same-origin /_seo/api/v1.
|
||||
//
|
||||
// 404 when the layer is off; 422 for a url that is not a path; 502 when the
|
||||
// backend gives no usable answer. Never route-cached ('/api/__seo__/**'
|
||||
// cache false) and never indexed.
|
||||
|
||||
import { seoServerConfig } from '../../lib/config.ts'
|
||||
import { resolveCached } from '../../lib/resolve.ts'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
setResponseHeaders(event, { 'cache-control': 'no-store', 'x-robots-tag': 'noindex' })
|
||||
if (!seoServerConfig(useRuntimeConfig(event)).enabled) throw createError({ statusCode: 404, statusMessage: 'Not Found' })
|
||||
const url = getQuery(event).url
|
||||
if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//') || url.length > 2048) {
|
||||
throw createError({ statusCode: 422, statusMessage: 'Bad url' })
|
||||
}
|
||||
const answer = await resolveCached(event, url)
|
||||
if (!answer) throw createError({ statusCode: 502, statusMessage: 'No SEO answer' })
|
||||
return answer
|
||||
})
|
||||
80
server/lib/config.ts
Normal file
80
server/lib/config.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
// The SEO layer's settings as the server code reads them from runtime
|
||||
// config. Pure TypeScript outside Nitro's auto-import directories, so
|
||||
// `node --test`, the middleware and the routes import it directly.
|
||||
|
||||
import { seoEnabled } from '../../app/utils/seo.ts'
|
||||
|
||||
export interface SeoServerConfig {
|
||||
/** False when public.seo.enabled or its alias public.seo.cms is false: no CMS call at all. */
|
||||
enabled: boolean
|
||||
/** Server-only base of the plugin's API (NUXT_SEO_API_BASE), without a trailing slash. */
|
||||
apiBase: string
|
||||
/** Server-only origin of the Go binary for the root files (NUXT_SEO_BACKEND_BASE). */
|
||||
backendBase: string
|
||||
/** How long a call may take before the page renders without it (NUXT_SEO_TIMEOUT_MS). */
|
||||
timeoutMs: number
|
||||
/** Seconds a resolve answer stays cached (NUXT_SEO_RESOLVE_CACHE_TTL); 0 turns the cache off. */
|
||||
resolveCacheTtl: number
|
||||
/** Bearer token of POST /notfound (NUXT_SEO_NOTFOUND_TOKEN); empty: no reports. */
|
||||
notfoundToken: string
|
||||
/** Bearer token of the route report (33-08); falls back to notfoundToken. */
|
||||
routeReportToken: string
|
||||
/** Module option seo.rootFiles: serve robots.txt, the sitemaps, llms.txt and the listed root files. */
|
||||
rootFiles: boolean
|
||||
/** Module option seo.resolveFiles: file extensions the middleware still resolves (['pdf']). */
|
||||
resolveFiles: string[]
|
||||
}
|
||||
|
||||
export const DEFAULT_SEO_API_BASE = 'http://127.0.0.1:8096/_seo/api/v1'
|
||||
export const DEFAULT_RESOLVE_CACHE_TTL = 60
|
||||
|
||||
const API_SUFFIX = /\/_seo\/api\/v1\/?$/
|
||||
|
||||
function section(config: unknown, name: string): Record<string, unknown> {
|
||||
if (config === null || typeof config !== 'object') return {}
|
||||
const value = (config as Record<string, unknown>)[name]
|
||||
return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : {}
|
||||
}
|
||||
|
||||
const str = (v: unknown) => (typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : '')
|
||||
|
||||
function num(v: unknown, fallback: number): number {
|
||||
if (v === '' || v === null || v === undefined) return fallback
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) && n >= 0 ? n : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* The backend origin for root files: backendBase when set, else apiBase
|
||||
* without its /_seo/api/v1 suffix (so an app that only sets
|
||||
* NUXT_SEO_API_BASE needs nothing else), else apiBase's origin.
|
||||
*/
|
||||
export function seoBackendBase(backendBase: string, apiBase: string): string {
|
||||
if (backendBase) return backendBase.replace(/\/+$/, '')
|
||||
if (API_SUFFIX.test(apiBase)) return apiBase.replace(API_SUFFIX, '')
|
||||
try {
|
||||
return new URL(apiBase).origin
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the layer's settings from a runtime config object (useRuntimeConfig(event)). */
|
||||
export function seoServerConfig(config: unknown): SeoServerConfig {
|
||||
const seo = section(config, 'seo')
|
||||
const pub = section(section(config, 'public'), 'seo')
|
||||
const apiBase = (str(seo.apiBase) || DEFAULT_SEO_API_BASE).replace(/\/+$/, '')
|
||||
const notfoundToken = str(seo.notfoundToken)
|
||||
const resolveFiles = Array.isArray(pub.resolveFiles) ? pub.resolveFiles.filter((e): e is string => typeof e === 'string') : ['pdf']
|
||||
return {
|
||||
enabled: seoEnabled(pub),
|
||||
apiBase,
|
||||
backendBase: seoBackendBase(str(seo.backendBase), apiBase),
|
||||
timeoutMs: num(seo.timeoutMs, 1500) || 1500,
|
||||
resolveCacheTtl: num(seo.resolveCacheTtl, DEFAULT_RESOLVE_CACHE_TTL),
|
||||
notfoundToken,
|
||||
routeReportToken: str(seo.routeReportToken) || notfoundToken,
|
||||
rootFiles: pub.rootFiles !== false && pub.rootFiles !== 'false',
|
||||
resolveFiles,
|
||||
}
|
||||
}
|
||||
38
server/lib/resolve.ts
Normal file
38
server/lib/resolve.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
// The server side of the resolve call: GET <apiBase>/resolve?url=<path and
|
||||
// query>, forwarding the visitor's address so the backend's per-IP throttle
|
||||
// (seo-resolve) keeps one bucket per visitor, also on route-cached renders
|
||||
// (server/plugins/seo-client-address.ts records it). Any failure (timeout,
|
||||
// 4xx, 5xx, an unexpected body) answers null and the page renders without
|
||||
// CMS head tags (fail open); with the layer switched off nothing is called.
|
||||
//
|
||||
// Nitro auto-imports (useRuntimeConfig, $fetch) are used inside the
|
||||
// functions only, so `node --test` can import this file.
|
||||
|
||||
import type { H3Event } from 'h3'
|
||||
import { seoAnswer } from '../../app/utils/seo.ts'
|
||||
import type { SeoResolveAnswer } from '../../app/utils/types.ts'
|
||||
import { seoServerConfig, type SeoServerConfig } from './config.ts'
|
||||
|
||||
/** The x-forwarded-for value the SEO calls carry for this request. */
|
||||
export function seoForwardedFor(event: H3Event): Record<string, string> {
|
||||
const recorded = event.context.seoForwardedFor as string | undefined
|
||||
return recorded ? { 'x-forwarded-for': recorded } : {}
|
||||
}
|
||||
|
||||
async function fetchResolve(cfg: SeoServerConfig, url: string, headers: Record<string, string>): Promise<SeoResolveAnswer | null> {
|
||||
try {
|
||||
return seoAnswer(await $fetch('/resolve', { baseURL: cfg.apiBase, query: { url }, headers, timeout: cfg.timeoutMs }))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolve answer for `url` (path and query), or null on any failure or
|
||||
* when the layer is off (public.seo.enabled or seo.cms false).
|
||||
*/
|
||||
export async function resolveCached(event: H3Event, url: string): Promise<SeoResolveAnswer | null> {
|
||||
const cfg = seoServerConfig(useRuntimeConfig(event))
|
||||
if (!cfg.enabled) return null
|
||||
return fetchResolve(cfg, url, seoForwardedFor(event))
|
||||
}
|
||||
21
server/middleware/seo.ts
Normal file
21
server/middleware/seo.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// Resolves every page request through the CMS before Nuxt renders it, so the
|
||||
// render (and the head) uses one answer and no second call. Skipped: Nuxt's
|
||||
// and the layers' internal paths (/_nuxt, /__nuxt_error, /_seo …), /api and
|
||||
// asset files (isPagePath). The answer is left in event.context.seo for the
|
||||
// app (useSeoResolve reads event.context.seoResolved).
|
||||
|
||||
import { isPagePath } from '../../app/utils/pagePath.ts'
|
||||
import { seoServerConfig } from '../lib/config.ts'
|
||||
import { resolveCached } from '../lib/resolve.ts'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
if (event.method !== 'GET' && event.method !== 'HEAD') return
|
||||
const cfg = seoServerConfig(useRuntimeConfig(event))
|
||||
if (!cfg.enabled) return
|
||||
const url = event.path
|
||||
if (!isPagePath(url, cfg.resolveFiles)) return
|
||||
|
||||
const answer = await resolveCached(event, url)
|
||||
event.context.seo = answer
|
||||
event.context.seoResolved = { url, answer }
|
||||
})
|
||||
Reference in New Issue
Block a user