Skip to content
Back to skills

Kmp Data Layer

ASecurity

Use when designing, adding or refactoring the data layer of a Kotlin Multiplatform app in commonMain — Ktor HttpClient setup, DTOs and kotlinx.serialization, repositories and mappers, a typed result/error wrapper, bearer token refresh, offline-first caching with Room 3 or SQLDelight — or when debugging MissingFieldException, JsonConvertException, JsonDecodingException, 401 refresh loops, random logouts, tokens in logs, iOS-only network timeouts, or flows that stop updating in release builds.

  • 17 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 3, 2026
developmentrustgokotlinbashsqltestingdebuggingrefactoringgitapi

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Pro scans all 6 files and shows the line behind each finding

Scanned December 3, 2026

npx -y skills add Kushpawan/kmp-mobile-skills --skill kmp-data-layer --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Kmp Data Layer?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Kmp Data Layer
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/kushpawan-kmp-data-layer/badge)](https://www.skillsdirectory.com/skills/kushpawan-kmp-data-layer)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: kmp-data-layer
description: Use when designing, adding or refactoring the data layer of a Kotlin Multiplatform app in commonMain — Ktor HttpClient setup, DTOs and kotlinx.serialization, repositories and mappers, a typed result/error wrapper, bearer token refresh, offline-first caching with Room 3 or SQLDelight — or when debugging MissingFieldException, JsonConvertException, JsonDecodingException, 401 refresh loops, random logouts, tokens in logs, iOS-only network timeouts, or flows that stop updating in release builds.
license: Apache-2.0
compatibility: Kotlin Multiplatform project (Android + iOS) using or adopting Ktor client 3.x (3.6 current) and kotlinx.serialization 1.7+ (1.13 current). iOS compile checks need macOS with Xcode.
metadata:
  category: data
  platforms: android, ios
---

# KMP data layer

The wire is untrusted; the domain is not. Parse responses into nullable DTOs, validate and map them in
the data layer, and expose only non-null domain models and a typed result. One configured `HttpClient`
is the only door to the network. When a screen must work offline, the UI observes the database, not
the network response.

## When to use

- Designing the remote and local data layer of a new KMP app or module.
- Adding a repository, mapper, error type, cache or sync path to existing shared code.
- Reviewing data-layer code against the failure modes in **Common mistakes**.
- Debugging: one malformed item empties a whole list; 401 loops or random logouts; tokens in
  Logcat or the Xcode console; iOS-only timeouts; a cached flow that stops updating in release.

## When not to use

- Adding one concrete REST endpoint end to end — use **kmp-api-endpoint** (it follows this skill's rules).
- Room setup, DAOs, migrations — **kmp-room-database**. Koin modules — **kmp-koin-di**. Token
  storage and logout wipe — **kmp-secure-storage**.

## Step 0 — Read the project first

```bash
grep -rn "HttpClient(" --include=*.kt .                                                    # 1 client
grep -rnE "sealed (class|interface) [A-Za-z]*(Result|Outcome|Either)" --include=*.kt .    # 2 wrapper
grep -rnE "DispatcherProvider|CoroutineDispatchers|Dispatchers\.IO" --include=*.kt .      # 3 dispatchers
grep -nE "ktor|serialization|coroutines|datetime|room|sqldelight|koin|kermit|napier" gradle/libs.versions.toml  # 4 stack + versions
find . -path "*commonTest*" -name "*.kt" | head -20                                       # 5 tests
```

| Finding | Then |
|---|---|
| A client factory or DI-provided `HttpClient` | Inject it. Do not build a second client. |
| A result wrapper (sealed type, `Either`, `kotlin.Result`) or a dispatcher provider | Use it. Never add a second one. |
| Room 2.x, SQLDelight, Realm or DataStore | Follow it. New cache with no precedent: Room 3 (`androidx.room3`) via **kmp-room-database**. |
| Koin, kotlin-inject, Hilt or manual DI; Kermit or Napier | Wire in that idiom; route HTTP logs through that logger. |
| An existing feature | Copy its layout: where DTOs live, `toDomain()` or mapper classes, use cases or not. |
| Ktor below 3.6.2, serialization 1.12.x, coroutines below 1.11, `kotlinx.datetime.Instant` | Known pitfalls and workarounds: [references/version-notes.md](references/version-notes.md). Do not upgrade as a side effect. |
| `Fake*` classes, `MockEngine`, Turbine | Write tests the same way. |

Defaults below apply only when the project has no precedent.

## Workflow

### 1. Lay out the layers

```
shared/src/commonMain/kotlin/com/example/app/
├── core/network/        HttpClient factory, AppJson, ApiResult, DataError, safeApiCall
├── core/coroutines/     DispatcherProvider
└── notes/
    ├── data/            remote/ (NotesApi, KtorNotesApi, dto/), local/ (NoteEntity, NotesDao — only
    │                    when cached), NoteMappers.kt, NotesRepositoryImpl.kt
    └── domain/          Note.kt (non-null, no annotations), NotesRepository.kt (interface)
```

Dependencies point inward: `domain` imports nothing from Ktor, kotlinx.serialization or Room. Each
feature owns its API, DTOs and repository; shared modules hold only infrastructure. Two features
calling the same endpoint may each declare a DTO — duplication is cheaper than coupling. Done when
this prints nothing:

```bash
grep -rnE "import (io\.ktor|kotlinx\.serialization|androidx\.room)" --include=*.kt $(find . -type d -name domain -path "*commonMain*")
```

### 2. One HttpClient, configured once

- Build it in core/network and provide it as a DI singleton. Never call `HttpClient()` or
  `install(...)` in feature code — a second client loses auth, timeouts and log redaction.
- The factory takes the `HttpClientEngine`: OkHttp on Android, Darwin on iOS, `MockEngine` in tests.
- It installs: `ContentNegotiation` with one shared `Json`, `HttpTimeout`, `Logging` gated by build
  type (`HEADERS` in debug, `NONE` in release) with header sanitising, `defaultRequest` with the
  base URL, and sets `expectSuccess = true`.
- Do not build it eagerly on the main thread at app start: before Ktor 3.6.0, client construction
  on Android initialised SLF4J eagerly, and a start-up ANR was reported (KTOR-9834).

Details: [references/http-client.md](references/http-client.md). Done when exactly one production
construction site exists (**Verify**).

### 3. Refresh tokens in one place

- Ktor's `Auth { bearer { loadTokens; refreshTokens } }` on the authenticated client attaches the
  token, refreshes on a 401 and retries — **single-flight** within the client. Never copy a
  401-retry loop into repository methods.
- Two clients: a plain one for login and refresh, and `named("authenticated")`. Refresh through the
  plain client (or `markAsRefreshTokenRequest()`), or a 401 on refresh loops.
- `sendWithoutRequest { it.url.host == apiHost }` keeps tokens off CDNs and pre-signed URLs.
- Sign out only when the server rejects the refresh token, never on a timeout.

Contracts, the refresher, logout cache clearing, Ktor 3.6 auth fixes (KTOR-9827, KTOR-9905):
[references/auth-refresh.md](references/auth-refresh.md).

### 4. Treat DTOs as untrusted input

```kotlin
// commonMain — notes/data/remote/dto/NoteDto.kt
@Serializable
data class NoteDto(
    @SerialName("id") val id: String? = null,
    @SerialName("title") val title: String? = null,
    @SerialName("body") val body: String? = null,
    @SerialName("updated_at") val updatedAt: Long? = null,
    @SerialName("tags") val tags: List<String>? = null,
    @SerialName("visibility") val visibility: String? = null,   // enum as String: new values must not crash old apps
)

@Serializable
data class NotesPageDto(@SerialName("items") val items: List<NoteDto>? = null, @SerialName("next_cursor") val nextCursor: String? = null)
```

- **Every response field nullable, defaulting to `null`, with an explicit `@SerialName`.** A
  non-null field the server omits for one item throws `MissingFieldException` (Ktor wraps it in
  `JsonConvertException`) and fails the whole page, not just that item. `@SerialName` keeps the
  wire contract greppable.
- Decode server enums as `String?` and map them, or a value added server-side crashes every old install.
- Timestamps and ids: `kotlin.time.Instant` and `kotlin.uuid.Uuid` have stable serializers since
  kotlinx.serialization 1.12.0, but a malformed value fails the whole response. Unless the contract
  is strict, keep `String?` (or epoch `Long?`) in the DTO and parse in the mapper. Never use the
  deprecated `kotlinx.datetime.Instant` in new code.
- No `init { require(...) }` in DTOs: validation belongs in the mapper, and the exception it throws
  changed class between kotlinx.serialization 1.12 and 1.13.
- Request bodies you send may be non-null — you control them.

### 5. Keep domain models non-null

```kotlin
// commonMain — notes/domain/Note.kt  (no serialization annotations)
data class Note(
    val id: String, val title: String, val body: String,
    val updatedAtEpochMillis: Long, val tags: List<String>, val visibility: NoteVisibility,
)
enum class NoteVisibility { Private, Shared, Unknown }
```

Nullable only where absence means something to the domain.

### 6. Map and validate in the data layer

```kotlin
// commonMain — notes/data/NoteMappers.kt
internal fun NoteDto.toDomainOrNull(): Note? {
    val id = id?.takeIf { it.isNotBlank() } ?: return null   // no identity: row is unusable, drop it
    return Note(
        id = id,
        title = title?.trim().orEmpty(),                       // cosmetic: safe fallback
        body = body.orEmpty(),
        updatedAtEpochMillis = updatedAt ?: 0L,
        tags = tags.orEmpty().filter { it.isNotBlank() },
        visibility = when (visibility?.lowercase()) {
            "private" -> NoteVisibility.Private
            "shared" -> NoteVisibility.Shared
            else -> NoteVisibility.Unknown
        },
    )
}

internal fun List<NoteDto>?.toDomainNotes(): List<Note> = orEmpty().mapNotNull { it.toDomainOrNull() }
```

Decide per field: **drop** the row when a field it cannot exist without is missing (identity,
foreign key, payment amount); **fall back** when it is cosmetic. One test per rule. Log the count
of dropped rows, never the values. Nullability never leaks past the mapper.

### 7. Keep the API service thin

```kotlin
// commonMain — notes/data/remote/NotesApi.kt
interface NotesApi {
    suspend fun getNotes(cursor: String?): NotesPageDto
}

internal class KtorNotesApi(private val client: HttpClient) : NotesApi {
    override suspend fun getNotes(cursor: String?): NotesPageDto =
        client.get("notes") { cursor?.let { parameter("cursor", it) } }.body()
}
```

No `try`/`catch` here, no mapping, no base URL. Paths are relative to the `defaultRequest` base
URL, which must end with `/`; a path with a leading `/` replaces the base path (`/v1/` is lost).

### 8. Make the repository the error boundary

```kotlin
// commonMain — notes/data/NotesRepositoryImpl.kt
class NotesRepositoryImpl(
    private val notesApi: NotesApi,
    private val dispatchers: DispatcherProvider,
) : NotesRepository {

    override suspend fun getNotes(cursor: String?): ApiResult<NotesPage> =
        safeApiCall(dispatchers.default) {
            val page = notesApi.getNotes(cursor)
            NotesPage(notes = page.items.toDomainNotes(), nextCursor = page.nextCursor)
        }
}
```

`safeApiCall` turns every exception into a typed `DataError` and **rethrows
`CancellationException`**. Ktor is main-safe, but deserialization and mapping run on the caller's
dispatcher, so large payloads move off `Main`. Types, exception mapping and serialization-version
triage: [references/api-result.md](references/api-result.md). If the project has a wrapper, map
into it. ViewModels see only domain types and the result type, never DTOs or Ktor exceptions.

### 9. Inject dispatchers

```kotlin
// commonMain — core/coroutines/DispatcherProvider.kt
interface DispatcherProvider {
    val main: CoroutineDispatcher
    val io: CoroutineDispatcher        // Dispatchers.IO needs `import kotlinx.coroutines.IO` outside the JVM
    val default: CoroutineDispatcher
}
```

Production returns `Dispatchers.Main`/`IO`/`Default`; tests pass one
`StandardTestDispatcher(testScheduler)` for all three. Never read the current dispatcher from the
context: kotlinx.coroutines 1.11 deprecates `coroutineContext[CoroutineDispatcher]` (use
`ContinuationInterceptor`) and flags passing a `Job` to `launch`/`async`, which breaks structured
concurrency.

### 10. Go offline-first when the screen must work without network

Default cache with no precedent: **Room 3** (`androidx.room3`, via **kmp-room-database**); keep
Room 2.x or SQLDelight where the project uses them.

- **Read:** the DAO returns `Flow<List<Entity>>`; the repository maps it to domain models; the UI
  observes only this. A read never throws and is not wrapped in the result type.
- **Refresh:** a `suspend` call fetches, maps and writes in one transaction (`@Transaction` DAO
  method, or `withWriteTransaction { }` across DAOs in Room 3) and returns `ApiResult<Unit>`. Its
  result drives only the spinner and error UI — the database write updates the screen.
- **Writes made offline:** insert a pending row, then trigger a sync worker. It posts, marks the
  row synced, or retries with backoff (network errors, 429, 5xx); any other 4xx marks it failed.
- **Never make a user gesture await the whole outbox.** Trigger the sync and wait a bounded time
  for the gesture's own row; returning "pending" is a valid success.
- Store a last-synced timestamp per cache key: "never loaded" is not "loaded, empty".
- Sharing a cached flow with `stateIn`/`shareIn`: use kotlinx.coroutines 1.11.0+. Earlier, an R8
  optimisation could let the sharing coroutine be garbage-collected, so minified builds stopped updating.

```kotlin
// commonMain — notes/data/OfflineNotesRepository.kt
class OfflineNotesRepository(
    private val notesApi: NotesApi,
    private val notesDao: NotesDao,
    private val dispatchers: DispatcherProvider,
) {
    fun observeNotes(): Flow<List<Note>> = notesDao.observeAll().map { rows -> rows.map { it.toDomain() } }
    suspend fun refresh(): ApiResult<Unit> = safeApiCall(dispatchers.default) {
        val notes = notesApi.getNotes(cursor = null).items.toDomainNotes()
        notesDao.replaceAll(notes.map { it.toEntity() })   // @Transaction DAO method
    }
}
```

Clearing cached tables on logout: **kmp-secure-storage**.

### 11. Wire it

```kotlin
// commonMain — notes/di/NotesDataModule.kt  (Koin, the default when nothing else exists)
val notesDataModule = module {
    single<NotesApi> { KtorNotesApi(client = get(named("authenticated"))) }
    singleOf(::NotesRepositoryImpl) bind NotesRepository::class
}
```

`singleOf(::X)` cannot pass a qualifier; use a lambda for qualified dependencies. More: **kmp-koin-di**.

### 12. Test at the seams

| Unit | Test with | Assert |
|---|---|---|
| Mapper | plain `commonTest` | each drop rule and each fallback |
| API + client config | `MockEngine` through the real factory | path, query, headers, body; 401 → refresh → retry |
| Repository | hand-written `FakeNotesApi` | success, every `DataError`, cancellation propagates |
| ViewModel | fake repository + test dispatcher | state via `_state.update { }`, one-shot events |

Use the production `AppJson` in tests. Recipes: [references/testing.md](references/testing.md).

## Quick reference

| Concern | Default | Rule |
|---|---|---|
| JSON | one `Json { ignoreUnknownKeys = true; explicitNulls = false }` | shared by client and tests |
| DTO field | `@SerialName("x") val x: T? = null` | every response field; no `init` validation |
| Errors | `ApiResult<T>` + `DataError` | mapped in the repository; `CancellationException` rethrown |
| Timeouts | `HttpTimeout` request + socket | Darwin ignores `connectTimeoutMillis` |
| Logging | `HEADERS` in debug, `NONE` in release | `sanitizeHeader` for `Authorization`, `Cookie` |
| Auth | `Auth { bearer { } }` on the authenticated client | single-flight refresh; tokens only to your host |
| Time, ids | `kotlin.time.Instant`, `kotlin.uuid.Uuid` | parse in the mapper unless the contract is strict |
| Offline | Room 3 DAO `Flow` is the source of truth | network calls write to the DB |

## Verify

Run what applies; report each line as `PASS`, `FAIL` or `NOT RUN` (with the reason). Never report
a check as passed that you did not run. Module and task names vary — read `settings.gradle.kts`
and run `./gradlew :shared:tasks --all | grep -i test` when unsure.

```bash
./gradlew :shared:allTests                         # common, Android host and iOS simulator tests
./gradlew :shared:compileKotlinIosSimulatorArm64   # commonMain compiles for iOS
./gradlew :composeApp:assembleDebug                # Android app still builds
```

Static checks (each should print nothing, or only lines you have reviewed):

```bash
grep -rn "HttpClient(" --include=*.kt . | grep -viE "test|mock"               # one production site only
grep -rnE "val [A-Za-z0-9_]+: [^?=]+(,|$)" --include=*Dto.kt .                # non-null response DTO fields
grep -rnE "println\(|NSLog\(|Log\.[dviwe]\(" --include=*.kt . | grep -v Test   # bypasses log redaction
grep -rn "install(" --include=*.kt . | grep -v "core/network" | grep -viE "test" # plugins outside the network module
grep -rnE "import kotlinx\.datetime\.(Instant|Clock)$|\[CoroutineDispatcher\]" --include=*.kt .   # deprecated APIs
```

## Common mistakes

| Mistake | Why it bites | Fix |
|---|---|---|
| Non-null DTO field without default | One item missing it fails the whole response with `MissingFieldException` / `JsonConvertException` | Nullable, `= null`, map in the repository |
| `catch (e: Exception)` or `runCatching` around a suspend call | Swallows `CancellationException`; cancelled screens keep working and leak | Catch `CancellationException` first and rethrow (see `safeApiCall`) |
| `expectSuccess = false` then `.body<T>()` | A 404 or 500 error envelope is parsed as `T` and surfaces as a misleading parse error | `expectSuccess = true`; map `ResponseException` by status |
| `HttpClient()` inside a feature or per call | Loses auth, timeouts, redaction; new connection pool each time | Inject the shared client |
| `LogLevel.ALL` / `BODY` in release | Bodies with passwords and tokens reach device logs; `sanitizeHeader` does not touch bodies | `HEADERS` in debug only, `NONE` in release |
| Refresh through the `Auth` plugin, token sent to every host, or sign-out on an offline refresh | Refresh loops, tokens on CDNs, random logouts | Plain client for refresh, `sendWithoutRequest`, sign out only on rejection — [references/auth-refresh.md](references/auth-refresh.md) |
| Triaging a parse failure without the serialization version | 1.12.x wraps decoding failures in `JsonDecodingException`; 1.13.0 reverted it | Name the version; catch `SerializationException` + `ContentConvertException` |
| Base URL without trailing `/`, or path with leading `/` | `/v1` is dropped and requests hit the wrong path | `https://api.example.com/v1/` + `get("notes")` |
| `explicitNulls = false` with PATCH | Null fields are omitted, so "clear this field" never reaches the server | Send an explicit request DTO or a `JsonObject` for clears |
| `Dispatchers.IO` hard-coded in a repository | Tests race real threads and flake | Inject `DispatcherProvider` |
| UI binds to the network response in an offline app | Data disappears offline and after process death | Observe the DAO `Flow`; network writes into it |

## Related skills

- **kmp-api-endpoint** — one endpoint end to end using these rules.
- **kmp-room-database** — Room 3 setup, DAOs, transactions, migrations, iOS linking.
- **kmp-koin-di** — modules, qualifiers, bootstrap order. **kmp-secure-storage** — tokens, logout wipe.
- Ktor client: <https://ktor.io/docs/client-create-multiplatform-application.html>, bearer auth:
  <https://ktor.io/docs/client-bearer-auth.html>
- Compose-side state and ViewModels: <https://github.com/Meet-Miyani/compose-skill>
- Android-only data patterns: <https://github.com/rcosteira79/android-skills>

Files in this skill

  • SKILL.md18.7 KB
  • references/api-result.md8.5 KB
  • references/auth-refresh.md8.3 KB
  • references/http-client.md8.4 KB
  • references/testing.md6.2 KB
  • references/version-notes.md6.2 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.