'How do i pass a bearer authorization token with ApiSauce
Please help check if the method i used to pass the bearer authorization token, because its not working, Maybe im missing something please
apiClient.addAsyncRequestTransform(async (request) => {
const authToken = await authStorage.getToken();
if (!authToken) return;
request.headers["Authorization"] = "access " + authToken;
});
Solution 1:[1]
A bearer token normally starts with the phrase bearer. So, replace the word access with bearer and try again:
apiClient.addAsyncRequestTransform(request => async () => {
const authToken = await authStorage.getToken();
if (!authToken) return;
request.headers["Authorization"] = "Bearer " + authToken;
});
Solution 2:[2]
Here is my Complete Code:
import apisauce from 'apisauce';
import { Constants } from '../utils/Constants';
import LocalStorage from '../Service/LocalStorage'
let local = new LocalStorage()
export const createBackendServer = (baseURL = Constants.BASE_URL) =>
{
const api = apisauce.create({
baseURL,
timeout: 30 * 1000,
});
api.setHeaders({
Accept: 'application/json',
'Content-Type': 'application/json',
})
api.addAsyncRequestTransform(request => async () => {
await local.getSession((res) => {
if (res.token) {
request.headers["Authorization"] = "Bearer " + res.token;
}
})
});
const signUpUser = (body) => api.post('/signup', body);
const signInWithEmailPassword = (body) => api.post('/login', body);
const signOut = () => api.get('/logout');
return {
signUpUser,
signInWithEmailPassword,
signOut
};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Abdul Rehman |


