Skip to content

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.

Tutorial22 min read

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, 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, 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 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 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.

1Create 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.ktspluginManagement {    repositories {        google()        mavenCentral()        gradlePluginPortal()    }}dependencyResolutionManagement {    repositories {        google()        mavenCentral()    }}rootProject.name = "Northwilds"include(":app")
Kotlin
// build.gradle.ktsplugins {    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.propertiesorg.gradle.jvmargs=-Xmx2gandroid.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>

2Install 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.ktsimport java.util.Propertiesplugins {    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, 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.

3Add 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.propertiescms.apiUrl=https://api.bifrostorbit.com/cmscms.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.

4Create 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.ktpackage com.northwilds.appimport com.bifrostorbit.cms.CmsOrbitClientobject 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.

5Show 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.ktpackage com.northwilds.appimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.staticCompositionLocalOfimport androidx.compose.ui.platform.LocalUriHandlerimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport androidx.navigation.toRouteimport kotlinx.serialization.Serializable@Serializabledata 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.ktpackage com.northwilds.appimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.bifrostorbit.cms.CmsOrbitExceptionimport com.bifrostorbit.cms.CmsPageimport com.bifrostorbit.cms.CmsResolutionimport kotlinx.coroutines.launchsealed 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.ktpackage com.northwilds.appimport android.content.Intentimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material3.Buttonimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.unit.dpimport androidx.lifecycle.viewmodel.compose.viewModelimport com.bifrostorbit.cms.CmsPageimport com.northwilds.app.blocks.CmsBlock@OptIn(ExperimentalMaterial3Api::class)@Composablefun 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() }            }        }    }}@Composableprivate 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") }}@Composableprivate 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.

6Write 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.ktpackage com.northwilds.app.blocksimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.keyimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport com.bifrostorbit.cms.CmsComponentimport com.northwilds.app.BuildConfigval components: Map<String, @Composable (CmsComponent) -> Unit> = mapOf(    "hero" to { HeroBlock(it) },    "featureSpotlight" to { FeatureSpotlightBlock(it) },    "action" to { ActionBlock(it) },)@Composablefun CmsBlock(block: CmsComponent) {    val draw = components[block.type]    when {        draw != null -> draw(block)        BuildConfig.DEBUG -> MissingBlock(block)    }}@Composablefun CmsBlocks(blocks: List<CmsComponent>, modifier: Modifier = Modifier) {    Column(modifier, verticalArrangement = Arrangement.spacedBy(12.dp)) {        blocks.forEach { block -> key(block.id) { CmsBlock(block) } }    }}@Composableprivate 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.ktpackage com.northwilds.app.blocksimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport com.bifrostorbit.cms.CmsComponentimport kotlinx.serialization.Serializable@Serializabledata class Hero(    val eyebrow: String = "",    val heading: String = "",    val headingAccent: String = "",    val description: String = "",)@Composablefun 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.ktpackage com.northwilds.app.blocksimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport coil3.compose.AsyncImageimport com.bifrostorbit.cms.CmsComponentimport com.bifrostorbit.cms.CmsImageimport com.bifrostorbit.cms.CmsImagesimport kotlinx.serialization.Serializable@Serializabledata class FeatureSpotlight(    val eyebrow: String = "",    val heading: String = "",    val body: String = "",    val image: CmsImage? = null,)@Composablefun 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.ktpackage com.northwilds.app.blocksimport androidx.compose.material3.Buttonimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport com.bifrostorbit.cms.CmsComponentimport com.bifrostorbit.cms.CmsLinkimport com.northwilds.app.LocalOpenLinkimport kotlinx.serialization.Serializable@Serializabledata class Action(val label: String = "", val link: CmsLink? = null, val style: String = "primary")@Composablefun 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.ktpackage com.northwilds.app.blocksimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.ui.text.AnnotatedStringimport androidx.compose.ui.text.LinkAnnotationimport androidx.compose.ui.text.fromHtmlimport com.northwilds.app.LocalOpenLink@Composablefun 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.

7Show 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.ktsrootProject.name = "drafts-server"
Kotlin
// drafts-server/build.gradle.ktsplugins {    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.ktpackage com.northwilds.draftsimport io.ktor.http.ContentTypeimport io.ktor.http.HttpStatusCodeimport io.ktor.server.engine.embeddedServerimport io.ktor.server.netty.Nettyimport io.ktor.server.request.uriimport io.ktor.server.response.respondimport io.ktor.server.response.respondTextimport io.ktor.server.routing.getimport io.ktor.server.routing.routingimport java.net.URIimport java.net.http.HttpClientimport java.net.http.HttpRequestimport java.net.http.HttpResponseimport java.security.MessageDigestimport kotlin.system.exitProcessprivate 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:

Shell
cd drafts-serverexport CMS_API_URL=https://api.bifrostorbit.com/cmsexport CMS_PREVIEW_KEY=cms_sk_…export DRAFTS_TOKEN=a-long-random-valuegradle 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.ktpackage com.northwilds.appimport com.bifrostorbit.cms.CmsOrbitClientimport okhttp3.OkHttpClientobject 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.propertiesdrafts.apiUrl=https://drafts.northwilds.com/cmsdrafts.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.

8Refresh 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.ktpackage com.northwilds.appimport android.os.SystemClockimport com.bifrostorbit.cms.CmsResolutionimport com.bifrostorbit.cms.CmsServerExceptionimport java.util.concurrent.ConcurrentHashMapobject 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.ktpackage com.northwilds.appimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.bifrostorbit.cms.CmsOrbitExceptionimport com.bifrostorbit.cms.CmsPageimport com.bifrostorbit.cms.CmsResolutionimport kotlinx.coroutines.launchsealed 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.ktpackage com.northwilds.appimport android.content.Intentimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material3.Buttonimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.TopAppBarimport androidx.compose.material3.pulltorefresh.PullToRefreshBoximport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.unit.dpimport androidx.lifecycle.compose.LifecycleStartEffectimport androidx.lifecycle.viewmodel.compose.viewModelimport com.bifrostorbit.cms.CmsPageimport com.northwilds.app.blocks.CmsBlock@OptIn(ExperimentalMaterial3Api::class)@Composablefun 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) }            }        }    }}@Composableprivate 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") }}@Composableprivate 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.CmsWebhookimport io.ktor.server.request.receiveimport io.ktor.server.routing.postpost("/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

Was this page helpful?

Read next