react-nativecookieswebview

Are cookies set in react-native-webview automatically reflected in react-native?


I’m building an app with React Native and using react-native-webview. The WebView loads a web app I built with React.

When the WebView logs in to API server, the server responds with a Set-Cookie header containing a token. That part makes sense.

But here’s the strange part: Today at work, after logging in through the WebView, I tried calling another API from the React Native side(not in webview) using axios or fetch without setting any headers manually

When I checked the server logs, the token cookie was automatically included in the request. However, in the React Native code, if I inspect the request (axios.response.config.headers), I don’t see any Cookie field in the headers.

This is very confusing. Logically, the cookies from a WebView login should be stored only inside the WebView/browser. Why are they being sent along with my React Native fetch calls when I didn’t configure anything?

So my questions are:

Is this an intended behavior?

Why does React Native share WebView cookies automatically?

To reproduce, I created a sample project, and the same behavior occurs. Please check my repo below. (https://github.com/veursk/react-native-webview-cookie_test)

Notes:

I tested this on Android. I'll check iOS

If I enable incognito mode (I think it’s like private browsing), then the cookies are not shared with React Native fetch requests.

Does it make sense that WebView and native code are sharing cookies?

"react-native": "0.72.6", "react-native-webview": "^13.6.4"


Solution

  • On Android this is mostly expected. Here both react-native-webview and React Native’s fetch/axios use the same system cookie store which is CookieManager. When your WebView logs in and then server sets a cookie that then goes into the shared store and afterwards fetch or axios call will automatically include it.

    So that is why you see the cookie on the server side but not in axios.config.headers , axios only shows the headers you set yourself manually.. while the Android native network stack adds cookies automatically in background.

    On iOS it kinda works differently here WKWebView and NSURLSession don’t share cookies by default. If you want the same behavior here then you will need to sync them manually like for example using react-native-cookies .

    If you enable incognito mode in WebView, it uses an isolated cookie jar, so nothing is shared with native requests.