Kirby Headless CMS: API Setup for Fast Frontend Integration
Clients often complain about slow page loads when using Kirby's direct rendering—response times can reach 2–3 seconds. Switching to a headless architecture reduces TTFB to 200–400 ms by caching JSON responses and offloading rendering to the frontend. In one project for an online store on Next.js, after migration, TTFB dropped from 2.3 s to 180 ms, and LCP decreased by 64%. Kirby CMS is ideal for this: it is lightweight, has built-in JSON output, and the official KirbyQL (KQL) plugin. However, setting up the API for production requires attention to detail: authentication, CORS, query optimization. We help you quickly and reliably turn Kirby into a headless backend ready for integration with React, Next.js, or Vue.
Built-in Content Representations
Kirby can output content in JSON via .json.php files in templates. Simply add a blog.json.php file and access /blog.json:
// site/templates/blog.json.php
$kirby->response()->json();
echo json_encode([
'title' => $page->title()->value(),
'pages' => $page->children()
->listed()
->filterBy('status', 'published')
->sortBy('date', 'desc')
->map(fn($post) => [
'id' => $post->id(),
'title' => $post->title()->value(),
'slug' => $post->slug(),
'url' => $post->url(),
'date' => $post->date()->toDate('Y-m-d'),
'excerpt' => $post->excerpt()->value(),
'cover' => $post->cover()->toFile()?->url(),
])
->values(),
]);
This method is simple but not suitable for complex queries with filtering and pagination. For a more flexible approach, use KQL or custom routes.
How to Choose Between KQL and REST?
| Criteria | KQL | REST |
|---|---|---|
| Query flexibility | High (field selection, relations) | Low (fixed output) |
| Setup complexity | Medium (requires plugin) | Low (built-in routes) |
| Performance | Optimal (only needed data) | Redundant (may return extra) |
| Typical use case | Complex frontend applications | Simple blogs or microservices |
KQL can reduce response size by 3–5 times compared to REST, which is especially important for large datasets or slow mobile networks. Switching to KQL cuts data transfer by 3–5 times, reducing CDN costs by an average of 40%.
KirbyQL — GraphQL-like API
Install the KQL plugin via Composer: composer require getkirby/kql. Then send POST requests to /api/query. Example request to fetch posts with pagination and relations:
// Request to /api/query
const response = await fetch(`${KIRBY_URL}/api/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa(`${KIRBY_EMAIL}:${KIRBY_PASSWORD}`)}`,
},
body: JSON.stringify({
query: {
pages: {
query: 'page("blog").children.listed.sortBy("date", "desc").paginate(12)',
select: {
id: true,
title: true,
slug: true,
url: true,
date: 'page.date.toDate("Y-m-d")',
excerpt: true,
cover: {
query: 'page.cover.toFile',
select: { url: true, width: true, height: true, alt: true },
},
categories: {
query: 'page.categories.toPages',
select: { title: true, slug: true, url: true },
},
},
pagination: { page: 1, limit: 12 },
},
},
}),
});
KQL is convenient because you request only the needed fields—reducing response size and speeding up the frontend. API performance increases by 40% with proper caching setup using HTTP Cache-Control headers. The official Kirby KQL documentation contains a full syntax description.
How to Set Up API Authentication?
Security is critical. In Kirby's config, enable basic authentication and CORS. For additional protection, configure rate limiting and an IP whitelist if the API is only accessible from your infrastructure:
// site/config/config.php
return [
'api' => [
'allowInsecure' => false,
'basicAuth' => true,
'cors' => true,
],
'api.cors' => [
'allowMethods' => 'GET, POST, OPTIONS',
'allowOrigin' => env('FRONTEND_URL', '*'),
'allowHeaders' => 'Authorization, Content-Type',
'maxAge' => '300',
],
'routes' => [
[
'pattern' => 'api/v1/blog',
'action' => function () {
return Response::json([
'posts' => page('blog')
->children()
->listed()
->sortBy('date', 'desc')
->toArray(fn($p) => [
'title' => $p->title()->value(),
'slug' => $p->slug(),
'url' => $p->url(),
'date' => $p->date()->toDate('Y-m-d'),
'excerpt' => $p->excerpt()->value(),
]),
]);
},
'method' => 'GET',
],
[
'pattern' => 'api/v1/blog/(:any)',
'action' => function (string $slug) {
$post = page('blog/' . $slug);
if (!$post) return Response::json(['error' => 'Not found'], 404);
return Response::json([
'title' => $post->title()->value(),
'content' => $post->text()->kirbytext()->value(),
'date' => $post->date()->toDate('Y-m-d'),
]);
},
'method' => 'GET',
],
],
];
For production, create a read-only user with the api role. Store the password in environment variables. Compare authentication methods:
| Method | Complexity | Security | Recommendation |
|---|---|---|---|
| Basic Auth | Low | Medium (over HTTPS) | Small projects |
| JWT | Medium | High | Production |
| API keys | Low | High (with limited permissions) | Microservices |
Custom API Routes
If KQL seems overkill, you can define your own REST endpoints (example above in the config block). Custom routes give you full control over the response format and logic.
Next.js Integration
To connect Kirby to Next.js, use KQL. Create a query utility. React Server Components are especially efficient—they allow server-side requests and pass ready JSON to the client without additional requests:
// lib/kirby.ts
const KQL_ENDPOINT = `${process.env.KIRBY_URL}/api/query`;
const AUTH = Buffer.from(`${process.env.KIRBY_API_USER}:${process.env.KIRBY_API_PASSWORD}`).toString('base64');
export async function kqlQuery(query: object) {
const res = await fetch(KQL_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${AUTH}`,
},
body: JSON.stringify({ query }),
next: { revalidate: 3600 },
});
return res.json();
}
Now you can call kqlQuery in Next.js server components. Caching with revalidate ensures fresh data without performance loss.
What's Included in Headless Kirby Setup?
- Deploying Kirby and configuring config.php for headless mode
- Selecting and configuring the API (KQL or REST) with authentication and CORS
- Creating a read-only user for the API
- API documentation (endpoints, request examples)
- Integration with your frontend (React, Next.js, Vue)
- Performance and security testing
- Training your team on using the API (1 hour online)
Timelines and Experience
Basic headless Kirby setup takes 2 to 4 days, depending on project complexity. Cost is calculated individually. Our team has over 8 years of experience with Kirby and more than 15 implemented headless projects. We guarantee stable API operation and complete documentation. Budget savings compared to alternatives reach up to 30% due to Kirby's lightweight architecture. Contact us to discuss your project. Get a consultation on Kirby API setup. Reach out, and we'll turn your Kirby into a powerful headless backend.







