WKWebView
cookies
iOS development
webview
app cookies

Can I set the cookies to be used by a WKWebView?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Yes, you can set cookies for WKWebView, but success depends on using the right store and setting cookies before the first page load. Many failures come from timing issues, wrong cookie domain values, or mixing persistent and ephemeral data stores. A stable setup uses WKHTTPCookieStore explicitly and treats webview session handling as a first class integration concern.

WKWebView cookie behavior is controlled by these parts:

  • 'WKWebViewConfiguration'
  • 'WKWebsiteDataStore'
  • 'WKHTTPCookieStore'
swift
1import WebKit
2
3let config = WKWebViewConfiguration()
4config.websiteDataStore = .default()
5let store = config.websiteDataStore.httpCookieStore

Pick the data store first, because it determines persistence and sharing behavior.

Set Cookies Before Initial Request

To ensure first request includes cookies, set them and wait for completion before calling load.

swift
1import WebKit
2
3func buildWebView() -> WKWebView {
4    let config = WKWebViewConfiguration()
5    config.websiteDataStore = .default()
6    let webView = WKWebView(frame: .zero, configuration: config)
7
8    let props: [HTTPCookiePropertyKey: Any] = [
9        .domain: "example.com",
10        .path: "/",
11        .name: "session_id",
12        .value: "abc123",
13        .secure: true,
14        .expires: Date().addingTimeInterval(3600)
15    ]
16
17    if let cookie = HTTPCookie(properties: props) {
18        config.websiteDataStore.httpCookieStore.setCookie(cookie) {
19            let url = URL(string: "https://example.com/dashboard")!
20            webView.load(URLRequest(url: url))
21        }
22    }
23
24    return webView
25}

If you call load immediately, first navigation can race ahead without the cookie.

Choose Persistent or Ephemeral Storage Intentionally

Persistent session:

swift
config.websiteDataStore = .default()

Ephemeral session:

swift
config.websiteDataStore = .nonPersistent()

Use ephemeral mode for private or one time sessions that should not survive app restarts.

Share Session Across Multiple WebViews

If two web views must share login state, they need configurations that point to the same website data store.

swift
1let sharedStore = WKWebsiteDataStore.default()
2
3let aConfig = WKWebViewConfiguration()
4aConfig.websiteDataStore = sharedStore
5
6let bConfig = WKWebViewConfiguration()
7bConfig.websiteDataStore = sharedStore

Separate stores mean separate cookie jars.

Read and Delete Cookies for Debugging and Logout

Inspect cookies:

swift
1let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
2cookieStore.getAllCookies { cookies in
3    cookies.forEach { print("\($0.name)=\($0.value)") }
4}

Delete target cookies:

swift
1cookieStore.getAllCookies { cookies in
2    for cookie in cookies where cookie.domain.contains("example.com") {
3        cookieStore.delete(cookie)
4    }
5}

For strict logout, also clear broader website data.

swift
1let dataStore = webView.configuration.websiteDataStore
2let types = WKWebsiteDataStore.allWebsiteDataTypes()
3
4dataStore.fetchDataRecords(ofTypes: types) { records in
5    dataStore.removeData(ofTypes: types, for: records) { }
6}

Syncing App Network Auth to WebView

URLSession and WKWebView cookie behavior can diverge depending on architecture. If your app authenticates via API first, copy required auth cookies into WKHTTPCookieStore before rendering web content.

Treat this as explicit synchronization logic instead of assuming automatic sharing.

Even correctly set client cookies may be ignored if attributes are incompatible with backend policy. Validate:

  • domain and path scope
  • 'Secure use on HTTPS'
  • 'SameSite behavior for your navigation pattern'
  • expiration and renewal timing

Cookie bugs often live at the boundary between client setup and server policy, not in one side alone.

Environment and Domain Parity

Cookie behavior can differ between staging and production if domains, subdomains, or HTTPS settings differ. Keep environments aligned so cookie scope and security attributes are tested under realistic conditions before release.

Review cookie flags and logout behavior during security testing, especially in account-switch scenarios. Session handling defects in embedded web views can create serious cross-user exposure risks.

Common Pitfalls

A common pitfall is setting cookies after first navigation has already started. Then initial requests are unauthenticated.

Another issue is domain mismatch, such as using full host value that does not match request host rules.

Teams also forget to clear all relevant website data on logout, leaving partial session artifacts.

Summary

  • 'WKWebView supports cookie control through WKHTTPCookieStore.'
  • Set cookies before first load and wait for completion callback.
  • Choose .default() or .nonPersistent() data store based on session requirements.
  • Share one data store across web views when session continuity is needed.
  • Implement explicit cookie sync and cleanup logic for reliable auth flows.

Course illustration
Course illustration

All Rights Reserved.