tutorial··5 min read·WoWSQL Team

Android Kotlin Backend: Postgres, Auth and Storage

Build an Android Kotlin backend on Postgres with the WoWSQL Kotlin SDK: login, per-user RLS data, avatar uploads, and where Firebase or Supabase win.

The quickest backend for an Android app is a backend as a service: your Kotlin code calls a hosted API for sign-in, data and file storage, so you don't write or run a server. WoWSQL gives an Android app PostgreSQL, auth, an auto-generated REST API, file storage and realtime, and its official Kotlin SDK (com.wowsql:wowsql-sdk on Maven Central, version 3.10.0) wraps them with Kotlin coroutines. This tutorial builds the data layer of a notes app (email sign-in, per-user rows protected by Row Level Security, avatar upload) and shows the places where the SDK and the docs disagree, so you don't lose an afternoon to them.

The data-layer code below was compiled with Kotlin 2.0.21 against the real 3.10.0 artifact from Maven Central and run against a local mock server to check the HTTP requests. The Android pieces (manifest, ViewModel, Compose screens, SharedPreferences) were not built here because that needs the Android SDK, and nothing was run against a live WoWSQL project. Test on your own device before you ship.

Key facts

  • Kotlin SDK: implementation("com.wowsql:wowsql-sdk:3.10.0"), MIT-licensed, a JVM library with suspend functions. Its Gradle metadata targets JVM 17 and it depends on Kotlin stdlib 2.0.21, kotlinx-coroutines 1.7.3, OkHttp 4.12.0 and Gson 2.10.1 (Maven Central, Kotlin SDK docs).
  • Classes: WowSQLClient (queries, realtime), ProjectAuthClient (auth), WowSQLStorage (files), WowSQLSchema (DDL, service key only).
  • REST API: PostgREST at https://<project>.wowsqlconnect.com/rest/v1. Send the anon key (wowsql_anon_...) in apikey and the signed-in user's token in Authorization: Bearer ... so RLS applies. The service key bypasses RLS and never belongs in an APK. There is no GraphQL API.
  • Auth: email and password, magic links, email or phone OTP, OAuth with 19 working providers, TOTP two-factor, optional Cloudflare Turnstile CAPTCHA (auth docs). The Kotlin SDK does not wrap anonymous sign-in, identity linking, email change or /settings.
  • Plans (pricing, 27 November 2026): Free $0 (1 project, 256 MB database, 512 MB files, 5 GB bandwidth, 10,000 MAU, read-only when over a limit), Pro $25/month (100,000 MAU, daily backups kept 7 days), Scale $99/month. Regions: Mumbai, US East and Frankfurt.

Backend options for an Android app

Data model Kotlin / Android client Free tier (checked 27 Nov 2026) Paid from
WoWSQL PostgreSQL + REST (PostgREST) Official Kotlin SDK (JVM), plain OkHttp for anything it doesn't wrap 1 project, 256 MB DB, 512 MB files, 10,000 MAU; read-only over a limit Pro $25/month
Supabase PostgreSQL + REST (PostgREST) Kotlin client library, per Supabase's own mobile guide 2 projects, 500 MB DB, 1 GB files, 50,000 MAU; paused after 1 week idle (pricing) Pro from $25/month
Firebase Firestore (NoSQL documents) Firebase Android SDK Spark plan, no payment method needed; Cloud Storage and Cloud Functions show "Not applicable" on Spark (pricing) Pay as you go (Blaze)
Convex Reactive documents + TypeScript functions Kotlin client library (listed in the Convex docs client navigation and in Supabase's guide) Free & Starter plan, 0.5 GB database, 1 GB files (pricing) $25 per developer/month

Where the others are better: Firebase bundles Cloud Messaging for push notifications, Firebase Authentication and Google's wider Android tooling, and is the default choice if you want a NoSQL model and tight Google integration. Supabase has the larger ecosystem and a bigger free tier. Convex is the strongest fit if you want live-updating queries written in TypeScript. WoWSQL's case is plain SQL, a flat monthly price per project and Mumbai hosting for Indian users. Push notifications aren't covered in this guide; use Firebase Cloud Messaging alongside any backend. For a deeper comparison read WoWSQL vs Firebase and WoWSQL vs Convex.

What you will build

A notes app with:

  1. Email sign-up and sign-in (ProjectAuthClient), with the session kept across app restarts.
  2. A notes table where each user only sees their own rows (RLS).
  3. A profile picture upload to a public avatars bucket (WowSQLStorage).
  4. A ViewModel and Compose screen on top.

Step 1: Create the project, table and bucket

  1. Create a project at app.wowsql.com/signup in Mumbai, US East or Frankfurt, and enable Authentication.
  2. Copy the project slug and the anon key (wowsql_anon_...) from Settings, API.
  3. In the SQL editor, create the table with RLS and one policy per operation:
create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null,
  title text not null,
  done boolean not null default false,
  created_at timestamptz not null default now()
);

alter table public.notes enable row level security;

create policy "read own notes"   on public.notes for select using (auth.uid() = user_id);
create policy "insert own notes" on public.notes for insert with check (auth.uid() = user_id);
create policy "update own notes" on public.notes for update using (auth.uid() = user_id) with check (auth.uid() = user_id);
create policy "delete own notes" on public.notes for delete using (auth.uid() = user_id);
  1. Create a public bucket called avatars in the dashboard's storage section, or from code with WowSQLStorage.createBucket("avatars", public = true).

Without a select policy, an RLS-enabled table returns nothing to app users, so keep the first policy. More in What is Row Level Security?

Step 2: Add the dependencies

In your module's build.gradle.kts:

android {
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
}

dependencies {
    implementation("com.wowsql:wowsql-sdk:3.10.0")
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation("com.google.code.gson:gson:2.10.1")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
}

Set the Kotlin JVM target to 17 as well. The SDK's published metadata says it targets JVM 17, so if Gradle reports an incompatible Java version, that is the reason. We did not build an Android project to confirm the Gradle resolution. The SDK declares OkHttp, Gson and coroutines as runtime dependencies, so add them yourself if your own code imports them, as the repository below does.

Add the internet permission to AndroidManifest.xml:

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

Step 3: A token store that survives restarts

ProjectAuthClient keeps tokens in memory by default. It accepts any TokenStorage (four methods, shown in the SDK source; the Kotlin docs page doesn't mention it), so back it with app-private storage:

import android.content.SharedPreferences
import com.wowsql.sdk.TokenStorage

class PrefsTokenStorage(private val prefs: SharedPreferences) : TokenStorage {
    override fun getAccessToken(): String? = prefs.getString("access", null)
    override fun setAccessToken(token: String?) = prefs.edit().putString("access", token).apply()
    override fun getRefreshToken(): String? = prefs.getString("refresh", null)
    override fun setRefreshToken(token: String?) = prefs.edit().putString("refresh", token).apply()
}

Refresh tokens are long-lived secrets. For a production app, keep them in Keystore-backed encrypted storage rather than plain preferences.

Step 4: The repository (compiled against 3.10.0)

This class signs in, reads and writes the user's own notes and uploads an avatar. It uses the SDK for auth and storage and a plain OkHttp call for the notes table. The reason is in the next section.

package com.example.notes.data

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.wowsql.sdk.AuthResponse
import com.wowsql.sdk.ProjectAuthClient
import com.wowsql.sdk.TokenStorage
import com.wowsql.sdk.WowSQLClient
import com.wowsql.sdk.WowSQLStorage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.InputStream

data class Note(
    val id: String,
    val title: String,
    val done: Boolean = false,
)

class NotesRepository(
    private val project: String,        // project slug, e.g. "myproject"
    private val anonKey: String,        // wowsql_anon_... (never the service key)
    tokenStorage: TokenStorage,
) {
    private val http = OkHttpClient()
    private val gson = Gson()
    private val restBase = "https://$project.wowsqlconnect.com/rest/v1"

    // Sign-up, sign-in, refresh and sessions
    val auth = ProjectAuthClient(projectUrl = project, apiKey = anonKey, tokenStorage = tokenStorage)

    // Public tables only: the 3.10.0 client sends the anon key as the bearer token
    val publicDb = WowSQLClient(projectUrl = project, apiKey = anonKey)

    val storage = WowSQLStorage(projectUrl = project, apiKey = anonKey)

    // Returns the user id. In 3.10.0 signIn() returns a session but no user, so fetch it with getUser().
    suspend fun signIn(email: String, password: String): String {
        val res: AuthResponse = auth.signIn(email, password)
        check(!res.requires2fa) { "2FA required: finish with auth.verifyTwoFactorLogin()" }
        checkNotNull(res.session) { "No session returned" }
        return auth.getUser().id
    }

    // Per-user rows: send the signed-in user's access token so Row Level Security applies
    private fun request(path: String): Request.Builder {
        val token = auth.getSession()["access_token"] ?: error("Not signed in")
        return Request.Builder()
            .url("$restBase/$path")
            .addHeader("apikey", anonKey)
            .addHeader("Authorization", "Bearer $token")
    }

    suspend fun listNotes(): List<Note> = withContext(Dispatchers.IO) {
        val req = request("notes?select=id,title,done&order=created_at.desc").get().build()
        http.newCall(req).execute().use { res ->
            check(res.isSuccessful) { "HTTP ${res.code}: ${res.body?.string()}" }
            val type = object : TypeToken<List<Note>>() {}.type
            gson.fromJson<List<Note>>(res.body!!.string(), type)
        }
    }

    suspend fun addNote(userId: String, title: String): Note = withContext(Dispatchers.IO) {
        val json = gson.toJson(mapOf("user_id" to userId, "title" to title))
        val req = request("notes")
            .addHeader("Prefer", "return=representation")
            .post(json.toRequestBody("application/json".toMediaType()))
            .build()
        http.newCall(req).execute().use { res ->
            check(res.isSuccessful) { "HTTP ${res.code}: ${res.body?.string()}" }
            val type = object : TypeToken<List<Note>>() {}.type
            gson.fromJson<List<Note>>(res.body!!.string(), type).first()
        }
    }

    suspend fun uploadAvatar(input: InputStream, userId: String) =
        storage.upload("avatars", input, path = "$userId/avatar.jpg", fileName = "avatar.jpg")

    fun avatarUrl(userId: String): String = storage.getPublicUrl("avatars", "$userId/avatar.jpg")
}

Create it once, for example in your Application class:

val repo = NotesRepository(
    project = "myproject",
    anonKey = BuildConfig.WOWSQL_ANON_KEY,
    tokenStorage = PrefsTokenStorage(getSharedPreferences("wowsql", MODE_PRIVATE)),
)

Why the notes call uses OkHttp instead of client.table()

In 3.10.0, WowSQLClient sends the key you give it as both the apikey header and the Authorization: Bearer token. That means client.table("notes") runs as the anon role, which is right for public tables and wrong for per-user rows protected by RLS. To act as the signed-in user, send their access token as the bearer, which is what request() does above. We ran the repository against a local mock server and confirmed the notes requests carry Authorization: Bearer <user token> while the SDK's own table query carries the anon key. The same applies to WowSQLStorage, which authenticates with the key you pass it.

For public data, the SDK query builder is convenient:

import com.wowsql.sdk.SortDirection

val posts = repo.publicDb.table("public_posts")
    .select("id", "title")
    .eq("published", true)
    .orderBy("created_at", SortDirection.DESC)
    .limit(20)
    .get()

posts.data.forEach { println(it["title"]) }

Step 5: Sign-up, sign-in and sessions

// Sign up (the 4th argument is user metadata)
val signedUp = repo.auth.signUp("user@example.com", "a-strong-password", "Asha K", null)

// Sign in. In 3.10.0 the result carries a session but no user: call getUser() for the profile.
val login = repo.auth.signIn("user@example.com", "a-strong-password")
when {
    login.requires2fa -> {
        // TOTP is on for this user: finish with the 6-digit code
        repo.auth.verifyTwoFactorLogin(login.pendingToken!!, code = "123456")
    }
    login.session == null -> { /* verify your email first */ }
    else -> { val me = repo.auth.getUser() /* signed in; tokens are stored via PrefsTokenStorage */ }
}

// Later: refresh and sign out
repo.auth.refreshToken()
repo.auth.logout()

session is nullable since 3.10.0, because a sign-up that needs email verification returns no session. If you turn on CAPTCHA in Attack Protection, pass a captchaToken (a Cloudflare Turnstile token) to signUp and signIn. For passwordless sign-in see sendOtp, verifyOtp and sendMagicLink in the Kotlin docs.

Social login on Android

Enable the provider in Auth, Providers, register the redirect URI WoWSQL shows (https://<slug>.wowsqlconnect.com/auth/v1/oauth/<provider>/callback) with the provider, then:

val oauth = repo.auth.getOAuthAuthorizationUrl("google", "https://yourapp.com/auth/callback")
val url = oauth["authorization_url"]!!
// Open url in a Custom Tab. WoWSQL finishes the provider flow and redirects to your
// frontend_redirect_uri with ?access_token=...&refresh_token=...
// Catch that URL with an intent filter (an Android App Link is safest) and then:
repo.auth.setSession(accessToken, refreshToken)

Read tokens from the redirect URI in the activity that receives the link, and don't log it. More in Add Google, GitHub and Apple login.

Step 6: Upload an avatar

On Android you usually have a Uri, not a file path, so use the stream-based upload:

suspend fun uploadAvatarFromUri(context: Context, uri: Uri, userId: String) {
    context.contentResolver.openInputStream(uri)?.use { stream ->
        repo.uploadAvatar(stream, userId)
    }
}

// Show it with Coil, Glide or any image loader:
val avatarUrl = repo.avatarUrl(userId) // https://<project>.wowsqlconnect.com/storage/v1/object/public/avatars/<userId>/avatar.jpg

Public buckets serve files at /storage/v1/object/public/{bucket}/{path}. Free includes 512 MB of file storage and Pro 100 GB. For private files, follow the storage docs and never put the service key in the app.

Step 7: ViewModel and Compose (not compiled)

data class NotesUiState(
    val notes: List<Note> = emptyList(),
    val loading: Boolean = false,
    val error: String? = null,
    val userId: String? = null,
)

class NotesViewModel(private val repo: NotesRepository) : ViewModel() {
    private val _state = MutableStateFlow(NotesUiState())
    val state: StateFlow<NotesUiState> = _state

    fun signIn(email: String, password: String) = viewModelScope.launch {
        _state.update { it.copy(loading = true, error = null) }
        try {
            val id = repo.signIn(email, password) // user id; see the note on signIn() above
            _state.update { it.copy(userId = id) }
            refresh()
        } catch (e: Exception) {
            _state.update { it.copy(loading = false, error = e.message) }
        }
    }

    fun refresh() = viewModelScope.launch {
        try {
            _state.update { it.copy(notes = repo.listNotes(), loading = false) }
        } catch (e: Exception) {
            _state.update { it.copy(loading = false, error = e.message) }
        }
    }

    fun add(title: String) = viewModelScope.launch {
        val uid = _state.value.userId ?: return@launch
        try {
            repo.addNote(uid, title)
            refresh()
        } catch (e: Exception) {
            _state.update { it.copy(error = e.message) }
        }
    }
}

@Composable
fun NotesScreen(vm: NotesViewModel) {
    val state by vm.state.collectAsState()
    var title by remember { mutableStateOf("") }

    Column(Modifier.padding(16.dp)) {
        OutlinedTextField(title, { title = it }, label = { Text("New note") })
        Button(onClick = { vm.add(title); title = "" }) { Text("Add") }
        state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
        LazyColumn {
            items(state.notes, key = { it.id }) { Text(it.title) }
        }
    }
}

Every SDK call is a suspend function that switches to Dispatchers.IO internally, so calling it from viewModelScope is safe. The Kotlin docs show a LiveData version; the StateFlow shape above works the same way.

Realtime updates

To refresh the list when rows change, enable the table once (POST /realtime/v1/enable with {"schema_name":"public","table_name":"notes"}) and subscribe:

val unsubscribe = repo.publicDb.realtime().subscribe("notes", { change ->
    println("${change["event"]} ${change["new"]}")
}, schema = "public", event = "*")
// later: unsubscribe()

The socket authenticates with the project key in the apikey query parameter, and payloads are capped at 64 KiB (realtime docs). Because it uses the key rather than the user's token, test exactly what an anon-key client receives on your table before you rely on RLS for realtime data, and refetch through the REST call above when an event arrives.

Where the Kotlin docs and the 3.10.0 SDK disagree

We compiled the snippets from the Kotlin SDK docs page as written against the 3.10.0 artifact on 27 November 2026. These did not compile:

Docs example What the SDK actually has
client.table<Map<String, Any?>>("users") table(name) takes no type argument
.order("created_at", "desc") orderBy / order take SortDirection.DESC, not a string
.in("role", listOf(...)) inList(...); in is a Kotlin keyword
.like("email", "%@gmail.com") straight on table(...) call .select(...) first; like lives on the query builder
oauthUrl.authorizationUrl getOAuthAuthorizationUrl returns a map; use oauth["authorization_url"]

The snippets in this article use the forms that compile. Two more differences: signIn() returns a session but no user object (call getUser()), and the docs describe auth routes under /auth/v1/ while the SDK source builds them under /api/auth (the TypeScript SDK does the same). We did not test which route the live server prefers, so call auth through the SDK rather than hand-writing requests.

Before you ship

  • Never ship the service key. An APK can be unpacked. Use the anon key in the app and keep wowsql_service_... on a server.
  • Keep TLS verification on. The SDK constructors have a verifySsl flag that defaults to true; do not set it to false in a release build.
  • Add RLS to every table and test with two accounts. See the BaaS security checklist.
  • Plan for limits. On Free, going over a limit makes the project read-only (reads and deletes still work). Free has no platform backups; Pro and Scale keep daily backups for 7 days (backups policy).
  • Offline use. The SDK docs describe no offline cache; use Room or DataStore if the app must work without a network.

Related guides

FAQ

What is the best backend for an Android Kotlin app?

It depends on your data model. For SQL and Postgres, WoWSQL and Supabase both offer auth, an auto-generated REST API and file storage with Kotlin libraries. For NoSQL documents and push notifications, Firebase is the common choice. For live TypeScript queries, Convex. WoWSQL's Kotlin SDK is on Maven Central as com.wowsql:wowsql-sdk:3.10.0.

Does WoWSQL have a Kotlin SDK for Android?

Yes. The official Kotlin SDK is published on Maven Central (com.wowsql:wowsql-sdk, version 3.10.0 on 27 November 2026). It is a JVM library with coroutine-based suspend functions for queries, auth, storage and realtime. It is not an Android-specific library, so on Android you configure Java 17 and add your own ViewModel layer.

Is there a Firebase alternative for Android with SQL?

Yes. WoWSQL and Supabase both give an Android app PostgreSQL with Row Level Security instead of Firestore documents. Migrating means remodelling your data as tables; see How to migrate Firebase to Postgres. You would add Firebase Cloud Messaging separately if you need push.

How do I use Row Level Security from an Android app?

Enable RLS on the table, write one policy per operation using auth.uid(), and call the REST API with the anon key in apikey and the signed-in user's access token in Authorization: Bearer. In 3.10.0, WowSQLClient sends the anon key as the bearer, so use a direct OkHttp call (as shown) for per-user tables.

Can I use Jetpack Compose with the WoWSQL SDK?

Yes. The SDK has no Compose dependency, so call its suspend functions from a ViewModel, expose a StateFlow and collect it in your composables. The article shows the pattern; the Compose code there was not compiled in our test setup.

How do I keep users signed in on Android?

Pass a TokenStorage implementation to ProjectAuthClient (the tokenStorage parameter) that writes the access and refresh tokens to app-private storage, ideally Keystore-backed encryption. Call refreshToken() when an access token expires.

Is the WoWSQL free tier enough for an Android side project?

Often, yes. Free includes 1 project, 256 MB of database, 512 MB of files, 5 GB of bandwidth and 10,000 monthly active users, but it has no platform backups and becomes read-only when you exceed a limit. Pro is $25 per month.

Create a free WoWSQL project · Pricing · Kotlin SDK docs