r-iliass
r-iliass

Reputation: 21

How can I persist auth state in a nodejs app

So, I am learning NodeJs by creating this backend that fetches some data from a third-party API, the API requires auth. I couldn't figure out how to avoid sending an auth request to the third-party API whenever I wanted to fetch data from it. is there any way I could store the auth state in the app?

const axios = require("axios");

const AUTH_URL = process.env.AUTH_URL;
const REPORT_BASE_URL = process.env.REPORT_BASE_URL;
const X_API_KEY = process.env.X_API_KEY;

const getCompanies = async (req, res) => {
    let idToken;

    // auth
    const authPayload = JSON.stringify({
        // ...
    });

    const config = {
        method: "post",
        // ...
    };

    try {
        const { data } = await axios(config);
        idToken = data.idToken; // set idToken necessary for fetching companies
    } catch (error) {
        console.log(error);
    }

    // get company by full text query
    const { full_text_query } = req.query;

    if (!full_text_query)
        return res.send("No full_text_query parameter provided");

    try {
        const { data } = await axios.get(
            `${REPORT_BASE_URL}/companies?full_text_query=${full_text_query}`,
            {
                headers: {
                    "x-api-key": X_API_KEY,
                    Accept: "application/json",
                    authorization: idToken,
                },
            }
        );

        res.status(200).json(data);
    } catch (error) {
        console.log(error);
    }
};

module.exports = {
    getCompanies,
};

Upvotes: 2

Views: 79

Answers (1)

klhr
klhr

Reputation: 3390

You can break out a function like fetchIdToken and store a Promise that resolves with the idToken in memory.

let idTokenPromise;
async function fetchIdToken () {
  if (idTokenPromise) return idTokenPromise;
  return idTokenPromise = new Promise(async (resolve) => {
    ...
    resolve(data.idToken);
  })
}

You can then use await fetchIdToken() at the start of getCompanies.

You can also just store the idToken in memory. This is slightly simpler, but does mean that you can have a race-condition when multiple getCompanies requests happen at the same time:

let idToken;
async function fetchIdToken () {
  if (idToken) return idToken;

  ...
  idToken = data.idToken;
  return idToken;
}

Upvotes: 1

Related Questions