Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 방지

Expand Down
25 changes: 25 additions & 0 deletions docs/seo.md
Original file line number Diff line number Diff line change
@@ -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).
24 changes: 4 additions & 20 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,10 @@
<meta name="naver-site-verification" content="285723bcf1d1a6cbcc547cce5f249758f4c43267" />
<meta name="google-site-verification" content="DHPJy4dX7hesl1Kl-WWs7e4l4P211suOLbmlkT-pAUE" />
<meta name="google-adsense-account" content="ca-pub-2383130502932429" />
<title>Devy 블로그 — 백엔드·인프라·AI 개발 기록 | Devy Archive</title>
<meta name="description" content="Devy의 기술 블로그입니다. 백엔드·클라우드 인프라·AI 개발과 운영에서 겪은 문제와 해결 과정을 기록합니다." />
<meta property="og:title" content="Devy Archive" />
<meta property="og:description" content="Devy의 기술 블로그입니다. 백엔드·클라우드 인프라·AI 개발과 운영에서 겪은 문제와 해결 과정을 기록합니다." />
<meta property="og:url" content="https://dev.devy.dev" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Devy Archive" />
<meta property="og:image" content="https://dev.devy.dev/og-image.png?v=20260922-5" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="What works, and why. — Engineering notes by Devy" />
<meta property="og:locale" content="ko_KR" />
<link rel="canonical" href="https://dev.devy.dev" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Devy Archive" />
<meta name="twitter:description" content="Devy의 기술 블로그입니다. 백엔드·클라우드 인프라·AI 개발과 운영에서 겪은 문제와 해결 과정을 기록합니다." />
<meta name="twitter:image" content="https://dev.devy.dev/og-image.png?v=20260922-5" />
<meta name="twitter:image:alt" content="What works, and why. — Engineering notes by Devy" />
<link rel="alternate" type="application/rss+xml" title="Devy Archive RSS" href="https://dev.devy.dev/rss.xml" />
<link rel="sitemap" type="application/xml" title="Sitemap" href="https://dev.devy.dev/sitemap.xml" />
<!-- seo:start -->
<title>Devy Archive</title>
<meta name="description" content="Devy의 기술 블로그입니다." data-seo="true" />
<!-- seo:end -->
<link rel="stylesheet" as="style" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css" />
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2383130502932429"
crossorigin="anonymous"></script>
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
114 changes: 59 additions & 55 deletions scripts/prerender.mjs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -17,19 +17,6 @@ function escapeAttr(value) {
.replace(/>/g, "&gt;")
}

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(/</g, "\\u003c")
}
Expand All @@ -40,48 +27,63 @@ function outputPathFor(routePath) {
}

function withHead(templateHtml, route) {
const fullTitle = toFullTitle(route.title)
const description = route.description || "Devy의 기술 블로그입니다. 백엔드·클라우드 인프라·AI 개발과 운영에서 겪은 문제와 해결 과정을 기록합니다."
const previewTitle = route.ogTitle || fullTitle
const previewDescription = route.ogDescription || description
const canonicalPath = route.canonicalPath || route.path
const fullUrl = toAbsoluteUrl(canonicalPath)
const ogType = route.type || "website"
const htmlLang = route.language === "en" ? "en" : "ko"

let html = templateHtml
.replace(/<html lang="[^"]*"/, `<html lang="${htmlLang}"`)
.replace(/<title>[^<]*<\/title>/, `<title>${escapeAttr(fullTitle)}</title>`)
.replace(/(<meta name="description" content=")[^"]*(")/, `$1${escapeAttr(description)}$2`)
.replace(/(<meta name="robots" content=")[^"]*(")/, `$1${route.noindex ? "noindex, nofollow" : "index, follow"}$2`)
.replace(/(<meta property="og:title" content=")[^"]*(")/, `$1${escapeAttr(previewTitle)}$2`)
.replace(/(<meta property="og:description" content=")[^"]*(")/, `$1${escapeAttr(previewDescription)}$2`)
.replace(/(<meta property="og:url" content=")[^"]*(")/, `$1${escapeAttr(fullUrl)}$2`)
.replace(/(<meta property="og:type" content=")[^"]*(")/, `$1${escapeAttr(ogType)}$2`)
.replace(/(<meta property="og:locale" content=")[^"]*(")/, `$1${route.language === "en" ? "en_US" : "ko_KR"}$2`)
.replace(/(<link rel="canonical" href=")[^"]*(")/, `$1${escapeAttr(fullUrl)}$2`)
.replace(/(<meta name="twitter:title" content=")[^"]*(")/, `$1${escapeAttr(previewTitle)}$2`)
.replace(/(<meta name="twitter:description" content=")[^"]*(")/, `$1${escapeAttr(previewDescription)}$2`)

if (!html.includes('meta name="robots"')) {
html = html.replace(
/(<meta name="description" content="[^"]*" \/>)/,
`$1\n <meta name="robots" content="${route.noindex ? "noindex, nofollow" : "index, follow"}" />`
)
}
const head = renderSeoHead({ ...route, url: route.path, alternateUrls: route.alternates }, route.language || "ko")
if (!templateHtml.includes("<!-- seo:start -->")) throw new Error("Missing SEO head boundary")
return templateHtml
.replace(/<html lang="[^"]*"/, `<html lang="${route.language || "ko"}"`)
.replace(/<!-- seo:start -->[\s\S]*?<!-- seo:end -->/, () => `<!-- seo:start -->\n ${head}\n <!-- seo:end -->`)
}

if (route.alternates) {
const alternates = [
route.alternates.ko ? ` <link rel="alternate" hreflang="ko-KR" href="${escapeAttr(toAbsoluteUrl(route.alternates.ko))}">` : "",
route.alternates.en ? ` <link rel="alternate" hreflang="en" href="${escapeAttr(toAbsoluteUrl(route.alternates.en))}">` : "",
route.alternates.ko ? ` <link rel="alternate" hreflang="x-default" href="${escapeAttr(toAbsoluteUrl(route.alternates.ko))}">` : "",
].filter(Boolean).join("\n")
if (alternates) {
html = html.replace("</head>", `${alternates}\n </head>`)
}
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 [
" <url>",
` <loc>${escapeMarkup(seo.url)}</loc>`,
...(route.lastmod ? [` <lastmod>${escapeMarkup(route.lastmod)}</lastmod>`] : []),
...seo.alternates.map(alt => ` <xhtml:link rel="alternate" hreflang="${alt.hreflang}" href="${escapeMarkup(alt.href)}"/>`),
" </url>",
].join("\n")
})
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
${entries.join("\n")}
</urlset>
`
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 ` <item>
<title>${escapeMarkup(post.title)}</title>
<link>${escapeMarkup(url)}</link>
<guid>${escapeMarkup(url)}</guid>
<description>${escapeMarkup(post.description)}</description>
<pubDate>${new Date(post.date).toUTCString()}</pubDate>
</item>`
})
const rss = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>${escapeMarkup(SITE.name)}</title>
<link>${baseUrl}${homePath}</link>
<description>${escapeMarkup(home.description)}</description>
<language>${language}</language>
<atom:link href="${seo.feedUrl}" rel="self" type="application/rss+xml"/>
${items.join("\n")}
</channel>
</rss>
`
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) {
Expand All @@ -107,6 +109,8 @@ for (const route of routes) {
fs.writeFileSync(outPath, html)
}

writeDiscoveryFiles(routes)

const notFoundRoute = {
path: "/404/",
title: "404",
Expand Down
27 changes: 27 additions & 0 deletions scripts/seo-metadata.test.mjs
Original file line number Diff line number Diff line change
@@ -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 <script> $& $1', description: '" onload="oops < &', url: "/posts/test" }, "ko")
assert.ok(html.includes("A &amp; B &lt;script&gt; $&amp; $1 | Devy Archive"))
assert.ok(html.includes('content="&quot; onload=&quot;oops &lt; &amp;"'))
assert.ok(!html.includes("<script>"))
})

test("only explicit translations and indexable article dates are emitted", () => {
const options = { type: "article", datePublished: "2026-01-01", dateModified: "2026-02-01", alternateUrls: { ko: "/posts/ko-only" } }
const seo = resolveSeo(options, "ko")
assert.deepEqual(seo.alternates.map(alt => alt.hreflang), ["ko-KR", "x-default"])
assert.equal(seo.meta.filter(tag => tag.name.startsWith("article:")).length, 2)
assert.equal(resolveSeo({ ...options, noindex: true }, "ko").meta.filter(tag => tag.name.startsWith("article:")).length, 0)
assert.equal(resolveSeo({ ...options, type: "website" }, "en").meta.filter(tag => tag.name.startsWith("article:")).length, 0)
assert.equal(resolveSeo({}, "en").feedUrl, "https://dev.devy.dev/en/rss.xml")
})
31 changes: 31 additions & 0 deletions scripts/seo.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,34 @@ test("non-indexable prerendered routes do not publish article structured data",
visit(dist)
assert.match(fs.readFileSync(path.join(dist, "404.html"), "utf8"), /<meta name="robots" content="noindex, nofollow"/)
})

test("sitemap and HTML publish exactly the same language alternatives", () => {
for (const [, entry] of sitemap.matchAll(/<url>([\s\S]*?)<\/url>/g)) {
const url = entry.match(/<loc>([^<]+)<\/loc>/)[1]
const xmlAlternates = [...entry.matchAll(/<xhtml:link rel="alternate" hreflang="([^"]+)" href="([^"]+)"/g)]
.map(match => ({ language: match[1], url: match[2] }))
assert.deepEqual(alternates(pages.get(url)), xmlAlternates, url)
}
})

test("RSS lists exactly the published articles and HTML links to the feed in its own language", () => {
for (const prefix of ["", "/en"]) {
const feed = fs.readFileSync(path.join(dist, prefix, "rss.xml"), "utf8")
const items = [...feed.matchAll(/<item>([\s\S]*?)<\/item>/g)].map(match => match[1].match(/<link>([^<]+)<\/link>/)[1])
const articles = urls.filter(url => new URL(url).pathname.startsWith(`${prefix}/posts/`) && new URL(url).pathname !== `${prefix}/posts/`)
assert.deepEqual([...items].sort(), articles.sort())
for (const [url, html] of pages) {
if (new URL(url).pathname.startsWith("/en/") !== Boolean(prefix)) continue
assert.match(html, new RegExp(`type="application/rss\\+xml"[^>]*href="${origin}${prefix}/rss.xml"`), url)
}
}
})

test("article time metadata agrees with structured data", () => {
for (const [url, html] of pages) {
if (!/\/(?:en\/)?posts\/[^/]+\/$/.test(new URL(url).pathname)) continue
const article = schemas(html)[0]
assert.equal(html.match(/property="article:published_time" content="([^"]+)"/)?.[1], article.datePublished, url)
assert.equal(html.match(/property="article:modified_time" content="([^"]+)"/)?.[1], article.dateModified, url)
}
})
Loading
Loading