Files
2nd/10_Wiki/Topics/Frontend/Sanity Studio.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

221 lines
6.3 KiB
Markdown

---
id: wiki-2026-0508-sanity-studio
title: Sanity Studio
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Sanity, Sanity CMS, Sanity Headless]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [headless-cms, sanity, content, structured-content]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript
framework: Sanity v3 + React
---
# Sanity Studio
## 매 한 줄
> **"매 Sanity Studio는 customizable single-page editor 를 wrap 한 headless CMS"**. v3 (2023) 부터 React 기반 fully composable, 매 schema-as-code (TS), GROQ query language, Portable Text, real-time collaboration. 2026 기준 Contentful / Strapi 의 main alternative — 매 dev experience + customization 이 강점.
## 매 핵심
### 매 컴포넌트
- **Studio**: editor SPA (React, self-host or Sanity hosted)
- **Content Lake**: cloud datastore (도큐먼트 store)
- **GROQ**: query language (graph + projection)
- **Portable Text**: rich text JSON spec
### 매 schema 방식
- TS 로 schema 정의 → studio UI 자동 생성
- Field type: string, number, image, reference, array, object, slug, portable text...
- Custom input component 도 React 로 작성 가능
### 매 응용
1. Marketing sites (Next.js + Sanity).
2. Editorial / publishing (long-form, structured).
3. E-commerce content (product copy, lookbooks).
4. Multi-channel content (web + mobile + email).
## 💻 패턴
### Schema 정의
```typescript
// schemas/post.ts
import { defineType, defineField } from "sanity";
export const post = defineType({
name: "post",
title: "Post",
type: "document",
fields: [
defineField({ name: "title", type: "string", validation: (R) => R.required() }),
defineField({
name: "slug",
type: "slug",
options: { source: "title", maxLength: 96 },
}),
defineField({ name: "author", type: "reference", to: [{ type: "author" }] }),
defineField({ name: "body", type: "array", of: [{ type: "block" }, { type: "image" }] }),
defineField({ name: "publishedAt", type: "datetime" }),
],
});
```
### sanity.config.ts
```typescript
import { defineConfig } from "sanity";
import { structureTool } from "sanity/structure";
import { visionTool } from "@sanity/vision";
import { post, author } from "./schemas";
export default defineConfig({
name: "default",
title: "My Studio",
projectId: process.env.SANITY_PROJECT_ID!,
dataset: "production",
plugins: [structureTool(), visionTool()],
schema: { types: [post, author] },
});
```
### GROQ query
```typescript
import { createClient } from "@sanity/client";
const client = createClient({
projectId: process.env.SANITY_PROJECT_ID!,
dataset: "production",
apiVersion: "2026-01-01",
useCdn: true,
});
const posts = await client.fetch<Post[]>(`
*[_type == "post" && publishedAt < now()] | order(publishedAt desc) [0...10] {
_id, title, slug, publishedAt,
"authorName": author->name,
"image": mainImage.asset->url
}
`);
```
### Next.js 15 integration with revalidate
```typescript
// app/posts/[slug]/page.tsx
import { client } from "@/lib/sanity";
import { notFound } from "next/navigation";
export const revalidate = 60;
export default async function Page({
params,
}: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await client.fetch(
`*[_type == "post" && slug.current == $slug][0]`,
{ slug },
{ next: { tags: [`post:${slug}`] } },
);
if (!post) notFound();
return <article>{post.title}</article>;
}
```
### On-demand revalidation via webhook
```typescript
// app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";
import { parseBody } from "next-sanity/webhook";
export async function POST(req: Request) {
const { isValidSignature, body } = await parseBody<{ slug: string; _type: string }>(
req, process.env.SANITY_REVALIDATE_SECRET!,
);
if (!isValidSignature) return Response.json({ ok: false }, { status: 401 });
if (body?._type === "post") revalidateTag(`post:${body.slug}`);
return Response.json({ ok: true });
}
```
### Portable Text rendering
```tsx
import { PortableText, type PortableTextComponents } from "@portabletext/react";
const components: PortableTextComponents = {
types: {
image: ({ value }) => <img src={value.asset.url} alt={value.alt} />,
},
marks: {
link: ({ value, children }) => <a href={value.href}>{children}</a>,
},
};
export function Body({ value }: { value: any }) {
return <PortableText value={value} components={components} />;
}
```
### Custom input component
```tsx
// schemas/inputs/EmojiInput.tsx
import { TextInput, Card } from "@sanity/ui";
import { set, unset } from "sanity";
export function EmojiInput(props: any) {
return (
<Card padding={2}>
<TextInput
value={props.value || ""}
onChange={(e) =>
props.onChange(e.currentTarget.value ? set(e.currentTarget.value) : unset())
}
/>
</Card>
);
}
```
### TypeGen for type-safe queries
```bash
npx sanity@latest typegen generate
# generates sanity.types.ts with full TS types per query
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Dev-first, code-driven schema | Sanity |
| Non-tech editor, off-the-shelf | Contentful / Storyblok |
| Self-host, full control | Strapi / Payload |
| 매 real-time collab + custom UI | Sanity (강점) |
| Tiny site / blog | MDX in repo (overkill 회피) |
**기본값**: Sanity v3 + Next.js 15 + GROQ + Portable Text + TypeGen.
## 🔗 Graph
## 🤖 LLM 활용
**언제**: Marketing / editorial site, 매 dev-driven schema, custom editor needs. 매 Next.js + cloud CMS 의 경우.
**언제 X**: Tiny static blog (MDX 충분), enterprise with strict on-prem.
## ❌ 안티패턴
- **`useCdn: true` for drafts**: preview 모드에서 매 stale data. Preview 시 false.
- **Naked GROQ in components**: 매 query 를 lib/queries.ts 로 모으고 typegen.
- **No webhook revalidation**: 매 시간 단위 revalidate 만 → editor 답답함. On-demand webhook 필수.
- **Schema in studio UI**: 매 schema-as-code 가 v3 의 핵심. 매 GUI 편집 X.
## 🧪 검증 / 중복
- Verified (sanity.io docs v3, 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Sanity Studio full content |