Skip to content
Görkem KaraLead Mobile Developer

Type-Safe Navigation in Jetpack Compose with Jetpack Navigation 2.8.0

Android Development5 min read

The release of Jetpack Navigation 2.8.0 brings type-safe navigation APIs to Android developers, making it easier to define navigation destinations and pass data between them. This upgrade enhances the safety and simplicity of handling navigation in Compose-based UIs by offering compile-time safety and structured argument passing.

Update (November 2026): the type-safe APIs introduced in 2.8.0 are still how navigation works in Navigation 2.x. The examples below are updated for the current stable release, Navigation 2.10.2. If you are starting a new Compose-only app, also look at Navigation 3 (androidx.navigation3, stable 1.2.2), a separate library where you own the back stack.

Diagram of the key steps in Type-Safe Navigation in Jetpack Compose with Jetpack Navigation 2.8.0: Why Type-Safe Navigation Matters, Setting Up Your Project, Defining Destinations and Passing Data

Why Type-Safe Navigation Matters

Previously, developers needed to manage routes using string-based arguments, leading to potential runtime errors if arguments were missing or incorrectly passed. With type-safe navigation, the @Serializable annotation and Kotlin’s powerful type system come together to ensure arguments are correctly defined and passed between destinations.

Benefits of Type-Safe Navigation

  • Compile-Time Safety: Navigation errors are caught at compile time, reducing runtime crashes.

  • Structured Data: Arguments are passed as Kotlin types, making it easier to work with complex data structures.

  • Cleaner Code: Less boilerplate and string manipulation means easier-to-read and maintainable code.

1. Setting Up Your Project

To get started, you need to add the Jetpack Navigation library and the Kotlin serialization plugin to your project:

// build.gradle.kts (Project Level)
plugins {
    // Use the same version as the Kotlin plugin in your project
    kotlin("plugin.serialization") version "2.4.10" apply false
}

// build.gradle.kts (App Level)
plugins {
    kotlin("plugin.serialization")
}

dependencies {
    implementation("androidx.navigation:navigation-compose:2.10.2")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.13.0")
}

The serialization plugin version must match the Kotlin version your project uses. Now, you can use the @Serializable annotation to create serializable classes for your routes.

2. Defining Destinations and Passing Data

With type-safe navigation, you define routes using Kotlin classes. For example, consider an app where the Home screen displays a list of articles, and clicking an article takes you to an Article screen with detailed information.

Creating the Routes

Type-safe navigation routes in Jetpack Compose with Navigation 2.8.0

navigation compose type-safe routing

First, create the route types: a data object for the Home screen (it has no arguments) and a data class for the Article route:

@Serializable
data object Home

@Serializable
data class Article(val id: String, val title: String)

In your navigation graph, define the Article screen as a composable destination:

NavHost(navController = navController, startDestination = Home) {
    composable<Home> {
        HomeScreen(onArticleClick = { id, title -> 
            navController.navigate(route = Article(id = id, title = title))
        })
    }

    composable<Article> { backStackEntry ->
        val article: Article = backStackEntry.toRoute()
        ArticleScreen(article)
    }
}

In this example, Home is the starting destination, and Article is a route that accepts an Article data class. You can then use the backStackEntry.toRoute() function to retrieve the Article data for rendering the ArticleScreen.

3. Deep Linking to Destinations

Deep links allow users to navigate directly to a specific screen within your app. Here’s how you add a deep link to the Article screen:

composable<Article>(
    deepLinks = listOf(
        navDeepLink<Article>("https://www.example.com/article")
    )
) { backStackEntry ->
    val article: Article = backStackEntry.toRoute()
    ArticleScreen(article)
}

navDeepLink<Article>() builds the URL pattern from the route class: required arguments become path segments and arguments with default values become query parameters. For Article(id, title) the generated pattern is https://www.example.com/article/{id}/{title}. The activity also needs a matching <intent-filter> for this host in AndroidManifest.xml. You can test it using ADB:

adb shell am start -a android.intent.action.VIEW -d "https://www.example.com/article/ABC/Hello" com.example.yourapp

Deep Link Testing Tip

To debug your deep links, you can print the NavBackStackEntry.destination.route in your composable function to view the generated URL in logcat.

4. Using Enums and Nullable Types

You can also use nullable types and enums as navigation arguments. Enums are particularly useful for passing a set of predefined values.

@Serializable
data class Article(val id: String, val category: Category?)

enum class Category {
    TECH, LIFESTYLE, EDUCATION
}

Nullable arguments work out of the box. Enums need one extra step: mark the enum class with @Keep so R8 doesn’t remove it in minified builds. Since Navigation 2.9, a lint check warns you when an enum used in a type-safe route is missing @Keep:

@Keep
enum class Category {
    TECH, LIFESTYLE, EDUCATION
}

Then, navigating to the Article route with an enum looks like this:

navController.navigate(route = Article(id = "ABC", category = Category.TECH))

5. Testing Your Navigation Code

Testing navigation in Compose is usually done using instrumented tests to simulate user actions. For example, the following test ensures that clicking an article in the Home screen navigates correctly to the Article screen:

@RunWith(AndroidJUnit4::class)
class NavigationTest {
  @get:Rule
  val composeTestRule = createAndroidComposeRule<MainActivity>()

  @Test
  fun onHomeScreen_whenArticleIsTapped_thenArticleScreenIsDisplayed() {
    composeTestRule.apply {
      onNodeWithText("View details about Article ABC").performClick()
      onNodeWithText("Article details for ABC").assertExists()
    }
  }
}

Debugging Tip

If you need to pause your test for debugging, you can use:

composeTestRule.waitUntil(timeoutMillis = 3_600_000) { false }

This will pause the test execution, allowing you to interact with the app and inspect its state.

6. Migrating from String-Based Routes

If you are currently using string-based routes for navigation, migrating to type-safe routes involves:

  • Creating a serializable class for each route.

  • Replacing string-based route definitions with type-safe composable routes.

  • Using toRoute() to retrieve the route arguments.

// Before
const val ARTICLE_ID_KEY = "id"
const val ARTICLE_ROUTE = "article/{$ARTICLE_ID_KEY}"

// After
@Serializable data class Article(val id: String)
composable<Article> { backStackEntry ->
    val article: Article = backStackEntry.toRoute()
}

7. Top-Level Navigation UI

If your app has top-level navigation (like a bottom navigation bar or navigation drawer), use the new hasRoute() extension function to identify the current destination.

@Serializable data object Home
@Serializable data object Account

data class TopLevelRoute<T : Any>(val route: T, val icon: ImageVector)

val TOP_LEVEL_ROUTES = listOf(
    TopLevelRoute(route = Home, icon = Icons.Default.Home),
    TopLevelRoute(route = Account, icon = Icons.Default.AccountCircle)
)

val currentDestination = navController.currentBackStackEntryAsState().value?.destination

NavigationSuiteScaffold(
    navigationSuiteItems = {
        TOP_LEVEL_ROUTES.forEach { topLevelRoute ->
            item(
                icon = { Icon(topLevelRoute.icon, contentDescription = null) },
                selected = currentDestination?.hierarchy?.any {
                    it.hasRoute(route = topLevelRoute.route::class)
                } == true,
                onClick = { navController.navigate(route = topLevelRoute.route) }
            )
        }
    }
) {
    NavHost(…)
}

8. Best Practices and Debugging Tips

  • Avoid Duplicate Destinations: Use unique route classes for each destination to prevent ambiguity.

  • Handle “null” Strings Carefully: When using String arguments, ensure the value is not the literal “null” to prevent crashes.

  • Keep Routes Small: Avoid using large objects as routes to prevent TransactionTooLargeException. Use a unique ID and fetch the data at the destination if needed.

Conclusion

The new type-safe navigation APIs introduced in Jetpack Navigation 2.8.0, and still the recommended approach in Navigation 2.10, bring improved safety, maintainability, and cleaner code for Android developers using Compose. By leveraging Kotlin’s type system, you can avoid runtime errors, create structured navigation, and enhance the developer experience.

Further Reading

Last updated: Written by: Görkem KARA

What did you think of this post?

Comments 2

  1. altair8800

    The article says this way removes boilerplate, but the migration guide from string paths adds more code. Also, does this way mean we have to sanitize our argument strings for “null” edge cases?

    1. Görkem KARA

      No, declare the variables as null but do not forget to fill them because they come from the serialization class and can be misleading.

Leave a comment

Comments appear after the site owner approves them.

Your comment is published without your name; your email is used only for this comment and never published. Privacy notice

Security check Runs automatically when you send