1 March 2025

This solution is designed specifically for Expo because it uses expo-secure-store. Using SecureStore on mobile and cookies for better security on web.

Install expo-secure-store

Source code viewer
  1. npx expo install expo-secure-store
Programming Language: ECMAScript

Create a helper for Storing Tokens

Create a helper or utility file for the read and write functions. For an example: /helpers/jwt.js
Source code viewer
  1. import * as SecureStore from 'expo-secure-store';
  2. import { Platform } from 'react-native';
  3.  
  4. /**
  5.  * Save the token to the store.
  6.  * @param {string} token - The token to save.
  7.  */
  8. export async function saveToken(token) {
  9. if (Platform.OS === 'web') {
  10. // Set the cookie in the browser
  11. // We use the Secure flag to enable HTTPS only
  12. // We use the SameSite flag to prevent CSRF
  13. document.cookie = `jwt_token=${token}; path=/; Secure; SameSite=Strict`;
  14. } else {
  15. // Save the token to the secure store
  16. await SecureStore.setItemAsync('jwt_token', token);
  17. }
  18. }
  19.  
  20. /**
  21.  * Get the token from the store.
  22.  * @returns {Promise<string|null>} The token or null if it is not set.
  23.  */
  24. export async function getToken() {
  25. if (Platform.OS === 'web') {
  26. // Get the cookies from the document
  27. const cookies = document.cookie.split('; ').reduce((acc, cookie) => {
  28. // Split the cookie into key and value
  29. const [key, value] = cookie.split('=');
  30. // Add the key and value to the accumulator
  31. acc[key] = value;
  32. return acc;
  33. }, {});
  34. // Return the token or null if it is not set
  35. return cookies.jwt_token || null;
  36. } else {
  37. // Get the token from the secure store
  38. return await SecureStore.getItemAsync('jwt_token');
  39. }
  40. }
  41.  
  42. /**
  43.  * Delete the token from the store.
  44.  * If we are on the web, this sets the cookie to expire in the past.
  45.  * If we are on mobile, this deletes the item from the secure store.
  46.  */
  47. export async function deleteToken() {
  48. if (Platform.OS === 'web') {
  49. // Set the cookie to expire in the past
  50. document.cookie = 'jwt_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
  51. } else {
  52. // Delete the item from the secure store
  53. await SecureStore.deleteItemAsync('jwt_token');
  54. }
  55. }
Programming Language: ECMAScript

How to Use It

Source code viewer
  1. // Storing a JWT:
  2. await saveToken('your_jwt_token_here');
  3.  
  4. // Retrieving the JWT:
  5. const token = await getToken();
  6. console.log('JWT Token:', token);
  7.  
  8. // Deleting the JWT:
  9. await deleteToken();
Programming Language: ECMAScript