Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Session cookies can be managed in React Native using the 'react-native-cookies' library.

  1. Install the 'react-native-cookies' library using npm:

    npm install react-native-cookies

  2. Import the library in your React Native component:

    import CookieManager from 'react-native-cookies';

  3. To set a session cookie, use the 'set' method of CookieManager:

    CookieManager.set({
      name: 'session_id',
      value: '123456',
      domain: 'example.com',
      origin: 'https://example.com',
      path: '/',
      version: '1',
      expiration: '2022-12-31T12:00:00.000Z',
      secure: true,
      httpOnly: true,
    })
    

    Here, 'name' and 'value' are mandatory fields. 'domain', 'origin, 'path', and 'version' can be set according to your needs. 'expiration' sets the expiry date of the cookie. 'secure' and 'httpOnly' ensure that the cookie is secure and cannot be accessed by client-side Javascript.

  4. To get a session cookie, use the 'get' method of CookieManager:

    CookieManager.get('session_id')
      .then((cookie) => {
         // Do something with the cookie
      })
      .catch((error) => {
         console.log(error);
      })
    

    Here, the parameter is the name of the cookie to be retrieved. The 'then' method returns the cookie as an object, which can be accessed for further processing.

  5. To delete a session cookie, use the 'clearAll' method of CookieManager:

    CookieManager.clearAll()
      .then((success) => {
         console.log('All cookies deleted');
      })
      .catch((error) => {
         console.log(error);
      })
    

    This method deletes all cookies stored in the application.

By using these methods, you can manage session cookies in your React Native app.