xiaohongshu
xiaohongshu
bellog-notion
Provides Notion CMS integration patterns and best practices for Bellog. Triggers when working with Notion data or implementing Notion-based features.
Full skill instructions
This skill defines how to work with Notion as a CMS in the Bellog blog project.
Bellog uses Notion as a headless CMS:
/src/lib/notion.ts - Notion API client & queries/src/lib/posts.ts - Cached data fetching/src/lib/tags.ts - Tag aggregation/src/types/index.d.ts - Type definitions/src/app/api/revalidate/route.ts - Cache invalidationinterface NotionPostProperties {
// Required properties
title: {
type: "title";
title: Array<RichTextItemResponse>;
};
date: {
type: "date";
date: { start: string } | null;
};
description: {
type: "rich_text";
rich_text: Array<RichTextItemResponse>;
};
slug: {
type: "rich_text";
rich_text: Array<RichTextItemResponse>;
};
tags: {
type: "multi_select";
multi_select: Array<{
name: string;
color: string;
}>;
};
status: {
type: "select";
select: {
name: "published" | "draft" | "archived";
} | null;
};
}
/src/lib/notion.tsimport { getAllPostsFromNotion } from '@/lib/notion';
// Fetches all posts with status = "published"
const posts = await getAllPostsFromNotion();
Returns:
Array<{
id: string;
title: string;
slug: string;
date: string;
description: string;
tags: string[];
status: string;
}>
Query Details:
status = "published"date descendingimport { getPostBySlugFromNotion } from '@/lib/notion';
const post = await getPostBySlugFromNotion('my-post-slug');
Returns: Single post object or null if not found
import { getPostRecordMap } from '@/lib/notion';
// Get full page content for rendering
const recordMap = await getPostRecordMap(pageId);
Returns: ExtendedRecordMap for react-notion-x
Use: When rendering full post content with NotionRenderer
function extractPlainText(
richText: Array<RichTextItemResponse>
): string {
return richText.map(item => item.plain_text).join('');
}
// Usage
const description = post.properties.description.rich_text
.map(item => item.plain_text)
.join('');
const title = post.properties.title.title
.map(item => item.plain_text)
.join('');
const tags = post.properties.tags.multi_select
.map(tag => tag.name);
const date = post.properties.date.date?.start || '';
/src/lib/posts.tsTwo-level caching:
cache() - Request deduplicationunstable_cache() - Persistent cachingimport { cache } from "react";
import { unstable_cache } from "next/cache";
import { getAllPostsFromNotion } from './notion';
export const getAllPosts = cache(
unstable_cache(
async () => {
const posts = await getAllPostsFromNotion();
// Sort by date descending
return posts.sort((a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
);
},
["all-posts"], // Cache key
{
revalidate: 3600, // 1 hour
tags: ["posts", "notion"] // For invalidation
}
)
);
["all-posts"] // All posts list
["post-{slug}"] // Individual post
["post-recordmap-{id}"] // Post content
["posts", "notion"] // Tag for bulk invalidation
File: /src/app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
export async function POST(request: Request) {
// Verify secret
const secret = request.nextUrl.searchParams.get('secret');
if (secret !== process.env.REVALIDATION_SECRET) {
return Response.json(
{ message: 'Invalid secret' },
{ status: 401 }
);
}
// Invalidate cache
revalidateTag('notion');
return Response.json({
revalidated: true,
now: Date.now()
});
}
Trigger from Notion webhook:
curl -X POST "https://bellog.com/api/revalidate?secret=YOUR_SECRET"
Manual trigger:
curl -X POST "http://localhost:3000/api/revalidate?secret=dev_secret"
All cached data with tag "notion":
import { NotionRenderer } from 'react-notion-x';
import { getPostRecordMap } from '@/lib/notion';
export default async function PostContent({ postId }: Props) {
// Fetch content
const recordMap = await getPostRecordMap(postId);
return (
<NotionRenderer
recordMap={recordMap}
fullPage={false}
darkMode={false} // Handle with useTheme in client
components={{
// Custom component overrides
Code: CustomCodeBlock,
Collection: CustomCollection,
Equation: CustomEquation
}}
/>
);
}
Override default rendering:
import { Code } from 'react-notion-x/build/third-party/code';
// Custom code block with line numbers
function CustomCodeBlock({ block }) {
return (
<div className="custom-code-wrapper">
<Code block={block} />
</div>
);
}
.env.local# Official Notion API
NOTION_API_KEY=secret_xxxxxxxxxxxxxxxxxxxxx
NOTION_DATABASE_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# notion-client (for react-notion-x)
NOTION_TOKEN_V2=v02%3Auser_token_or_cookie...
NOTION_ACTIVE_USER=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# Cache revalidation
REVALIDATION_SECRET=your_random_secret_string
NOTION_API_KEY:
NOTION_DATABASE_ID:
notion.so/workspace/[THIS_PART]?v=...NOTION_TOKEN_V2:
token_v2 valueNOTION_ACTIVE_USER:
notion_user_id value// /src/types/index.d.ts
export interface Post {
id: string;
title: string;
slug: string;
date: string;
description: string;
tags: string[];
status: PostStatus;
}
export type PostStatus = 'published' | 'draft' | 'archived';
// ✅ Type-safe access
import type { QueryDatabaseResponse } from '@notionhq/client/build/src/api-endpoints';
const page = response.results[0] as PageObjectResponse;
if (page.properties.title.type === 'title') {
const title = page.properties.title.title
.map(t => t.plain_text)
.join('');
}
try {
const posts = await getAllPostsFromNotion();
return posts;
} catch (error) {
console.error('Failed to fetch posts:', error);
// Return fallback
return [];
// Or rethrow for error boundary
throw new Error('Failed to load posts');
}
// Check property exists and has value
const date = post.properties.date?.date?.start || new Date().toISOString();
// Provide defaults
const description = post.properties.description?.rich_text?.[0]?.plain_text || '';
Limits:
Mitigation:
unstable_cacheAdd to Notion Database
Update TypeScript Types
// /src/types/index.d.ts
export interface Post {
// ... existing fields
author?: string; // New field
}
Extract in Notion Client
// /src/lib/notion.ts
export async function getAllPostsFromNotion() {
// ... existing code
const posts = results.map(page => ({
// ... existing fields
author: extractPlainText(page.properties.author.rich_text)
}));
}
Invalidate Cache
curl -X POST "http://localhost:3000/api/revalidate?secret=dev_secret"
// ✅ Correct - Always use caching
export const getPosts = cache(
unstable_cache(
async () => await notion.query(...),
['key'],
{ revalidate: 3600 }
)
);
// ❌ Wrong - Direct API calls
export async function getPosts() {
return await notion.query(...); // No caching!
}
// ✅ Correct - Provide defaults
const title = page.properties.title?.title?.[0]?.plain_text || 'Untitled';
// ❌ Wrong - Can crash if undefined
const title = page.properties.title.title[0].plain_text;
// ✅ Correct - Use tags
unstable_cache(
fetchFunction,
['key'],
{ tags: ['posts', 'notion'] } // Can invalidate by tag
);
// ❌ Wrong - No tags
unstable_cache(
fetchFunction,
['key'],
{} // Can't invalidate efficiently
);
// ✅ Correct - API calls in notion.ts, caching in posts.ts
// /src/lib/notion.ts
export async function getAllPostsFromNotion() { }
// /src/lib/posts.ts
export const getAllPosts = cache(unstable_cache(...));
// ❌ Wrong - Mix concerns
export const getAllPosts = async () => {
const response = await notion.databases.query(...); // Mixed!
}
// ✅ Correct - Explicit types
import type { PageObjectResponse } from '@notionhq/client/build/src/api-endpoints';
const page = result as PageObjectResponse;
// ❌ Wrong - Any types
const page: any = result;
// Cache post content separately
export const getPostContent = cache(
unstable_cache(
async (id: string) => await getPostRecordMap(id),
['post-content'],
{ revalidate: 3600, tags: ['notion'] }
)
);
// Fetch multiple posts in parallel
const [post1, post2] = await Promise.all([
getPostBySlug('slug-1'),
getPostBySlug('slug-2')
]);
// Only revalidate specific posts
revalidatePath(`/posts/${slug}`);
// Instead of everything
revalidateTag('notion');
export async function getRecentPosts(limit: number = 5) {
const allPosts = await getAllPosts();
return allPosts.slice(0, limit);
}
export async function getPostsByTag(tag: string) {
const allPosts = await getAllPosts();
return allPosts.filter(post => post.tags.includes(tag));
}
// /src/lib/tags.ts
export async function getTagCounts() {
const posts = await getAllPosts();
const counts = new Map<string, number>();
posts.forEach(post => {
post.tags.forEach(tag => {
counts.set(tag, (counts.get(tag) || 0) + 1);
});
});
return Array.from(counts.entries())
.map(([tag, count]) => ({ tag, count }))
.sort((a, b) => b.count - a.count);
}
Solution: Trigger revalidation
curl -X POST "/api/revalidate?secret=YOUR_SECRET"
Check: Are you calling API too frequently? Solution: Increase cache TTL, reduce manual revalidation
Check: Is property name exactly matching? Solution: Use Notion API to inspect property names
Check: Is NOTION_TOKEN_V2 valid? Solution: Re-copy token from browser cookies
// Fetch all posts
import { getAllPosts } from '@/lib/posts';
const posts = await getAllPosts();
// Fetch single post
import { getPostBySlugFromNotion } from '@/lib/notion';
const post = await getPostBySlugFromNotion('slug');
// Fetch post content
import { getPostRecordMap } from '@/lib/notion';
const recordMap = await getPostRecordMap(postId);
// Render content
import { NotionRenderer } from 'react-notion-x';
<NotionRenderer recordMap={recordMap} />
// Invalidate cache
revalidateTag('notion');
// Environment variables
NOTION_API_KEY
NOTION_DATABASE_ID
NOTION_TOKEN_V2
NOTION_ACTIVE_USER
REVALIDATION_SECRET
Remember: Notion is the source of truth. Always cache and always handle missing data gracefully.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience