A field guide for teams who have already been paged at 2 a.m. because a marketing email opened the wrong screen.

Links That Land Right: Type-Safe Deep Linking in Navigation 3, Failure Modes Included
Deep links are the one part of your navigation graph you do not control. Every other route is typed by your own code, reviewed by your own teammates and exercised by your own tests. A deep link is a string that arrives from a browser, a push notification, a QR code, a partner app or a typo in a campaign spreadsheet, and your app is expected to turn it into a sensible screen with a sensible back stack.
Navigation 3 treats this as a first-class problem. Starting with 1.2.0, the library ships a deep link API built around DeepLinkRequest and DeepLinkMatcher, with kotlinx.serialization doing the argument decoding. This post follows the structure of the Android Dev Summit 2026 session on the topic (by Clara Fok and Ian Lake) and cross-checks everything against the official guide and the nav3-recipes repository. I will build one small, original example end to end and spend as much time on how it breaks as on how it works.
The example app is Fernwood, a cycling-route app. Its links look like https://links.fernwood.app/routes/42?tab=elevation.
1. The shape of the problem
Before any API, it helps to see the whole journey of a link. There are five steps, and every bug in this article lives in one of them.
Three design decisions in this pipeline are worth noticing, because they explain most of the API:
- Matching is separate from navigating. A matcher never touches your back stack. It answers one question: “is this request mine, and if so, which key does it map to?” That keeps matchers pure, testable and easy to spread across feature modules.
- Matches are comparable. Several matchers can say yes to the same link, and the library gives you a way to pick the most specific one instead of relying on registration order.
-
The back stack is your output, not a side effect. You end up with a
List<NavKey>. What you do with it (render it, persist it, log it) is your business.
Here are the keys we will use. Note they are plain @Serializable types, which matters later. The near property uses a documented pattern: to decode a repeated query parameter into a list of custom objects, you implement DeepLinkSerializer<T> for the element type and annotate the list's type argument with @Serializable(with = ...). The official Match URI deep links guide shows this same form under "Custom objects in repeated query parameters". No @Contextual or SerializersModule is needed.
@Serializable
data object HomeKey : NavKey
enum class RouteTab { OVERVIEW, ELEVATION, REVIEWS }
enum class Difficulty { ANY, EASY, MODERATE, HARD }
@Serializable
data class RouteKey(
val routeId: Long,
val tab: RouteTab = RouteTab.OVERVIEW,
) : NavKey
@Serializable
data class RouteListKey(
val difficulty: Difficulty = Difficulty.ANY,
val near: List<@Serializable(with = WaypointSerializer::class) Waypoint> = emptyList(),
) : NavKey
2. API design and URI pattern matching
Requests, matchers, results
A DeepLinkRequest is the incoming link: a DeepLinkUri plus optional extras such as the intent action or MIME type. On Android you build one straight from an Intent:
val request = DeepLinkRequest(intent = intent)
A DeepLinkMatcher binds a link shape to a navigation key. Calling match(request) returns a match result carrying the key, or null. Three matchers ship in the box: UriDeepLinkMatcher for hierarchical URIs, StaticKeyDeepLinkMatcher for fixed links (a launcher shortcut that always opens Home, say) and a back-stack-building matcher we will meet in section 5.
The workhorse is UriDeepLinkMatcher. You give it a pattern and the serializer of the key it should produce:
val routeMatcher = UriDeepLinkMatcher(
DeepLinkUri("links.fernwood.app/routes/{routeId}?tab={tab}"),
serializer<RouteKey>(),
)
Placeholder names map to property names on the key. That single convention is what makes the whole thing type-safe: rename routeId in the key and forget the pattern, and the argument is simply never found.
What a pattern actually compares
UriDeepLinkMatcher splits a URI into scheme, authority, path, query and fragment, and judges each part on its own rules. Knowing those rules cold is the difference between "it works on my emulator" and "it works for the link the campaign team actually sent".
The rules that bite in production:
-
The authority is an exact, case-insensitive match, and nothing else. No wildcards, no placeholders.
fernwood.appandlinks.fernwood.appare different authorities, so a link pasted without the subdomain silently does not match. -
A trailing slash is an extra, empty path segment.
/routes/42/is not/routes/42. URL builders, CMS plugins and email tools add slashes all the time. -
Query order does not matter and unknown parameters are ignored. This is good news for
utm_*noise, but it also means a typo in a parameter name is not an error; you just get the default. -
Scheme handling is asymmetric. A pattern with no scheme accepts http and https. A pattern written with
httpaccepts both. A pattern written withhttpsrejects plainhttp. Pick on purpose.
When two matchers both say yes
Suppose Fernwood also supports links.fernwood.app/routes/saved for the user's bookmarks. The link /routes/saved now fits two patterns. The library ranks UriMatchResult instances by comparing, in order: whether the path is literal, how many path arguments were captured, whether any arguments were captured, and finally the total argument count.
In practice, the literal path wins, which is what you want. The failure mode is subtler. If routeId were a String instead of a Long, saved would be a perfectly valid route id as far as parsing goes, and you would rely entirely on ranking to avoid opening a route called "saved". With a Long, the placeholder match fails to parse and returns null before ranking even matters. Prefer the narrowest argument type you can, because the type system becomes your first disambiguation layer.
And one operational rule: if two different keys can produce identically ranked results for the same link, the winner is an accident of list order. Treat that as a bug and cover it in a test.
3. Type-safe deserialization and custom serializers
Every extracted argument starts as a String. What happens next depends on the property type, and it is worth knowing which of four lanes your property falls into.
Standard serialization covers primitives, strings, enums and single-dimension collections of those. A repeated query parameter such as ?id=10&id=20 becomes a List<Int> with no code from you. Enums match case-sensitively against the entry names, so ?tab=elevation fails for RouteTab.ELEVATION while ?tab=ELEVATION works. If you control the producers of the link, fine; if you do not, see section 4.
Flattening applies to nested @Serializable classes: each inner property gets its own placeholder in the same URI namespace. The trap is name collision. A parent id and a nested id fight over one parameter, and @SerialName is the way out.
Writing a DeepLinkSerializer
For anything that is one string in the URL but a richer type in your code, you extend DeepLinkSerializer<T>. It is a KSerializer that converts between a single String and T.
Fernwood passes map positions as lat,lng. First, the parsing logic, written once and kept free of serialization concerns so it can be reused (we will reuse it in section 4):
data class Waypoint(val lat: Double, val lng: Double)
fun parseWaypoint(raw: String): Waypoint? {
val parts = raw.split(',')
if (parts.size != 2) return null
val lat = parts[0].trim().toDoubleOrNull() ?: return null
val lng = parts[1].trim().toDoubleOrNull() ?: return null
// Range checks also reject NaN, because every comparison with NaN is false.
return if (lat in -90.0..90.0 && lng in -180.0..180.0) Waypoint(lat, lng) else null
}
That comment is a real failure mode, not decoration. "NaN".toDoubleOrNull() happily returns NaN, and so does "Infinity" for an infinite value. A coordinate that is not a number will sail through a naive parser and surface later as a map camera that never settles. The range check handles it because NaN in -90.0..90.0 is false.
Now the serializer, a thin wrapper that converts “could not parse” into the exception type the serialization layer expects:
object WaypointSerializer : DeepLinkSerializer<Waypoint>() {
override val serialName: String = "app.fernwood.Waypoint"
override fun deserialize(value: String): Waypoint =
parseWaypoint(value)
?: throw SerializationException("Expected 'lat,lng' within valid ranges, got '$value'")
override fun serialize(value: Waypoint): String = "${value.lat},${value.lng}"
}
Two details I want you to notice. The serializer is attached where it is used, using @Serializable(with = ...) on the type argument of the list in RouteListKey, which is how a repeated parameter like ?near=47.6,-122.3&near=47.7,-122.4 becomes a List<Waypoint>. And a custom serializer for a type like java.time.LocalDate has the same wrinkle as Waypoint: the platform's parse throws its own exception type, so wrap it:
object RideDateSerializer : DeepLinkSerializer<LocalDate>() {
override val serialName: String = "app.fernwood.RideDate"
override fun deserialize(value: String): LocalDate =
try {
LocalDate.parse(value)
} catch (e: DateTimeParseException) {
throw SerializationException("Expected ISO date, got '$value'", e)
}
override fun serialize(value: LocalDate): String = value.toString()
}
(java.time needs API 26 or core library desugaring on older devices.)
Null versus exception is the most important distinction in this API
The library separates two kinds of failure, and your error handling should too.
A mismatch returns null. Missing required parameter, a value that does not parse as the property type, an enum name that does not exist: all of these mean "this link is not for this matcher", and the next matcher gets its turn. Parameters with default values simply fall back to the default, including when the query parameter is present but empty.
A misconfiguration throws. A Map property, a nested collection, a List<Filter> with no serializer on the element type: these are mistakes in your key class, not in the link, and they blow up at match time.
That has a consequence people miss. The throwing case happens when a link arrives, not when the app starts. A broken key class can ship to production, sit quietly for weeks, and crash the front door the first time someone taps the right link. Instantiate and match every matcher against at least one sample URL in a unit test. One caveat on that advice: DeepLinkUri is a typealias for android.net.Uri on Android, so plain JVM tests hit the "not mocked" stub problem. Use Robolectric or run these as instrumented tests.
Also, test what your serializer does on malformed input in your library version. The official example throws SerializationException from deserialize, and the safe behavior for a bad value from outside is a mismatch, not a crash. I would not assume; write the test, and if your version propagates the exception, catch it at the router (section 5).
4. Preprocessing arguments with custom matchers
Sometimes the link is valid in spirit but wrong in shape. Fernwood has three real-world examples:
- a legacy mobile site produced
/v1/routes/42, and the QR codes on printed trail signs cannot be reprinted - an email tool appends a trailing slash
- a maps app hands the app a
geo:link, which is not hierarchical at all
UriDeepLinkMatcher is an open class for exactly this reason. You can override matchUri to normalize the incoming URI before the real matching runs, matchRequest to inspect extras first, and matchArguments to transform extracted values before the key is built.
Here is a normalizing matcher for the first two problems:
class TolerantUriMatcher<T : Any>(
pattern: DeepLinkUri,
serializer: KSerializer<T>,
) : UriDeepLinkMatcher<T>(pattern, serializer) {
private val legacyPrefix = Regex("^/v1(?=/|$)")
override fun matchUri(uri: DeepLinkUri): UriMatchResult<T>? {
val path = uri.encodedPath ?: return super.matchUri(uri)
val cleaned = path
.replace(legacyPrefix, "")
.trimEnd('/')
.ifEmpty { "/" }
if (cleaned == path) return super.matchUri(uri)
// On Android DeepLinkUri is android.net.Uri, so buildUpon() is available.
return super.matchUri(uri.buildUpon().encodedPath(cleaned).build())
}
}
Two failure modes are baked into how I wrote that, on purpose:
-
Normalize the path, not the whole string. The tempting version is
uri.toString().replace("/v1", ""). That also rewrites a query value containing/v1, and it corrupts any path segment that merely starts with those characters. Anchoring the regex and working onencodedPathavoids both. - Normalizing widens what you accept. Every normalization is a new input shape you now support forever. Keep this layer small and documented, and prefer fixing the producer when you can.
When the link is not a URI at all
The geo: scheme is opaque, so UriDeepLinkMatcher is the wrong tool and you extend DeepLinkMatcher directly. You supply the key type and the result type, and implement matchRequest:
class GeoLinkMatcher : DeepLinkMatcher<RouteListKey, DeepLinkMatcher.MatchResult<RouteListKey>>() {
override fun matchRequest(request: DeepLinkRequest): MatchResult<RouteListKey>? {
val uri = request.uri ?: return null
if (uri.scheme != "geo") return null
// schemeSpecificPart is Android-only, and may carry a "?z=12" suffix.
val raw = uri.schemeSpecificPart?.substringBefore('?') ?: return null
val center = parseWaypoint(raw) ?: return null
return MatchResult(RouteListKey(near = listOf(center)))
}
}
This is where factoring parseWaypoint out of the serializer pays off: one validation routine, two entry points. If you later need to rank this matcher against others, extend MatchResult and override compareTo, and remember to unwrap a wrapped result first when the matcher sits inside a back-stack matcher. Otherwise your precedence logic silently compares the wrapper instead of the thing inside it.
5. Synthetic back stacks
Here is the part that separates a deep link that works from one that feels right.
When a user taps a link to a route, you can resolve to listOf(RouteKey(42)) and call it done. The screen renders. Then the user presses Up, and there is nothing above it. Depending on how you wired things, they leave the app, or worse, land on a blank state. They came from a link, but they did not stop being a user of your app.
A synthetic back stack fixes this by constructing the history the user would have had. You attach it to a matcher with withBackStack:
private val hosts = listOf("links.fernwood.app", "fernwood.app")
private fun routeMatchers() = hosts.map { host ->
TolerantUriMatcher(
DeepLinkUri("$host/routes/{routeId}?tab={tab}"),
serializer<RouteKey>(),
).withBackStack { result ->
listOf(HomeKey, RouteListKey(), result.key)
}
}
Look at what the back stack is not: it is not just [Home, Route]. Putting the route list in between means Up goes to "all routes", which is where a user browsing normally would have come from. The policy is a product decision, and it belongs in the matcher where it is declared and testable, not in a screen's LaunchedEffect.
Notice also the two hosts. Because authority matching is exact, the apex domain needs its own matcher. Generating them from a list keeps the two from drifting apart.
The router
The router is the only place that knows how to turn a request into a stack. It collates matchers, picks the best result, and always returns something renderable:
class DeepLinkRouter(
private val matchers: List<DeepLinkMatcher<*, *>>,
private val fallback: List<NavKey> = listOf(HomeKey),
) {
fun resolve(request: DeepLinkRequest): List<NavKey> {
val best = matchers.mapNotNull { it.match(request) }.maxOrNull()
return when (best) {
null -> fallback
is BackStackMatchResult<*, *> -> best.backStack.filterIsInstance<NavKey>()
else -> listOfNotNull(best.key as? NavKey).ifEmpty { fallback }
}
}
/** Release-build wrapper: a bad link must never crash the front door. */
fun resolveSafely(request: DeepLinkRequest, onError: (Throwable) -> Unit): List<NavKey> =
try {
resolve(request)
} catch (e: SerializationException) {
onError(e); fallback
} catch (e: IllegalArgumentException) {
onError(e); fallback
}
}
val fernwoodMatchers: List<DeepLinkMatcher<*, *>> =
routeMatchers() + GeoLinkMatcher()
Two small idioms are doing real work. filterIsInstance<NavKey>() replaces the unchecked cast you would otherwise need after star projection, so a wrong type is dropped instead of crashing later. And resolveSafely exists because of section 3: a matcher that throws is a bug, but it should be reported and recovered from, not turned into a launch crash. In debug builds and tests, call resolve directly so the bug is loud.
Wiring it into an activity without breaking state
Now the failure modes that no amount of correct matching saves you from. The first one is the most common, and it is entirely about lifecycle.
class MainActivity : ComponentActivity() {
private val router = DeepLinkRouter(fernwoodMatchers)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val initial = router.resolveSafely(DeepLinkRequest(intent = intent)) { Log.w("Deeplink", it) }
setContent {
FernwoodApp(activity = this, router = router, initialStack = initial)
}
}
}
@Composable
fun FernwoodApp(activity: ComponentActivity, router: DeepLinkRouter, initialStack: List<NavKey>) {
// Initial elements apply only when there is no saved state.
val backStack = rememberNavBackStack(*initialStack.toTypedArray())
DisposableEffect(activity) {
val listener = Consumer<Intent> { newIntent ->
val stack = router.resolveSafely(DeepLinkRequest(intent = newIntent)) { Log.w("Deeplink", it) }
Snapshot.withMutableSnapshot { backStack.clear(); backStack.addAll(stack) }
}
activity.addOnNewIntentListener(listener)
onDispose { activity.removeOnNewIntentListener(listener) }
}
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider = entryProvider {
entry<HomeKey> { HomeScreen() }
entry<RouteListKey> { RouteListScreen(it) }
entry<RouteKey> { RouteScreen(it) }
},
)
}
What each line is protecting against:
-
Re-applying the link on every recreation. The original
Intentis still attached to the activity after rotation or process death. If you rebuild the stack from it in everyonCreate, the user's progress is replaced by the link's starting point. Passing the resolved stack as the initial value ofrememberNavBackStackmeans it is used only when there is no saved state, so a restored session keeps its own history. -
onNewIntentfor already-running activities. With a single-top style launch mode, a second link does not create a new activity; it delivers a new intent to the existing one. If you only handleonCreate, the second link is ignored and the user sees whatever was already there. The listener above covers that. -
The empty stack in the middle. Calling
clear()and thenaddAll()as separate state changes can expose a momentary empty stack, andNavDisplayhas nothing to render for it. Doing both inside one mutable snapshot makes the swap atomic.
Cross-app links and task stacks
Everything so far is about the in-app stack. Links from another app add a second dimension: which Android task your activity lands in. The official deeplinks-syntheticbackstack recipe simulates an "App A" linking into "App B" and demonstrates both options. With the link opened in the caller's existing task, Back returns to the calling app, and pressing Up moves you to your own app's parent screen in your own task. Opened in a new task, both Back and Up stay inside your app. Neither is universally right; what matters is that you decided, and that Up and Back behave consistently with that decision. Read the recipe's navigateUp helper before writing your own.
6. Lightning round: the things that will still get you
Verify your App Links, then verify the verification. An unverified HTTPS link shows a disambiguation dialog or opens the browser. After a release, check the state on a real device:
adb shell pm get-app-links com.fernwood.app
adb shell pm verify-app-links --re-verify com.fernwood.app
adb shell am start -W -a android.intent.action.VIEW \
-d "https://links.fernwood.app/routes/42?tab=ELEVATION" com.fernwood.app
Intent filters and matchers must agree. The manifest decides whether your activity is offered the link at all, and the matchers decide what to do with it. Add a matcher for a new path without adding the filter and it works from adb and nowhere else. Keep one list of supported patterns and derive both from it, or at least have a test that compares them.
Treat every link as hostile input. A deep link is attacker-controllable. Never perform a destructive or irreversible action (delete, purchase, sign out) straight from a link; land on a confirmation screen. Do not put tokens in URLs. DeepLinkRequest(intent = ...) also copies the intent's extras into the request, so treat those as untrusted too, especially on exported activities.
Auth gates belong in the stack, not in a global. If a route needs a signed-in user, resolve to [Home, Login(next = RouteKey(42))], not "remember the link in a static variable and replay it later". The static variable is lost on process death; the stack is persisted.
Modularization can fail silently. If each feature module contributes its own matchers (the guide suggests multibindings for this), a module that is accidentally excluded from a build variant produces no error. Links just fall back to Home. Add a test asserting that every key that is meant to be linkable has at least one matcher in the final collated list.
Pin the version and read the changelog. This API is young, and the release notes show it moving: factory helpers such as fromAction and fromMimeType were removed in favor of the extras field, empty path segments and empty query values got fixes, and http versus https matching was corrected. Code copied from an older blog post (including a version of this one) may not compile against your resolved version.
Summary
The mental model fits in four sentences. A link becomes a DeepLinkRequest. Matchers turn requests into typed keys or null, ranked so the most specific one wins. Types decide whether a bad value is a harmless mismatch or a loud misconfiguration. And a synthetic back stack is what turns "the screen rendered" into "the app feels like it was already open".
A short checklist to take to your next code review:
- Does every linkable key have a unit or instrumented test that matches a real sample URL?
- Are apex and
wwwhosts, trailing slashes and legacy prefixes handled deliberately? - Is the narrowest possible type used for each argument, and does each custom serializer reject
NaN, empty and out-of-range input? - Does the initial stack apply only without saved state, and is
onNewIntenthandled? - Does a thrown matcher exception degrade to a fallback instead of crashing launch?
- Do Up and Back behave correctly for links from both inside and outside your app?
References
- Android Developers, Support deep links (Navigation 3 guide): https://developer.android.com/guide/navigation/navigation-3/deep-links
- Android Developers, Match URI deep links: https://developer.android.com/guide/navigation/navigation-3/deep-links/uri-matcher
- Android Developers, Create custom DeepLinkMatcher classes: https://developer.android.com/guide/navigation/navigation-3/deep-links/custom-matchers
- Android Developers, Navigation 3 release notes: https://developer.android.com/jetpack/androidx/releases/navigation3
- Android Developers, Deep Link Synthetic BackStack Recipe: https://developer.android.com/guide/navigation/navigation-3/recipes/deeplinks-syntheticbackstack
-
android/nav3-recipeson GitHub: https://github.com/android/nav3-recipes - Android Dev Summit 2026 session, Building type-safe deep links with Jetpack Navigation3: https://www.youtube.com/watch?v=cgmY14gf4zg
📘 Master Your Next Technical Interview
Since Java is the foundation of Android development, mastering DSA is essential. I highly recommend “Mastering Data Structures & Algorithms in Java”. It’s a focused roadmap covering 100+ coding challenges to help you ace your technical rounds.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.






Top comments (0)