Building Server-Driven UI with Swift and Kotlin: An Architectural Blueprint
Design native server-driven paywalls with typed component catalogs, safe Swift and Kotlin decoding, StoreKit and Play Billing actions, and fallbacks.
Key Takeaways
- Production mobile SDUI needs a finite component catalog, versioned contracts, defensive decoding, stable action routing, and local fallbacks on both iOS and Android.
- Swift
Decodableand Kotlin Serialization validate structure only when models and failure handling are designed deliberately; unknown enums and semantic product errors need explicit policy. - ONLang applies this blueprint to registered native components while StoreKit 2 and Google Play Billing remain application-owned; its iOS and Android guides provide concrete integration paths.
Airbnb’s Ghost Platform and Lyft’s Bikes and Scooters work show why large teams invest in server-driven UI: a shared schema lets a server assemble screens while native frameworks own rendering and interactions. Sections, screens, and actions become data. Product teams can change composition without reimplementing presentation in every client.
A paywall narrows that problem but raises the stakes. It has store products, legal disclosures, purchase and restore actions, entitlement state, and revenue analytics. A generic remote layout tree is insufficient unless those behaviors are typed and tested. This blueprint starts with the smallest catalog that can represent the existing paywall safely.
Begin with primitives, not arbitrary layout
Define components around application semantics: PaywallIntro, PlanToggle, PurchaseButton, RestoreButton, and LegalFooter are more useful than unrestricted stacks of View and Text. Semantic components preserve accessibility and prevent a payload from accidentally turning a restore action into decorative text.
Each prop needs a type and a boundary. Copy tokens have maximum lengths. Product selectors reference an allowlisted catalog. Lists have minimum and maximum sizes. Interactive components declare emitted actions instead of accepting arbitrary URLs or executable handlers.
Containers can express approved ordering without exposing every layout parameter. If designers need two arrangements, model an enum such as compact and expanded, then implement both natively. Avoid shipping numeric constraints that allow a contract to place controls offscreen or produce impossible flex layouts.
Here is a compact JSON contract for a paywall composition:
{
"version": 1,
"screen": "paywall",
"components": [
{ "type": "intro", "headline": "Your plan, built for you" },
{
"type": "plans",
"products": ["annual", "monthly"],
"selected": "annual"
},
{ "type": "purchase", "title": "Continue" },
{ "type": "restore", "title": "Restore purchases" }
]
}
The schema is intentionally finite. It can evolve through explicit versions, while unknown fields can be ignored by tolerant decoders. Unknown component types require a safe failure or skip policy; they must not crash the screen.
Safe deserialization in Swift
Swift’s Decodable synthesizes useful parsing, but default enum decoding rejects unknown cases. That may be desirable for a security boundary, yet it can take down an entire screen when a newer server sends a case to an old binary. Decode the whole composition inside a fallible boundary and preserve a bundled fallback.
The following Swift 5.9 example models a small contract and rejects malformed required values. It uses associated values so actions cannot be attached to arbitrary components.
import Foundation
enum PaywallComponent: Decodable {
case intro(headline: String)
case plans(products: [String], selected: String)
case purchase(title: String)
case restore(title: String)
private enum CodingKeys: String, CodingKey { case type, headline, products, selected, title }
private enum Kind: String, Decodable { case intro, plans, purchase, restore }
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
switch try c.decode(Kind.self, forKey: .type) {
case .intro:
let headline = try c.decode(String.self, forKey: .headline)
guard headline.count <= 40 else { throw DecodingError.dataCorruptedError(
forKey: .headline, in: c, debugDescription: "Headline exceeds 40 characters") }
self = .intro(headline: headline)
case .plans:
let products = try c.decode([String].self, forKey: .products)
let selected = try c.decode(String.self, forKey: .selected)
guard products.count == 2, products.contains(selected) else {
throw DecodingError.dataCorruptedError(
forKey: .products, in: c, debugDescription: "Invalid product selection")
}
self = .plans(products: products, selected: selected)
case .purchase:
self = .purchase(title: try c.decode(String.self, forKey: .title))
case .restore:
self = .restore(title: try c.decode(String.self, forKey: .title))
}
}
}
struct PaywallContract: Decodable {
let version: Int
let components: [PaywallComponent]
}
func decodePaywall(_ data: Data) throws -> PaywallContract {
let contract = try JSONDecoder().decode(PaywallContract.self, from: data)
guard contract.version == 1 else { throw URLError(.cannotDecodeContentData) }
return contract
}
The example rejects unknown component kinds. Callers catch that error and use a known-good contract. A production implementation can collect component-level errors and omit nonessential sections, but should fail closed for purchase-critical inconsistencies.
Kotlin Serialization with the same semantics
Kotlin 1.9 with kotlinx.serialization can represent the same closed catalog using sealed classes. Keep serialization configuration consistent with your compatibility policy: ignoring unknown additive fields is useful; coercing invalid values is not.
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
sealed interface PaywallComponent {
@Serializable
@SerialName("intro")
data class Intro(val headline: String) : PaywallComponent
@Serializable
@SerialName("plans")
data class Plans(val products: List<String>, val selected: String) : PaywallComponent
@Serializable
@SerialName("purchase")
data class Purchase(val title: String) : PaywallComponent
@Serializable
@SerialName("restore")
data class Restore(val title: String) : PaywallComponent
}
@Serializable
data class PaywallContract(val version: Int, val components: List<PaywallComponent>)
private val json = Json { ignoreUnknownKeys = true }
fun decodePaywall(input: String): PaywallContract {
val contract = json.decodeFromString<PaywallContract>(input)
require(contract.version == 1) { "Unsupported contract version" }
contract.components.forEach { component ->
when (component) {
is PaywallComponent.Intro -> require(component.headline.length <= 40)
is PaywallComponent.Plans -> require(
component.products.size == 2 && component.selected in component.products
)
else -> Unit
}
}
return contract
}
Wrap decoding in runCatching at the integration boundary and select the bundled composition on failure. Do not show a blank paywall while logging an error only to analytics. The fallback must include working purchase and restore controls.
The complete ONLang integrations use a registry rather than asking each app to build this infrastructure from scratch. See the iOS guide and Android guide for OnlangRegistry, OnlangFlowViewController and the SwiftUI OnlangFlowView on iOS, and OnlangFlowView and the Compose wrapper OnlangFlow on Android.
Bind actions to billing, never to payload code
A contract should emit select(product), purchase(product), or restore, not a Swift closure, Kotlin class name, or JavaScript function. Native code resolves those actions against products loaded from StoreKit 2 or Play Billing. The selected identifier must belong to the current offer and storefront.
On iOS, the purchase handler can call Product.products(for:) and product.purchase(), then observe transaction updates and entitlement state through the app’s existing store layer. On Android, use the Billing Client’s product details and purchase flow, acknowledge purchases as required, and process entitlement updates in one place. The UI contract should never be the receipt authority.
Disable purchase controls while a transaction is pending, but do not block restore or terms unnecessarily. If product loading fails, retain a useful native error and retry path. A cached contract does not make an expired price valid; localized price text should come from store product metadata whenever the offer requires it.
ONLang’s products prop type and onlang://select?product=... actions fit this boundary. Developers register components and wire actions to their existing purchase functions, including RevenueCat if already present. The billing-layer comparison explains why that separation matters.
Versioning and backward compatibility
Treat every released payload as an API request from an old client. Add fields additively where possible, keep defaults explicit, and never silently change an action’s meaning. Introduce a new component version when semantics change rather than relying on distant clients to guess.
Maintain fixture contracts for each supported app version. Test malformed JSON, missing fields, unknown fields, unknown components, oversized arrays, invalid UTF-8 boundaries, duplicate product identifiers, and empty required actions. Snapshot tests alone will not catch semantic errors such as selecting a product absent from the list.
Publish through environments with validation before delivery. ONLang’s onlang lint compiles every assignment in every locale and checks it against the registry before onlang publish. That gate reduces the chance of an invalid contract reaching old clients, but application fallback remains mandatory because networks and local state can still fail.
For teams generating variants with AI, validation is even more important. Finite hypothesis spaces for safe LLM-generated paywalls explains why structured output alone cannot prove semantic correctness.
State, caching, and process recovery
Keep three states distinct: the selected composition, the selected store product, and the active transaction. A background refresh must not change the selected plan under a user’s finger or replace a screen during purchase authentication. Apply new contracts between impressions unless there is an explicit safe-update policy.
Persist the last validated contract and experiment assignment. Bundle a known-good default for first launch. On every presentation, resolve network, cache, and bundle in an order that never requires network success for basic purchase access. Log which source produced the impression so performance and conversion analyses do not mix incompatible paths.
After process death, restore entitlement and pending transaction state from the store layer, not from the serialized UI. A cached “Purchased” label is not proof of ownership. Offline-first dynamic paywalls details this resolution strategy and its instrumentation.
Operate the screen after launch
A production paywall needs a kill switch and audit trail. If a published assignment breaks a device-specific layout or purchase action, operators must disable the placement without waiting for app review. ONLang supports onlang kill paywall --reason "INC-12", onlang kill --status, and onlang kill paywall --lift; SDK outcomes let the app show its own paywall on failed or killed delivery. A killed placement shows neither the cached nor the bundled flow, even offline, until delivery serves a flow again.
Measure exposure, action, store result, and entitlement separately. Do not infer a purchase from a button tap. Preserve the original assignment for delayed renewal and refund analysis, and keep holdout outcomes outside adaptive allocation. Holdout groups and incrementality explains why.
Finally, rehearse failure before optimizing copy. Airplane mode, a malformed fixture, an unavailable product, and a killed placement should all leave a coherent native purchase path. Once those paths are boring, remote iteration becomes an advantage rather than another way to take checkout down.
Build the first contract with ONLang
The ONLang registry provides the typed boundary described here, with native SDKs for iOS (15+, UIKit and SwiftUI) and Android (6.0+, Views and Jetpack Compose), both rendering with DivKit, and existing billing left intact. Every new app has a 14-day full-featured trial, with no card required at signup. Start the trial, register one existing screen, and use the React Native guide as well if your component catalog spans all three stacks.