How to persist navigation state in SwiftUI
Learn how to save and restore NavigationPath to maintain user context across app launches.
21 Apr 2025 · 4 min read
When building multi-screen apps in SwiftUI, preserving where a user left off can improve the user experience. One of the key advantages of SwiftUI's NavigationPath is that it's serializable. As long as all data types in the path conform to Codable, we can save and restore the navigation state.
This allows us to persist the navigation stack across app launches or even sync state between devices.
Let's look at how to do that.

Making our routes codable
To persist a NavigationPath, every element that goes into it must conform to both Hashable and Codable. If, for example, we used a router based approach to work with NavigationPath, it can look as follows:
enum Route: Hashable, Codable {case searchcase detail(id: String)}
Encoding and storing navigation state
Once the route type is Codable, we can encode the navigation path and store it using a persistence mechanism such as UserDefaults or the file system.
For example:
// Encode navigation pathif let encodedPath = try? JSONEncoder().encode(navigationPath) {UserDefaults.standard.set(encodedPath, forKey: "savedNavigation")}
For larger or sensitive data, we could use the file system or Keychain instead.
Restoring the navigation stack
To restore navigation, we can retrieve the encoded path and decode it back into a NavigationPath:
if let data = UserDefaults.standard.data(forKey: "savedNavigation"),let decodedPath = try? JSONDecoder().decode(NavigationPath.self, from: data) {navigationPath = decodedPath}
We can perform this restoration early in the app lifecycle, for example when initializing a router.
Limitations to keep in mind
While persisting navigation state can be powerful, there are a few important things to consider. First, only types that conform to Codable can be stored in a NavigationPath.
Second, our route definitions must remain stable over time. If we modify the structure of a route, for example by adding or removing enum cases, previously saved navigation data may no longer decode properly.
Finally, we should be mindful of what data we include in our routes. Associated values should be lightweight and safe to persist, especially if using mechanisms like UserDefaults for persistence.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



