Cookie Management in React Native

JP Wallhorn
Syntx — News, Blog & Insights
2 min readApr 18, 2019

Cookie Management in React Native

Cookies, not the yummy chocolate ones but the old way to authenticate users, are still heavily used. Unfortunately, React Native has some trouble when it comes to native cookie management.

Normally you can easily add:

{ withCredentials: true }

This automatically adds the cookie to each request and you technically don’t have to worry about anything. As mentioned above, this doesn’t work 100% of the time to React Native.

Furthermore, you might want to use the cookie value and persist in localStorage meaning the actual device.

That by itself can be easily archived be accessing the Header values when requesting the cookie and storing that Cookie. From here, you just have to add the Cookie to the Header when making a request that requires the Cookie value:

{ Headers: { Cookie: "CookieValue" } }

After a while and making various requests back and forth you might notice some inconsistent behavior here too. The reason for that is the Network Handler. It might request a new Cookie and it will conflict with the Cookie you are manually setting. We have tried various ways to block/avoid this behavior but nothing has helped.

We ended up with the following solution: We clear the cookies manually after each request to make sure the RTCNetworking module doesn’t store any Cookies without our knowledge:

const RCTNetworking = require('RCTNetworking'); export default function clearCookies() { return new Promise(success => { RCTNetworking.clearCookies(success); }); }

Last but not least, you might leverage native web views. If you do, you have to make sure to clear those cookies manually as well because the cookie management in the native environment (I.e. iOS) is separate from the cookie management in JavaScript.

let cookieStorage = HTTPCookieStorage.shared if let cookies = cookieStorage.cookies { let tedCookies = cookies.filter{ $0.domain.contains("domain.com") } for cookie in tedCookies { cookieStorage.deleteCookie(cookie) } }

By manually clearing the cookies you can be 100% sure that no other cookies will interfere with your manual management.

Btw. This method doesn’t require you to use any 3rd party cookie management libraries.

Originally published at https://www.syntx.io on April 18, 2019.

--

--