diff --git a/AGENTS.md b/AGENTS.md index 3461705..a92468c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,8 +130,9 @@ publishDate: "2025-12-01" # optional - 예약 발행 - draft/scheduled 글은 production 메타데이터·본문·검색 인덱스에서 자동 필터링 ### SEO -- `useMetaTags()` 훅으로 페이지별 title, description, OG 태그 설정 -- `vite.config.ts`에서 빌드 시 sitemap.xml, rss.xml 자동 생성 +- `src/lib/seo.ts`의 공통 사이트 설정·정규화·메타태그 규칙을 초기 HTML과 `useMetaTags()` 훅에서 공유 +- `src/entry-server.tsx`의 발행 경로 목록으로 `scripts/prerender.mjs`에서 sitemap.xml, 언어별 rss.xml 생성 +- SEO 변경 후 `pnpm build`, `pnpm test:seo`, `pnpm test:sitemap-lastmod`, `pnpm check:internal-links` 실행; 상세 규칙은 `docs/seo.md` 참고 - `src/entry-server.tsx` + `scripts/prerender.mjs`로 주요 라우트를 hydrated SSG HTML로 생성 - 빌드 후 `dist/404.html`은 NotFound SSR HTML로 생성해 GitHub Pages SPA fallback의 hydration mismatch 방지 diff --git a/docs/seo.md b/docs/seo.md new file mode 100644 index 0000000..5da20ea --- /dev/null +++ b/docs/seo.md @@ -0,0 +1,25 @@ +# 공통 SEO 처리 + +React/Vite와 hydrated SSG 구조를 유지한다. Jekyll SEO Tag의 사이트 기본값 + 페이지별 정보 패턴을 참고하며, 테마나 플러그인 자체는 추가하지 않는다. + +## 생성 규칙 + +- `src/lib/seo.ts`: 사이트 이름·기본 설명·이미지, canonical 정규화, 메타태그, hreflang, 언어별 RSS 링크의 공통 규칙. +- `src/lib/page-seo.ts`: 홈·글 목록·태그·시리즈·소개 등 고정 페이지의 제목·설명·언어 연결을 공유한다. +- `src/lib/post-seo.ts`: 게시글 제목·설명·발행일·수정일·실제 번역 연결을 서버와 클라이언트에서 공유한다. +- `src/hooks/useMetaTags.ts`: 같은 규칙을 클라이언트 이동에 적용한다. 이전 페이지의 관리 대상 태그를 교체하며 구조화 데이터는 React 페이지가 소유한다. +- `src/entry-server.tsx`: 프리렌더할 경로와 발행된 글 목록을 제공한다. +- `scripts/prerender.mjs`: 공통 규칙으로 초기 HTML을 만들고 동일한 경로 목록에서 사이트맵과 언어별 RSS를 생성한다. Vite 설정에서 별도로 Markdown을 파싱하지 않는다. +- `src/lib/structured-data.ts`: 공통 사이트 설정을 사용해 글·블로그·프로젝트의 구조화 데이터를 생성한다. + +사이트맵에는 noindex 경로를 넣지 않는다. 초안·예약 글·미번역 안내는 발행 목록에서 제외하며, hreflang에는 실제로 발행된 언어만 연결한다. canonical은 후행 슬래시를 통일하고 fragment를 제거한다. 기존 필터 쿼리의 noindex 정책은 유지한다. + +RSS에는 게시글만 넣는다. 게시글의 최초 발행일과 실제 수정일은 보존한다. 고정 페이지의 수정일은 `src/data/page-updates.ts`에 명시하며 빌드 시간으로 갱신하지 않는다. 기존 시리즈·태그·홈의 읽기 가이드와 관련 글 탐색을 유지한다. + +## 검증 + +`pnpm build` 후 `pnpm test:seo`, `pnpm test:sitemap-lastmod`, `pnpm check:internal-links`를 실행한다. 이동·언어·hydration 변경은 `pnpm test:browser`로 확인한다. SEO 검사는 사이트맵과 HTML의 canonical·언어 연결 일치, RSS와 발행 글의 일치, 게시글 날짜와 구조화 데이터의 일치를 확인한다. 브라우저 검사는 초기 HTML과 hydration 후 메타정보, 글 이동, 언어 전환과 없는 주소의 404를 확인한다. + +검사 통과는 Google 색인이나 순위 상승을 뜻하지 않는다. 배포 후에는 Search Console의 Google 선택 canonical, 색인 상태, 검색 노출과 클릭을 별도로 확인한다. 색인 요청은 자동 제출하지 않는다. + +참고: [Jekyll SEO Tag](https://github.com/jekyll/jekyll-seo-tag), [Jekyll Sitemap](https://github.com/jekyll/jekyll-sitemap), [Google canonical 안내](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls), [다국어 연결 안내](https://developers.google.com/search/docs/specialty/international/localized-versions). diff --git a/index.html b/index.html index 717146c..ffdf3b9 100644 --- a/index.html +++ b/index.html @@ -7,26 +7,10 @@ - Devy 블로그 — 백엔드·인프라·AI 개발 기록 | Devy Archive - - - - - - - - - - - - - - - - - - - + + Devy Archive + + diff --git a/package.json b/package.json index c5ab6f6..52a0d44 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "test:post-dates": "node --test scripts/post-dates.test.mjs", "test:charts": "node --test scripts/markdown-chart.test.mjs", "test:loading": "node --test scripts/async-loader.test.mjs scripts/loading.test.mjs", - "test:seo": "node --test scripts/seo.test.mjs", + "test:seo": "node --test scripts/seo.test.mjs scripts/seo-metadata.test.mjs", "test:sitemap-lastmod": "node --test scripts/sitemap-lastmod.test.mjs", "test:analytics": "node --test scripts/analytics.test.mjs", "test:rendering": "node --test scripts/rendering.test.mjs", diff --git a/scripts/prerender.mjs b/scripts/prerender.mjs index 1d79ce9..d20b433 100644 --- a/scripts/prerender.mjs +++ b/scripts/prerender.mjs @@ -1,13 +1,13 @@ import fs from "node:fs" import path from "node:path" import { fileURLToPath } from "node:url" -import { getPrerenderRoutes, render, preparePostContentForPrerender, getPostHydrationData } from "../dist-ssr/entry-server.js" +import { getPrerenderRoutes, render, preparePostContentForPrerender, getPostHydrationData, renderSeoHead, siteConfig as SITE, getFeedPosts, resolveSeo, escapeMarkup } from "../dist-ssr/entry-server.js" const __dirname = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.resolve(__dirname, "..") const distDir = path.resolve(rootDir, "dist") const template = fs.readFileSync(path.resolve(distDir, "index.html"), "utf-8") -const baseUrl = "https://dev.devy.dev" +const baseUrl = SITE.url function escapeAttr(value) { return value @@ -17,19 +17,6 @@ function escapeAttr(value) { .replace(/>/g, ">") } -function toFullTitle(title) { - return title ? `${title} | Devy Archive` : "Devy Archive" -} - -function toCanonicalPath(routePath) { - if (routePath === "/") return "/" - return routePath.endsWith("/") ? routePath : `${routePath}/` -} - -function toAbsoluteUrl(routePath) { - return `${baseUrl}${toCanonicalPath(routePath)}` -} - function safeJsonLd(jsonLd) { return JSON.stringify(jsonLd).replace(/[^<]*<\/title>/, `${escapeAttr(fullTitle)}`) - .replace(/()/, - `$1\n ` - ) - } + const head = renderSeoHead({ ...route, url: route.path, alternateUrls: route.alternates }, route.language || "ko") + if (!templateHtml.includes("")) throw new Error("Missing SEO head boundary") + return templateHtml + .replace(/[\s\S]*?/, () => `\n ${head}\n `) +} - if (route.alternates) { - const alternates = [ - route.alternates.ko ? ` ` : "", - route.alternates.en ? ` ` : "", - route.alternates.ko ? ` ` : "", - ].filter(Boolean).join("\n") - if (alternates) { - html = html.replace("", `${alternates}\n `) - } +function writeDiscoveryFiles(routes) { + const entries = routes.filter(route => !route.noindex).map(route => { + const seo = resolveSeo({ ...route, url: route.path, alternateUrls: route.alternates }, route.language || "ko") + if (new URL(seo.url).pathname !== route.path) throw new Error(`Non-canonical sitemap route: ${route.path}`) + return [ + " ", + ` ${escapeMarkup(seo.url)}`, + ...(route.lastmod ? [` ${escapeMarkup(route.lastmod)}`] : []), + ...seo.alternates.map(alt => ` `), + " ", + ].join("\n") + }) + const sitemap = ` + + +${entries.join("\n")} + +` + fs.writeFileSync(path.resolve(distDir, "sitemap.xml"), sitemap) + for (const language of ["ko", "en"]) { + const homePath = language === "en" ? "/en/" : "/" + const home = routes.find(route => route.path === homePath) + const seo = resolveSeo({ ...home, url: homePath }, language) + const items = getFeedPosts(language).map(post => { + const url = `${baseUrl}${language === "en" ? "/en" : ""}/posts/${post.slug}/` + if (!routes.some(route => route.path === new URL(url).pathname && !route.noindex)) throw new Error(`RSS target is not indexable: ${url}`) + return ` + ${escapeMarkup(post.title)} + ${escapeMarkup(url)} + ${escapeMarkup(url)} + ${escapeMarkup(post.description)} + ${new Date(post.date).toUTCString()} + ` + }) + const rss = ` + + + ${escapeMarkup(SITE.name)} + ${baseUrl}${homePath} + ${escapeMarkup(home.description)} + ${language} + +${items.join("\n")} + + +` + const feedPath = path.resolve(distDir, language === "en" ? "en/rss.xml" : "rss.xml") + fs.mkdirSync(path.dirname(feedPath), { recursive: true }) + fs.writeFileSync(feedPath, rss) } - - return html } function injectAppHtml(templateHtml, appHtml, routePath) { @@ -107,6 +109,8 @@ for (const route of routes) { fs.writeFileSync(outPath, html) } +writeDiscoveryFiles(routes) + const notFoundRoute = { path: "/404/", title: "404", diff --git a/scripts/seo-metadata.test.mjs b/scripts/seo-metadata.test.mjs new file mode 100644 index 0000000..d2e49dd --- /dev/null +++ b/scripts/seo-metadata.test.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { canonicalUrl, renderSeoHead, resolveSeo } from "../src/lib/seo.ts" + +test("canonical addresses normalize paths, retain legacy queries, and discard document fragments", () => { + assert.equal(canonicalUrl(), "https://dev.devy.dev/") + assert.equal(canonicalUrl("/en/posts/spring-ai-guide-01-setup#section"), "https://dev.devy.dev/en/posts/spring-ai-guide-01-setup/") + assert.equal(canonicalUrl("/tags?tag=C%2B%2B#filters:tag=java"), "https://dev.devy.dev/tags/?tag=C%2B%2B") + assert.throws(() => canonicalUrl("https://example.com/post"), /must belong/) +}) + +test("metadata escapes text and attribute values without corrupting literal replacement tokens", () => { + const html = renderSeoHead({ title: 'A & B