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
npx expo install expo-secure-storeProgramming 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.jsSource code viewer
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
/**
* Save the token to the store.
* @param {string} token - The token to save.
*/
export async function saveToken(token) {
if (Platform.OS === 'web') {
// Set the cookie in the browser
// We use the Secure flag to enable HTTPS only
// We use the SameSite flag to prevent CSRF
document.cookie = `jwt_token=${token}; path=/; Secure; SameSite=Strict`;
} else {
// Save the token to the secure store
await SecureStore.setItemAsync('jwt_token', token);
}
}
/**
* Get the token from the store.
* @returns {Promise<string|null>} The token or null if it is not set.
*/
export async function getToken() {
if (Platform.OS === 'web') {
// Get the cookies from the document
const cookies = document.cookie.split('; ').reduce((acc, cookie) => {
// Split the cookie into key and value
const [key, value] = cookie.split('=');
// Add the key and value to the accumulator
acc[key] = value;
return acc;
}, {});
// Return the token or null if it is not set
return cookies.jwt_token || null;
} else {
// Get the token from the secure store
return await SecureStore.getItemAsync('jwt_token');
}
}
/**
* Delete the token from the store.
* If we are on the web, this sets the cookie to expire in the past.
* If we are on mobile, this deletes the item from the secure store.
*/
export async function deleteToken() {
if (Platform.OS === 'web') {
// Set the cookie to expire in the past
document.cookie = 'jwt_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
} else {
// Delete the item from the secure store
await SecureStore.deleteItemAsync('jwt_token');
}
}Programming Language: ECMAScript
How to Use It
Source code viewer
// Storing a JWT:
await saveToken('your_jwt_token_here');
// Retrieving the JWT:
const token = await getToken();
console.log('JWT Token:', token);
// Deleting the JWT:
await deleteToken();Programming Language: ECMAScript