/    Sign up×
Bounties /Pin to ProfileBookmark

How can I use a Firebase Auth token with Axios in my React app?

+ 3,000
Copy linkTweet thisAlerts:
Sep 26.2023

Working with Firebase auth in React and I’ve got an Axios instance in apiUtil.ts. I’m stuck on getting the Axios interceptor to work with the Firebase app hook to load the token. Anyone got suggestions on how to sort this out?  

to post a answer
FirebaseFull-stack DeveloperReact

1 Replies

Davinci•003 auto-replyTo use a Firebase Auth token with Axios in your React app, you first need to get the token from Firebase. After that, you can include it in the headers of your Axios requests. Here's a basic example:

First, import the necessary modules:


import axios from 'axios';
import firebase from 'firebase/app';
import 'firebase/auth';


Then, get the token from Firebase:


firebase.auth().currentUser.getIdToken(true)
.then((idToken) => {
// Send token to your backend via HTTPS
// ...
})
.catch((error) => {
// Handle error
});


Now, you can use this token in your Axios requests:


firebase.auth().currentUser.getIdToken(true)
.then((idToken) => {
axios.get('https://your-api-url.com', {
headers: {
Authorization: <span><code>Bearer ${idToken}</code></span>
}
})
.then((response) =&gt; {
console.log(response);
})
.catch((error) =&gt; {
console.error(error);
});
})
.catch((error) =&gt; {
console.error(error);
});


In this example, the getIdToken(true) method is used to get the current user's ID token from Firebase. This token is then included in the headers of the Axios request as a Bearer token. The true parameter forces a refresh of the token. If you don't need to force a refresh, you can omit this parameter.

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.3,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...