# Android quickstart (Jetpack Compose)

> An Android app in Jetpack Compose that shows your CMS Orbit pages by their address, draws their components as composables, reads drafts through your own server and refreshes with pull to refresh.

Source: https://docs.bifrostorbit.com/cms/developers/quickstart-android/

This guide builds the Northwilds app: an Android app in Jetpack Compose that shows the pages of the Northwilds website from CMS Orbit. Every published page opens by its address, the components editors place are drawn by your own composables, a separate drafts build shows unpublished changes to your team, and the app reloads content when it is out of date or when someone pulls to refresh.

It uses the [Kotlin SDK](https://docs.bifrostorbit.com/cms/developers/sdk-kotlin/), `com.bifrostorbit:cms-sdk`. An app works differently from a website in two places, drafts and refresh, and steps 7 and 8 say plainly what an app can and cannot do there.

Tested with: Android Gradle plugin 9.5.1, Gradle 9.8.2, Kotlin 2.4.21, Compose BOM 2026.09.00, `com.bifrostorbit:cms-sdk` 0.2.0, JDK 17, an Android 16 (API 36) emulator, and Ktor 3.6.1 for the drafts server.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-android](https://github.com/bifrost-orbit/cms-starter-android), the finished code of this guide.

## Before you start

You need:

- A CMS Orbit space with at least one published page.
- A public key, which starts with `cms_pk_`, and for step 7 a secret key with **Read drafts** on, which starts with `cms_sk_`. Step 4, **Create the two keys**, of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) shows how to create both in **Configuration › API keys**.
- The API address, `https://api.bifrostorbit.com/cms`, and the key of the region the app shows, such as `global`. Step 3 of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) shows where to find the region key.
- Android Studio, or the Android SDK and JDK 17 or later.

The public key reads published content only, so it may ship inside the app. The secret key never goes into the app: see step 7.

## 1. Create the project

In Android Studio, select **New Project › Empty Activity** and use:

- **Name:** `Northwilds`
- **Package name:** `com.northwilds.app`
- **Minimum SDK:** API 24
- **Build configuration language:** Kotlin DSL

Replace the generated Gradle files and manifest with the ones below. This guide writes library versions straight into `app/build.gradle.kts` so every file is complete on the page; move them into `gradle/libs.versions.toml` if you prefer the version catalogue. You can delete the generated `ui/theme` folder, as the app uses the default Material 3 theme.

```kotlin
// settings.gradle.kts
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "Northwilds"
include(":app")
```

```kotlin
// build.gradle.kts
plugins {
    id("com.android.application") version "9.5.1" apply false
    id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false
    id("org.jetbrains.kotlin.plugin.serialization") version "2.4.21" apply false
}
```

Android Gradle plugin 9 compiles Kotlin itself, so there is no `org.jetbrains.kotlin.android` plugin. The serialization plugin lets you decode CMS fields into your own classes.

```properties
# gradle.properties
org.gradle.jvmargs=-Xmx2g
android.useAndroidX=true
```

```xml
<!-- app/src/main/AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:label="Northwilds"
        android:theme="@android:style/Theme.Material.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
```

## 2. Install the SDK

Add the SDK and the Compose libraries to the app module. This is the whole file; step 3 explains the `setting` lines.

```kotlin
// app/build.gradle.kts
import java.util.Properties

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.plugin.compose")
    id("org.jetbrains.kotlin.plugin.serialization")
}

val local = Properties().apply {
    rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use(::load)
}

fun setting(name: String, default: String = ""): String = "\"${local.getProperty(name) ?: default}\""

android {
    namespace = "com.northwilds.app"
    compileSdk = 37

    defaultConfig {
        applicationId = "com.northwilds.app"
        minSdk = 24
        targetSdk = 36
        versionCode = 1
        versionName = "1.0"

        buildConfigField("String", "CMS_API_URL", setting("cms.apiUrl", "https://api.bifrostorbit.com/cms"))
        buildConfigField("String", "CMS_PUBLIC_KEY", setting("cms.publicKey"))
        buildConfigField("String", "CMS_REGION", setting("cms.region", "global"))
        buildConfigField("String", "DRAFTS_TOKEN", "\"\"")
    }

    buildFeatures {
        compose = true
        buildConfig = true
    }
}

dependencies {
    implementation("com.bifrostorbit:cms-sdk:0.2.0")

    implementation(platform("androidx.compose:compose-bom:2026.09.00"))
    implementation("androidx.compose.material3:material3")
    implementation("androidx.activity:activity-compose:1.13.0")
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
    implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
    implementation("androidx.navigation:navigation-compose:2.10.2")
    implementation("io.coil-kt.coil3:coil-compose:3.6.3")
    implementation("io.coil-kt.coil3:coil-network-okhttp:3.6.3")
}
```

- The current Compose and OkHttp libraries need `compileSdk = 37`. If the platform is not installed yet, Android Studio, or Gradle with accepted licences, downloads it on the first build.
- Coil loads images. Its OkHttp module shares the HTTP stack the SDK already brings.
- The SDK is on [Maven Central](https://central.sonatype.com/artifact/com.bifrostorbit/cms-sdk), where you can see the latest version.
- The file reads `local.properties` before you add the settings in step 3, and that is fine: it skips settings that are not there yet and uses the defaults, so Gradle syncs now. The settings take effect on the next sync or build after step 3.

## 3. Add the settings

Android Studio keeps `local.properties` out of source control, so the settings go there, after the `sdk.dir` line it wrote:

```properties
# local.properties
cms.apiUrl=https://api.bifrostorbit.com/cms
cms.publicKey=cms_pk_…
cms.region=global
```

The `setting` function in `app/build.gradle.kts` reads them into `BuildConfig`. On a build server, write the same lines into `local.properties` from your secrets before building. A public key in an app is fine: anyone who unpacks the app can read it, and it can only read what is already published.

## 4. Create the client

Create one client for the whole app. It is safe to use from many coroutines at once.

```kotlin
// app/src/main/java/com/northwilds/app/Cms.kt
package com.northwilds.app

import com.bifrostorbit.cms.CmsOrbitClient

object Cms {
    val client = CmsOrbitClient(BuildConfig.CMS_PUBLIC_KEY) {
        baseUrl = BuildConfig.CMS_API_URL
        defaultRegion = BuildConfig.CMS_REGION
    }
}
```

The SDK refuses a `cms_sk_` key on Android with an `IllegalArgumentException`, so a secret key cannot end up in the app by mistake.

## 5. Show a page by its address

Every screen in the app is one CMS page, opened by its address, such as `/` or `/products/cms-orbit`. A Navigation Compose route carries the address, and links inside the content open the next page in the app.

```kotlin
// app/src/main/java/com/northwilds/app/MainActivity.kt
package com.northwilds.app

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalUriHandler
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import kotlinx.serialization.Serializable

@Serializable
data class PageRoute(val path: String = "/")

val LocalOpenLink = staticCompositionLocalOf<(String) -> Unit> { {} }

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                val navController = rememberNavController()
                val uriHandler = LocalUriHandler.current
                val openLink: (String) -> Unit = { href ->
                    if (href.startsWith("/")) navController.navigate(PageRoute(href)) else uriHandler.openUri(href)
                }
                CompositionLocalProvider(LocalOpenLink provides openLink) {
                    NavHost(navController, startDestination = PageRoute()) {
                        composable<PageRoute> { entry ->
                            PageScreen(
                                path = entry.toRoute<PageRoute>().path,
                                onBack = navController.previousBackStackEntry?.let { { navController.popBackStack() } },
                            )
                        }
                    }
                }
            }
        }
    }
}
```

`LocalOpenLink` is how components open links: addresses that start with `/` open in the app, and anything else in the browser.

The view model asks the CMS what the address is with `resolve`, which answers with a page, a redirect, gone or not found. It follows redirects to other pages in the app and keeps the page through screen rotation.

```kotlin
// app/src/main/java/com/northwilds/app/PageViewModel.kt
package com.northwilds.app

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bifrostorbit.cms.CmsOrbitException
import com.bifrostorbit.cms.CmsPage
import com.bifrostorbit.cms.CmsResolution
import kotlinx.coroutines.launch

sealed interface PageState {
    data object Loading : PageState
    data class Ready(val page: CmsPage) : PageState
    data object NotFound : PageState
    data class Elsewhere(val url: String) : PageState
    data class Failed(val message: String) : PageState
}

class PageViewModel(private val path: String) : ViewModel() {
    var state by mutableStateOf<PageState>(PageState.Loading)
        private set

    init {
        load()
    }

    fun load() {
        viewModelScope.launch {
            state = try {
                show(path)
            } catch (error: CmsOrbitException) {
                PageState.Failed("We couldn't load this page. Check your connection and try again.")
            }
        }
    }

    private suspend fun show(path: String, hops: Int = 0): PageState =
        when (val result = Cms.client.resolve(path)) {
            is CmsResolution.Page -> PageState.Ready(result.page)
            is CmsResolution.Redirect ->
                if (result.to.startsWith("/") && hops < 5) show(result.to, hops + 1) else PageState.Elsewhere(result.to)
            CmsResolution.Gone, CmsResolution.NotFound -> PageState.NotFound
        }
}
```

The screen shows the page's name in the top bar and its blocks in a list. An app has no `<title>` or meta description, so the SEO title and description go where people see them outside the app: the **Share** button sends them with the page's canonical address.

```kotlin
// app/src/main/java/com/northwilds/app/PageScreen.kt
package com.northwilds.app

import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.bifrostorbit.cms.CmsPage
import com.northwilds.app.blocks.CmsBlock

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PageScreen(path: String, onBack: (() -> Unit)?) {
    val model = viewModel { PageViewModel(path) }
    val state = model.state
    val openLink = LocalOpenLink.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text((state as? PageState.Ready)?.page?.let { if (it.draft) "${it.name} (draft)" else it.name } ?: "Northwilds") },
                navigationIcon = { if (onBack != null) TextButton(onClick = onBack) { Text("Back") } },
                actions = { if (state is PageState.Ready) ShareButton(state.page) },
            )
        },
    ) { padding ->
        Box(Modifier.padding(padding).fillMaxSize()) {
            when (state) {
                PageState.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
                is PageState.Ready -> LazyColumn(Modifier.fillMaxSize()) {
                    items(state.page.components, key = { it.id }) { CmsBlock(it) }
                }
                PageState.NotFound -> Message("We couldn't find this page.", "Go to the home page") { openLink("/") }
                is PageState.Elsewhere -> LaunchedEffect(state.url) {
                    openLink(state.url)
                    onBack?.invoke()
                }
                is PageState.Failed -> Message(state.message, "Try again") { model.load() }
            }
        }
    }
}

@Composable
private fun ShareButton(page: CmsPage) {
    val context = LocalContext.current
    TextButton(onClick = {
        val share = Intent(Intent.ACTION_SEND)
            .setType("text/plain")
            .putExtra(Intent.EXTRA_TITLE, page.seo.title.ifEmpty { page.name })
            .putExtra(Intent.EXTRA_TEXT, listOf(page.seo.description, page.seo.canonical).filter { it.isNotEmpty() }.joinToString("\n"))
        context.startActivity(Intent.createChooser(share, null))
    }) { Text("Share") }
}

@Composable
private fun Message(text: String, action: String, onAction: () -> Unit) {
    Column(
        Modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(text)
        Button(onClick = onAction) { Text(action) }
    }
}
```

- **Not found and gone:** Both show a message with a way back to the home page. A website answers these with `404` and `410`; an app has nothing to answer, so one screen covers both.
- **Redirects:** A redirect to another address in the space opens that page in place. A redirect to another website opens the browser and closes the screen.
- **Draft label:** `page.draft` is only true in the drafts build from step 7.

`PageScreen` draws each block with `CmsBlock`, which you write in the next step. The app builds once step 6 is done.

## 6. Write components as composables

Each block on a page is a `CmsComponent` with a `type`, its `fields` and the blocks in its slots, `children`. A component map pairs each type with the composable that draws it, so adding a component is one line.

```kotlin
// app/src/main/java/com/northwilds/app/blocks/CmsBlocks.kt
package com.northwilds.app.blocks

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.bifrostorbit.cms.CmsComponent
import com.northwilds.app.BuildConfig

val components: Map<String, @Composable (CmsComponent) -> Unit> = mapOf(
    "hero" to { HeroBlock(it) },
    "featureSpotlight" to { FeatureSpotlightBlock(it) },
    "action" to { ActionBlock(it) },
)

@Composable
fun CmsBlock(block: CmsComponent) {
    val draw = components[block.type]
    when {
        draw != null -> draw(block)
        BuildConfig.DEBUG -> MissingBlock(block)
    }
}

@Composable
fun CmsBlocks(blocks: List<CmsComponent>, modifier: Modifier = Modifier) {
    Column(modifier, verticalArrangement = Arrangement.spacedBy(12.dp)) {
        blocks.forEach { block -> key(block.id) { CmsBlock(block) } }
    }
}

@Composable
private fun MissingBlock(block: CmsComponent) {
    Text(
        "No composable for \"${block.type}\" yet",
        Modifier.fillMaxWidth().padding(20.dp, 8.dp).border(1.dp, MaterialTheme.colorScheme.outline).padding(12.dp),
        style = MaterialTheme.typography.bodySmall,
    )
}
```

A type the map does not know draws a labelled box in debug builds, so you can see what is left to build, and nothing in release builds. An app already in people's hands keeps working when editors add a new component.

Declare a `@Serializable` class with the fields you use and decode them with `decodeFields`. Fields you leave out are ignored, and missing ones take your defaults. The Northwilds hero has an eyebrow, a heading in two parts and a description, with a button in each of two slots:

```kotlin
// app/src/main/java/com/northwilds/app/blocks/Hero.kt
package com.northwilds.app.blocks

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.bifrostorbit.cms.CmsComponent
import kotlinx.serialization.Serializable

@Serializable
data class Hero(
    val eyebrow: String = "",
    val heading: String = "",
    val headingAccent: String = "",
    val description: String = "",
)

@Composable
fun HeroBlock(block: CmsComponent) {
    val hero = block.decodeFields<Hero>()
    Column(Modifier.padding(horizontal = 20.dp, vertical = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        if (hero.eyebrow.isNotEmpty()) Text(hero.eyebrow, style = MaterialTheme.typography.labelLarge)
        Text(listOf(hero.heading, hero.headingAccent).filter { it.isNotEmpty() }.joinToString(" "), style = MaterialTheme.typography.headlineLarge)
        RichText(hero.description)
        CmsBlocks(block.children["primaryAction"].orEmpty() + block.children["secondaryAction"].orEmpty())
    }
}
```

A feature spotlight adds an optional image. `CmsImages.url` asks the CMS for the image resized to the width you show it at, so a phone does not download a 4,000-pixel photo:

```kotlin
// app/src/main/java/com/northwilds/app/blocks/FeatureSpotlight.kt
package com.northwilds.app.blocks

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.bifrostorbit.cms.CmsComponent
import com.bifrostorbit.cms.CmsImage
import com.bifrostorbit.cms.CmsImages
import kotlinx.serialization.Serializable

@Serializable
data class FeatureSpotlight(
    val eyebrow: String = "",
    val heading: String = "",
    val body: String = "",
    val image: CmsImage? = null,
)

@Composable
fun FeatureSpotlightBlock(block: CmsComponent) {
    val feature = block.decodeFields<FeatureSpotlight>()
    Column(Modifier.padding(horizontal = 20.dp, vertical = 24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        feature.image?.let {
            AsyncImage(model = CmsImages.url(it.url, width = 1080), contentDescription = it.alt, modifier = Modifier.fillMaxWidth())
        }
        if (feature.eyebrow.isNotEmpty()) Text(feature.eyebrow, style = MaterialTheme.typography.labelLarge)
        Text(feature.heading, style = MaterialTheme.typography.headlineSmall)
        RichText(feature.body)
        CmsBlocks(block.children["action"].orEmpty())
    }
}
```

The blocks in a slot, such as the hero's buttons, are in `children` under the slot's name. Passing them to `CmsBlocks` draws them with the same map, however deep they are nested. The button is a component of its own, with a link field that decodes as `CmsLink`:

```kotlin
// app/src/main/java/com/northwilds/app/blocks/Action.kt
package com.northwilds.app.blocks

import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import com.bifrostorbit.cms.CmsComponent
import com.bifrostorbit.cms.CmsLink
import com.northwilds.app.LocalOpenLink
import kotlinx.serialization.Serializable

@Serializable
data class Action(val label: String = "", val link: CmsLink? = null, val style: String = "primary")

@Composable
fun ActionBlock(block: CmsComponent) {
    val action = block.decodeFields<Action>()
    val href = action.link?.href ?: return
    val openLink = LocalOpenLink.current
    if (action.style == "primary") {
        Button(onClick = { openLink(href) }) { Text(action.label) }
    } else {
        OutlinedButton(onClick = { openLink(href) }) { Text(action.label) }
    }
}
```

Rich text fields are HTML. `AnnotatedString.fromHtml` shows paragraphs, bold, italics, lists and links, and its link listener sends links through `LocalOpenLink`, so a link to `/products` opens in the app:

```kotlin
// app/src/main/java/com/northwilds/app/blocks/RichText.kt
package com.northwilds.app.blocks

import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.fromHtml
import com.northwilds.app.LocalOpenLink

@Composable
fun RichText(html: String) {
    val openLink = LocalOpenLink.current
    val text = remember(html) {
        AnnotatedString.fromHtml(html.trim(), linkInteractionListener = { link ->
            (link as? LinkAnnotation.Url)?.let { openLink(it.url) }
        })
    }
    Text(text, style = MaterialTheme.typography.bodyLarge)
}
```

Run the app. The home page opens with its hero and feature spotlights, and **Back** returns from any page you open through a link or button. Use your own component types from **Configuration › Components**: the field names in your classes are the field keys there. To write the classes for you, run the type generator in [The Kotlin SDK](https://docs.bifrostorbit.com/cms/developers/sdk-kotlin/).

## 7. Show drafts to your team

On a website, editors see drafts in the live preview beside the editor: the CMS opens the website with a preview token, the website reads drafts with the secret key on its server, and the bridge script and `data-cms-id` let editors click blocks. **None of that works in an Android app.** The editor can only frame a web page, and an app cannot keep a secret: anyone who installs it can unpack it and read every string inside. The SDK refuses a secret key on Android for this reason.

What an app can do is read drafts through **your own server**, which holds the secret key and decides who may see drafts. This step builds:

- a small drafts server that forwards read requests to CMS Orbit with the secret key and `draft=true`, for requests that carry your drafts token;
- a `drafts` build of the app, for your team only, that talks to that server instead of CMS Orbit.

Editors still use the live preview on your website while they write. The drafts build is for checking how a page looks in the app before it is published.

### The drafts server

A Kotlin server with Ktor, in its own Gradle project next to the app:

```kotlin
// drafts-server/settings.gradle.kts
rootProject.name = "drafts-server"
```

```kotlin
// drafts-server/build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.21"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.ktor:ktor-server-netty:3.6.1")
    runtimeOnly("org.slf4j:slf4j-simple:2.0.17")
}

kotlin {
    jvmToolchain(17)
}

application {
    mainClass.set("com.northwilds.drafts.MainKt")
}
```

```kotlin
// drafts-server/src/main/kotlin/com/northwilds/drafts/Main.kt
package com.northwilds.drafts

import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.uri
import io.ktor.server.response.respond
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.security.MessageDigest
import kotlin.system.exitProcess

private val readable = setOf("resolve", "content", "navigation", "global", "list")

private fun required(name: String): String {
    val value = System.getenv(name)
    if (value.isNullOrBlank()) {
        System.err.println("$name is not set. Add it to the drafts server's environment and start it again.")
        exitProcess(1)
    }
    return value
}

fun main() {
    val cmsApi = required("CMS_API_URL").trimEnd('/') + "/api/cdn/v1"
    val secretKey = required("CMS_PREVIEW_KEY")
    val draftsToken = required("DRAFTS_TOKEN").toByteArray()
    val http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()

    embeddedServer(Netty, port = System.getenv("PORT")?.toInt() ?: 8080) {
        routing {
            get("/cms/api/cdn/v1/{endpoint}") {
                val token = call.request.headers["X-Drafts-Token"].orEmpty().toByteArray()
                if (!MessageDigest.isEqual(token, draftsToken)) return@get call.respond(HttpStatusCode.Unauthorized)
                val endpoint = call.parameters["endpoint"]
                if (endpoint !in readable) return@get call.respond(HttpStatusCode.NotFound)

                val query = call.request.uri.substringAfter('?', "")
                val target = "$cmsApi/$endpoint?" + listOf(query, "draft=true").filter { it.isNotEmpty() }.joinToString("&")
                val request = HttpRequest.newBuilder(URI(target))
                    .header("Authorization", "Bearer $secretKey")
                    .header("Accept", "application/json")
                    .build()
                val answer = http.send(request, HttpResponse.BodyHandlers.ofString())
                call.respondText(answer.body(), ContentType.Application.Json, HttpStatusCode.fromValue(answer.statusCode()))
            }
        }
    }.start(wait = true)
}
```

- It answers on the same paths as the delivery API, so the app's code does not change: the drafts build only points the SDK at another address.
- It forwards reads of pages, menus, site-wide content and lists, and nothing else. The secret key never leaves the server.
- It compares the token in constant time and answers `401` when it is missing or wrong.
- It stops at once, naming the setting, when `CMS_API_URL`, `CMS_PREVIEW_KEY` or `DRAFTS_TOKEN` is not set, rather than failing later with a null error.

Start it with the secret key and a long random drafts token in its environment, never in source control:

```bash
cd drafts-server
export CMS_API_URL=https://api.bifrostorbit.com/cms
export CMS_PREVIEW_KEY=cms_sk_…
export DRAFTS_TOKEN=a-long-random-value
gradle run
```

To deploy it, `gradle installDist` writes a start script to `build/install/drafts-server/bin`.

Host it on `https`, for example at `https://drafts.northwilds.com`. Use a secret key from the environment editors work in, usually Staging, with **Read drafts** on.

### The drafts build

Give the client the drafts token when the build has one, by adding a header to every request:

```kotlin
// app/src/main/java/com/northwilds/app/Cms.kt
package com.northwilds.app

import com.bifrostorbit.cms.CmsOrbitClient
import okhttp3.OkHttpClient

object Cms {
    val client = CmsOrbitClient(BuildConfig.CMS_PUBLIC_KEY) {
        baseUrl = BuildConfig.CMS_API_URL
        defaultRegion = BuildConfig.CMS_REGION
        if (BuildConfig.DRAFTS_TOKEN.isNotEmpty()) {
            okHttpClient = OkHttpClient.Builder()
                .addInterceptor { chain ->
                    chain.proceed(chain.request().newBuilder().header("X-Drafts-Token", BuildConfig.DRAFTS_TOKEN).build())
                }
                .build()
        }
    }
}
```

Add a `drafts` build type inside `android { }` in `app/build.gradle.kts`, before `buildFeatures`:

```kotlin
// app/build.gradle.kts
    buildTypes {
        create("drafts") {
            initWith(getByName("debug"))
            applicationIdSuffix = ".drafts"
            buildConfigField("String", "CMS_API_URL", setting("drafts.apiUrl"))
            buildConfigField("String", "DRAFTS_TOKEN", setting("drafts.token"))
        }
    }
```

And its two settings:

```properties
# local.properties
drafts.apiUrl=https://drafts.northwilds.com/cms
drafts.token=a-long-random-value
```

Build it with **Build Variants › drafts** in Android Studio, or `./gradlew :app:assembleDrafts`. It installs beside the normal app as `com.northwilds.app.drafts`, and pages with unpublished changes show **(draft)** in the top bar.

Be clear about what the drafts token protects. Anyone who has the drafts build can read your drafts, so share it only with your team, for example through an internal testing track in Google Play. To cut off access, change `DRAFTS_TOKEN` on the server and send a new build. To give each person their own access, put the drafts server behind your organisation's sign-in instead of a shared token.

## 8. Refresh content in the app

A website refreshes when editors publish: CMS Orbit sends a signed webhook to its server, and the server clears its cache. An installed app has no address the CMS can call, so it cannot receive webhooks. Instead the app decides when to ask again:

- **Cache lifetime:** A page is kept in memory for a minute and shown straight away when you open it again.
- **Back in the foreground:** When the app returns and the page is older than a minute, it is read again.
- **Pull to refresh:** Pulling down reads the page again at once, whatever its age.
- **No connection:** When the CMS cannot be reached, the app keeps showing the page it already has.

A small cache holds what the app has read:

```kotlin
// app/src/main/java/com/northwilds/app/PageCache.kt
package com.northwilds.app

import android.os.SystemClock
import com.bifrostorbit.cms.CmsResolution
import com.bifrostorbit.cms.CmsServerException
import java.util.concurrent.ConcurrentHashMap

object PageCache {
    private const val LIFETIME_MILLIS = 60_000L

    private class Kept(val result: CmsResolution, val at: Long)

    private val kept = ConcurrentHashMap<String, Kept>()

    suspend fun resolve(path: String, fresh: Boolean = false): CmsResolution {
        val now = SystemClock.elapsedRealtime()
        val entry = kept[path]
        if (!fresh && entry != null && now - entry.at < LIFETIME_MILLIS) return entry.result
        return try {
            Cms.client.resolve(path).also { kept[path] = Kept(it, now) }
        } catch (error: CmsServerException) {
            entry?.result ?: throw error
        }
    }

    fun clear() = kept.clear()
}
```

The view model reads through the cache, and keeps the page on screen if a refresh fails:

```kotlin
// app/src/main/java/com/northwilds/app/PageViewModel.kt
package com.northwilds.app

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bifrostorbit.cms.CmsOrbitException
import com.bifrostorbit.cms.CmsPage
import com.bifrostorbit.cms.CmsResolution
import kotlinx.coroutines.launch

sealed interface PageState {
    data object Loading : PageState
    data class Ready(val page: CmsPage) : PageState
    data object NotFound : PageState
    data class Elsewhere(val url: String) : PageState
    data class Failed(val message: String) : PageState
}

class PageViewModel(private val path: String) : ViewModel() {
    var state by mutableStateOf<PageState>(PageState.Loading)
        private set
    var refreshing by mutableStateOf(false)
        private set

    fun load(fresh: Boolean = false) {
        viewModelScope.launch {
            refreshing = fresh
            state = try {
                show(path, fresh)
            } catch (error: CmsOrbitException) {
                state as? PageState.Ready ?: PageState.Failed("We couldn't load this page. Check your connection and try again.")
            }
            refreshing = false
        }
    }

    private suspend fun show(path: String, fresh: Boolean, hops: Int = 0): PageState =
        when (val result = PageCache.resolve(path, fresh)) {
            is CmsResolution.Page -> PageState.Ready(result.page)
            is CmsResolution.Redirect ->
                if (result.to.startsWith("/") && hops < 5) show(result.to, fresh, hops + 1) else PageState.Elsewhere(result.to)
            CmsResolution.Gone, CmsResolution.NotFound -> PageState.NotFound
        }
}
```

The screen loads the page each time it comes into view, with `LifecycleStartEffect` in place of the view model's `init`, and wraps the list in `PullToRefreshBox`:

```kotlin
// app/src/main/java/com/northwilds/app/PageScreen.kt
package com.northwilds.app

import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import com.bifrostorbit.cms.CmsPage
import com.northwilds.app.blocks.CmsBlock

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PageScreen(path: String, onBack: (() -> Unit)?) {
    val model = viewModel { PageViewModel(path) }
    val state = model.state
    val openLink = LocalOpenLink.current

    LifecycleStartEffect(model) {
        model.load()
        onStopOrDispose { }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text((state as? PageState.Ready)?.page?.let { if (it.draft) "${it.name} (draft)" else it.name } ?: "Northwilds") },
                navigationIcon = { if (onBack != null) TextButton(onClick = onBack) { Text("Back") } },
                actions = { if (state is PageState.Ready) ShareButton(state.page) },
            )
        },
    ) { padding ->
        Box(Modifier.padding(padding).fillMaxSize()) {
            when (state) {
                PageState.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
                is PageState.Ready -> PullToRefreshBox(isRefreshing = model.refreshing, onRefresh = { model.load(fresh = true) }) {
                    LazyColumn(Modifier.fillMaxSize()) {
                        items(state.page.components, key = { it.id }) { CmsBlock(it) }
                    }
                }
                PageState.NotFound -> Message("We couldn't find this page.", "Go to the home page") { openLink("/") }
                is PageState.Elsewhere -> LaunchedEffect(state.url) {
                    openLink(state.url)
                    onBack?.invoke()
                }
                is PageState.Failed -> Message(state.message, "Try again") { model.load(fresh = true) }
            }
        }
    }
}

@Composable
private fun ShareButton(page: CmsPage) {
    val context = LocalContext.current
    TextButton(onClick = {
        val share = Intent(Intent.ACTION_SEND)
            .setType("text/plain")
            .putExtra(Intent.EXTRA_TITLE, page.seo.title.ifEmpty { page.name })
            .putExtra(Intent.EXTRA_TEXT, listOf(page.seo.description, page.seo.canonical).filter { it.isNotEmpty() }.joinToString("\n"))
        context.startActivity(Intent.createChooser(share, null))
    }) { Text("Share") }
}

@Composable
private fun Message(text: String, action: String, onAction: () -> Unit) {
    Column(
        Modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(text)
        Button(onClick = onAction) { Text(action) }
    }
}
```

What this does not do:

- **Instant updates:** A change that editors publish reaches an open app within a minute of it returning to the foreground, or at once on pull to refresh, not the moment it is published. If you need that, see Refresh from your server below.
- **Offline at start:** The cache is in memory, so it is empty when the app starts without a connection. To open offline, save pages in a local database such as Room as well.
- **HTTP caching:** The API's `Cache-Control` is meant for shared caches such as a CDN, so OkHttp's own cache does not keep CMS answers. The cache above is what keeps them.

Choose the lifetime to suit your content. A minute keeps prices and opening times close to live; a few minutes is fine for pages that rarely change.

### Refresh from your server (optional)

To update the app within seconds of publishing, let a server receive CMS Orbit's webhook and pass it on as a push message:

1. Add a webhook in **Configuration › Webhooks** that points at your server.
2. On your server, check the signature before trusting the message.
3. Send a Firebase Cloud Messaging data message to the app.
4. In the app, call `PageCache.clear()` when the message arrives, so every page is read again the next time it is shown.

On a Kotlin server, `CmsWebhook.parse` from the SDK checks the signature and the timestamp. In the drafts server from step 7, add the SDK to `drafts-server/build.gradle.kts`:

```kotlin
dependencies {
    implementation("io.ktor:ktor-server-netty:3.6.1")
    implementation("com.bifrostorbit:cms-sdk:0.2.0")
    runtimeOnly("org.slf4j:slf4j-simple:2.0.17")
}
```

Read the secret in `main`, after `draftsToken`:

```kotlin
val webhookSecret = System.getenv("CMS_WEBHOOK_SECRET")?.takeIf { it.isNotBlank() }
if (webhookSecret == null) println("CMS_WEBHOOK_SECRET is not set, so /cms-webhook answers 503 until you set it and restart.")
```

Then add a route beside the `get` in `routing { }`, with these imports:

```kotlin
import com.bifrostorbit.cms.CmsWebhook
import io.ktor.server.request.receive
import io.ktor.server.routing.post

post("/cms-webhook") {
    if (webhookSecret == null) return@post call.respond(HttpStatusCode.ServiceUnavailable)
    val message = CmsWebhook.parse(
        webhookSecret,
        call.request.headers[CmsWebhook.TIMESTAMP_HEADER].orEmpty(),
        call.request.headers[CmsWebhook.SIGNATURE_HEADER].orEmpty(),
        call.receive<ByteArray>(),
    ) ?: return@post call.respond(HttpStatusCode.Unauthorized)
    call.respond(HttpStatusCode.NoContent)
    if (message.event != "webhook.test") sendRefreshMessage()
}
```

It takes the raw request body, the `x-orbit-timestamp` and `x-orbit-signature` headers, and the webhook secret, including `whsec_`, and answers `null` when the message is not genuine or is more than five minutes old. Set `CMS_WEBHOOK_SECRET` in the server's environment; without it the server still serves drafts, says so when it starts, and answers `503` on this route. Then write `sendRefreshMessage` with the Firebase Admin SDK. The drafts server needs no other change to receive webhooks, but for everyone's app, run the route on a server that is not limited to your team. Push messages can be delayed, so keep the cache lifetime and pull to refresh as well.

## Next steps

- [The Kotlin SDK](https://docs.bifrostorbit.com/cms/developers/sdk-kotlin/): every method, errors, generated types and the Java API.
- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): slots, nested blocks and variants.
- [Menus, globals and lists](https://docs.bifrostorbit.com/cms/developers/menus-globals-and-lists/): add the Northwilds menu and footer to the app.
- [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/): show the app in the reader's language.
- [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/): the editor's live preview for your website.
- [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/): receive publish events on your server.
- [SEO with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/): titles, descriptions and canonical addresses on the web.
- [Keys, permissions and sign-in](https://docs.bifrostorbit.com/cms/developers/security-and-access/): what each key may read.
- [Troubleshooting](https://docs.bifrostorbit.com/cms/developers/troubleshooting/): when a page does not show.
