Loading headers from SecureStore in apisauce

Viewed 1504

All the endpoints in the backend require Authorization header. This header is stored in SecureStore.

Problem Statement

I want to load the Authorization header ( JWT Token ), for every API call after logging in. Now this requires an async operation i.e.authStorage.getToken.

This is my client.js ( the apisauce client ).

client.js

import { create } from "apisauce";
import authStorage from "../auth/storage";
import IP from "../config/network";

const restoreToken = async () => {
  return await authStorage.getToken("idToken");
};

const apiClient = (auth_token = "") =>
  create({
    baseURL: "http://" + IP + ":8990",
    headers: { Authorization: auth_token }, // This I've added later
  });

export default apiClient;

This is the PostsApi which uses apiClient to make the calls.

PostsApi.js

import apiClient from "./client";

const endpoint = "/api/";
const bookmarkEndpoint = "/bookmark/";
const getPosts = (last_id = 0, limit = 10) => {
  return apiClient.get(endpoint + "?last_id=" + last_id + "&limit=" + limit);
};

const toggleBookmark = (item_id) => {
  return apiClient.get(bookmarkEndpoint + "?item_id=" + item_id);
};

export default {
  getPosts,
  toggleBookmark,
};

My Understanding

I understand that if I can add the header in client.js itself, it would be injected everytime there's an API call. I've tried :

const restoreToken = async () => {
  return await authStorage.getToken("idToken");
};

But I am not sure how to call this async operation in client.js

Bonus Question

This token ( idToken ) would be reloaded every hour, so it's best to get the token from SecureStore everytime instead of saving it once.

Thanks.

Accepted answer and what worked for me

Worked for me apisauce's setHeader : Documented here

Accepted answer is a detailed drilling of the axios setting up of headers. So if someone's using axios client directly they can see the accepted answer else, if you're an apisauce user, use the setHeader functionality provided with the library.

Cheers.

1 Answers
  1. You will have to store your token with the state (can be redux or local state).
  2. During save/refresh/reload the token, you will have set headers of the HTTP client.

You can set header using below command (example)

export const setAuthToken = (token) => {
  apiClient.defaults.headers.common['Authorization'] = ''
  delete apiClient.defaults.headers.common['Authorization']

  if (token) {
    apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`
  }
}

Call the above function to set a token during reload/refresh/creation of token.

const restoreToken = async () => {
  return await authStorage.getToken("idToken").then(token =>  setAuthToken(token));
};
Related