I'm making an app using Expo that has session cookie authentication. The backend is express sessions.
When a user sucessfully signs in, I store the token that's given by the server in Async storage on the device. When the user logs out or checkAuth
fails for some reason (for example if the session has expired) I clear the token from Async storage and set the state to not authenticated. All this works good and seems to be robust.
Now I have encountered what might be a problem. For all other requests that aren't related to logging in or checking auth, I also need to send the token to server for authorization. For example when logging out.
I use Axios and need a way to attach the token that's currently stored in Async storage to the request. I have a custom Axios instance that's used in all requests. I'm thinking I could attach the token through that instance? Something like this:
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const getStoredSessionID = async () => { // this function gets the auth token from storage
try {
const value = await AsyncStorage.getItem('local_sid');
return value;
} catch (e) {
alert("Async storage error")
}
};
const axiosInstance = axios.create({
baseURL: 'http://192.168.0.6:3002',
timeout: 4000,
headers: {'Cookie': `user_sid=${getStoredSessionID}`}
});
export default axiosInstance;
Does the code above make sense at all? Or is there maybe a better way? Please let me know if this is vague or if more information is needed. BIG thanks for any input!
The code above did not work as intended.