🦭 Kirby, but headless only – KQL with bearer token, Express-esque middlewares & more

Overview

Kirby Headless Starter

ℹ️ Send a Bearer test authorization header with a request to the live playground to test this headless starter.

This starter kit is intended for an efficient and straight forward headless usage of Kirby. Thus, you will only be able to fetch JSON-encoded data. No visual data shall be presented.

Routing and JSON-encoded responses are handled by the internal routes.

Key Features

  • 🦭 Optional bearer token for authentication
  • 🧩 KQL with bearer token support
    • Post requests to /query
  • ⚡️ Cached KQL results
  • 🗂 Templates present JSON instead of HTML
    • Fetch either /example or /example.json
  • 🦾 Express-esque API builder with middleware support

Prerequisites

  • PHP 8.0+

Kirby is not a free software. You can try it for free on your local machine but in order to run Kirby on a public server you must purchase a valid license.

Setup

Composer

Kirby-related dependencies are managed via Composer and located in the vendor directory. To install them, run:

composer install

Environment Variables

Duplicate the .env.development.example as .env:

cp .env.example .env

Optionally, adapt it's values.

Usage

Bearer Token

If you prefer to use a token to secure your Kirby installation, set the environment variable KIRBY_HEADLESS_API_TOKEN with a token of your choice.

You will then have to provide the header Bearer ${token} with each request.

⚠️ Without a token the /query route would be publicly accessible by everyone. Be careful.

Data Fetching

You can fetch data by using KQL or Templates.

Templates

Create templates just like you normally would in any Kirby project. Instead of writing HTML, we build arrays and encode them to JSON. The internal headless plugin will add the correct content type and also handles correct caching.

Example template:

# /site/templates/about.php

$data = [
  'title' => $page->title()->value(),
  'layout' => $page->layout()->toLayouts()->toArray(),
  'address' => $page->address()->value(),
  'email' => $page->email()->value(),
  'phone' => $page->phone()->value(),
  'social' => $page->social()->toStructure()->toArray()
];

echo \Kirby\Data\Json::encode($data);

KQL

ℹ️ Keep in mind the KQL endpoint /api/query remains and uses the username/password authentication.

KQL is available under /query and requires a bearer token set.

import { $fetch } from "ohmyfetch"

const apiToken = "test"

const response = await $fetch(
  "https://example.com/query",
  {
    method: 'POST'
    body: {
      query: "page('notes').children",
      select: {
        title: true,
        text: "page.text.toBlocks.toArray",
        slug: true,
        date: "page.date.toDate('d.m.Y')",
      },
    },
    headers: {
      Authentication: `Bearer ${apiToken}`,
    },
  },
);

console.log(response);

API Builder

This headless starter includes an Express-esque API builder, defined in the KirbyHeadless\Api\Api class. You can use it to re-use logic like handling a token or verifying some other incoming data.

Take a look at the built-in routes to get an idea how you can use the API builder to chain complex route logic.

It is also useful to consume POST requests including JSON data:

# /site/config/routes.php
[
    'pattern' => 'post-example',
    'method' => 'POST',
    'action' => Api::createHandler(
        [Middlewares::class, 'hasBearerToken'],
        [Middlewares::class, 'hasBody'],
        function ($context) {
            // Get the data of the POST request
            $data = $context['body'];

            // Do something with `$data` here

            return Api::createResponse(201);
        }
    )
]

You you use one of the built-in middlewares or write custom ones:

/**
 * Check if `foo` is sent with the request
 * and bail with an 401 error if not
 *
 * @param array $context
 * @return mixed
 */
public static function hasFooParam($context)
{
    if (empty(get('foo'))) {
        return Api::createResponse(401);
    }
}

Deployment

ℹ️ See ploi-deploy.sh for exemplary deployment instructions.

ℹ️ Some hosting environments require to uncomment RewriteBase / in .htaccess to make site links work.

Background

Why Not Use Content Representations?

Content representations are great. But they require a non-representing template. Otherwise, the content representation template just would not be read by Kirby. This means, you would have to create the following template structure:

  • default.php
  • default.json.php
  • home.php
  • home.json.php
  • … and so on

To simplify this approach, we use the standard template structure, but encode each template's content as JSON via the internal route middleware.

License

MIT License © 2022 Johann Schopplich

You might also like...
Helper to automatically load various Kirby extensions in a plugin

Autoloader for Kirby Helper to automatically load various Kirby extensions in a plugin Commerical Usage This package is free but if you use it in a co

Add information about PGP public keys on upload in Kirby v3
Add information about PGP public keys on upload in Kirby v3

Kirby3 GnuPG This plugin adds information about PGP public keys on upload, using gpg binary (which needs to be installed for this to work). Getting st

A Frankenstein's monster: Kirby inside of Laravel.

A Kirby-Laravel Starter Kit This is an experimental starter kit for using Kirby within Laravel (a little like Statamic). In my limited experience it r

Kirby wrapper for automated content accessibility checkers Editoria11y and Sa11y

Kirby3 A11yprompter For a comprehensive overview of Sa11y and Editoria11y, how they can assist maintaining an accessible website by supporting content

Plugin for Kirby that allows you to load assets generated by Vite.

Kirby Vite Plugin Plugin for Kirby that allows you to load assets generated by Vite. In development mode, assets are loaded from Vite's development se

Kirby plugin to visually show hidden characters in all kind of input fields and their previews.
Kirby plugin to visually show hidden characters in all kind of input fields and their previews.

Kirby Hidden Characters Kirby plugin to visually show hidden characters in all kind of input fields and their previews. This includes white spaces and

Kirby 3 Plugin for running jobs like cleaning the cache from within the Panel, PHP code, CLI or a cronjob

Kirby 3 Janitor Kirby 3 Plugin for running jobs. It is a Panel Button! It has jobs build-in for cleaning the cache, sessions, create zip-backup, pre-g

A simple wrapper around vlucas' PHP dotenv library for Kirby CMS.

kirby-phpdotenv A simple wrapper around vlucas' PHP dotenv library for Kirby CMS. Why? I've been using .env in my Kirby projects for a while, but I go

Traits used primarily in the v6 package but also available as a helper package for applications

Phalcon Traits This package contains traits with methods that are used for Phalcon v6 onward. It can also be useful to others that want short snippets

Comments
  • Can I securely fetch templates without auth?

    Can I securely fetch templates without auth?

    Hi Johann,

    thanks a lot for the headless starter. After having started the whole Kirby headless discussion a few days agai, I am still trying to make sense of it.

    Lukas told me in the Discord channel:

    Yes, absolutely. Content representations are intended to be used without authentication. As you can fully control the data that they output, you can make sure that no sensitive data is leaked.

    If you want to request the data from a JS frontend, the data is considered public by definition.

    Can the templates in your headless starter used in the same sense? As in, without auth, only exposing the public data that I choose? Or will I expose sensitive information as soon as I turn of the token option?

    Would love to set up the templates as you've shown in the README and then consume those via a JS frontend without auth. Is this possible and does this make sense?

    Thanks!

    opened by trych 1
Owner
Johann Schopplich
Web designer/developer. Pharmacist prior to that.
Johann Schopplich
Perch Dashboard app for exporting content to (Kirby) text files and Kirby Blueprint files

toKirby Perch Dashboard app for exporting content to (Kirby) text files and Kirby Blueprint files. You can easily install and test it in a few steps.

R. Banus 4 Jan 15, 2022
This Kirby V3 Plugin brings snippets and blueprints together in one place. It includes useful tools that completely changing the way you work with Kirby: Fast and well organized.

Kirby Components Overview Do you love to make awesome projects with Kirby CMS? Do you also find it difficult to switch between snippets and blueprints

Roman Gsponer 6 May 31, 2023
This is wegare tools but all-in-one installer only, exclude GUI

All In One Installer for Wegare Tools This is wegare tools, but this is all-in-one. Here is the source https://github.com/wegare123?tab=repositories I

Helmi Amirudin 3 Jul 29, 2022
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
Implementation of the Token Bucket algorithm in PHP.

Token Bucket This is a threadsafe implementation of the Token Bucket algorithm in PHP. You can use a token bucket to limit an usage rate for a resourc

null 477 Jan 7, 2023
DiscordLookup | Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more...

DiscordLookup Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more... Website Getting Help Tool

Felix 69 Dec 23, 2022
Ratio plugin is a luck plugin. The more lucky you are, the more you win!

Ratio Ratio plugin is a luck plugin. The more lucky you are, the more you win Features When you break a block (Cobblestone), it gives/puts you somethi

Ali Tura Çetin 2 Apr 25, 2022
Kirby Janitor job for staging

Simple staging Janitor jobs Plugin for very simple staging setup for https://github.com/bnomei/kirby3-janitor/ (required). Beta quality - use at your

Florian Karsten 8 Nov 27, 2022
This plugin allows you to create many-to-many relationships between pages in Kirby and synchronizes them on both sides.

Kirby 3 Many To Many Field This plugin allows you to create many-to-many relationships between pages in Kirby.

Jonas Holfeld 41 Nov 19, 2022
Color-managed thumbnails for Kirby 3

ImageKit for Kirby 3 This is not directly related for ImageKit for Kirby 2, but based on the same idea of improving Kirby’s built-in image processing

Fabian Michael 13 Nov 21, 2022