Crash Courses · Masters
The Local API
Query Payload data directly in Next.js server components using the Local API.
10 min read+175 XP on completionCert: Payload CMS Crash Course
Tap any word in the text below to start reading from there.
The Local API
The Local API calls Payload directly from server components — no HTTP round-trip. The fastest way to query data in a Next.js + Payload app.
Setup
// lib/payload.ts
import configPromise from '@payload-config'
import { getPayload } from 'payload'
export const getPayloadClient = async () => {
return getPayload({ config: configPromise })
}payload.find()
// Server component
export default async function BlogPage() {
const payload = await getPayloadClient()
const { docs: posts } = await payload.find({
collection: 'posts',
where: { status: { equals: 'published' } },
sort: '-publishedAt', // - prefix = descending
limit: 10,
depth: 1, // populate author relationship
})
return (
<main>
{posts.map(post => (
<PostCard key={post.id} post={post} />
))}
</main>
)
}payload.findByID()
import { notFound } from 'next/navigation'
export default async function PostPage({ params }: { params: { slug: string } }) {
const payload = await getPayloadClient()
const { docs } = await payload.find({
collection: 'posts',
where: { slug: { equals: params.slug }, status: { equals: 'published' } },
limit: 1,
})
const post = docs[0]
if (!post) notFound()
return <PostDetail post={post} />
}payload.create() (Server Action)
'use server'
import { getPayloadClient } from '@/lib/payload'
export async function createComment(postId: string, text: string, userId: string) {
const payload = await getPayloadClient()
return payload.create({
collection: 'comments',
data: {
post: postId,
author: userId,
text,
},
})
}Reading progress
0% read
In this module
payload.find()
payload.findByID()
payload.create()
depth
0%