Reputation: 190
I'm currently working on a Next.js (React) project, where I use Firebase Auth for authentication. I use this to connect to a REST API back-end, which receives the user token Firebase provides (via getIdToken()
).
Because the IdToken changes every now and then, I'm currently reqesting the latest IdToken before sending a fetch
request like this:
const fetcher = (url: string) => {
return user.getIdToken().then((token) =>
fetch(url, {
method: "GET",
headers: new Headers({
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
}),
}).then((res) => res.json())
);
};
This setup actually works, but I was wondering if it's considered efficient/best-practice? I see a lot of examples out there where the IdToken is used to set a cookie (eg. firebase docs, next.js example).
I could see why when using SSR, since getIdToken()
can't be called there. But my application only uses client-side data fetching. Would there be any benefits for me moving away from my current approach to using cookies?
Upvotes: 7
Views: 4962
Reputation: 501
Set the Auth Token in a cookie or local storage:
After obtaining the Auth token during authentication, you can store it in a cookie or local storage. Using a cookie is preferable when you need to send the Auth token with server-side rendered (SSR) requests, and local storage is a good option for client-side-only applications.
Here's an example of setting the Auth token in a cookie:
import Cookies from 'js-cookie';
// ...
useEffect(() => {
const fetchUserData = async () => {
try {
const user = firebase.auth().currentUser;
if (user) {
// Get the Auth token
const token = await user.getIdToken();
// Set the Auth token in a cookie
Cookies.set('authToken', token);
// Make the API request with the Auth token in the headers
// Your fetch code here
}
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchUserData();
}, []);
Upvotes: 0
Reputation: 599041
The Firebase Authentication SDK already caches the token in local storage, so there's no need for you to cache it elsewhere again.
In fact, the token is refreshed every hour, and the Firebase Authentication SDK refreshes it automatically in the background. If you cache the token yourself, you might end up using an outdated token.
So I'd recommend always calling getIdToken()
when you need the ID token. Of course it's fine to store it in a variable, and use that in a single code block (code that runs at pretty much the same time).
Using a cookie to pass the token to your server is fine, as is using the Authorization
header as you do now. The latter is more common, but a cookie works too.
Upvotes: 13