Sådan læser du CMS-indhold i Next.js — loader-funktioner, sider, statisk generering og metadata.
Læsning af indhold
Alt indhold læses server-side med fs:
import { readFileSync, readdirSync, existsSync } from 'fs';
import { join } from 'path';
const CONTENT = join(process.cwd(), 'content');
export function getCollection(name: string) {
const dir = join(CONTENT, name);
if (!existsSync(dir)) return [];
return readdirSync(dir)
.filter(f => f.endsWith('.json'))
.map(f => JSON.parse(readFileSync(join(dir, f), 'utf-8')))
.filter(d => d.status === 'published');
}
export function getDocument(collection: string, slug: string) {
const file = join(CONTENT, collection, `${slug}.json`);
if (!existsSync(file)) return null;
return JSON.parse(readFileSync(file, 'utf-8'));
}Blog-listeside
// app/blog/page.tsx
import { getCollection } from '@/lib/content';
export default function BlogPage() {
const posts = getCollection('posts')
.sort((a, b) => (b.data.date ?? '').localeCompare(a.data.date ?? ''));
return (
<div>
<h1>Blog</h1>
{posts.map(post => (
<a key={post.slug} href={`/blog/${post.slug}`}>
<h2>{post.data.title}</h2>
<p>{post.data.excerpt}</p>
</a>
))}
</div>
);
}Vigtige mønstre
- Kun Server Components — indhold læses ved build/request-tid
generateStaticParams— prægenerer alle sider ved build-tidgenerateMetadata— SEO-metadata fra CMS_seo-felter- Filtrer altid på published —
status === 'published'for at skippe kladder - Hardkod aldrig indhold — alt fra CMS JSON-filer