ID Token
This page covers how you can subscribe and listen to the users ID Token and use it throughout your application.
Subscribing to the ID Token
If you require the users ID Token (e.g. for making external API requests), the useAuthIdToken
provides a simple way to subscribe to latest token.
import { useAuthIdToken } from "@react-query-firebase/auth";
import { auth } from "./firebase";
function App() {
const tokenResult = useAuthIdToken(["token"], auth);
if (tokenResult.isLoading) {
return <div />;
}
if (tokenResult.data) {
return <div>ID Token: {user.data.token}!</div>;
}
return <div>Not signed in.</div>;
}
Anytime your users state changes or the ID Token is refreshed, the hook will update either returning null
(if there is no authenticated user) or an IDTokenResult
containing your token and metadata to go with it.
Force Refreshing
By default, if the ID Token has not yet expired the same one will be returned. You can override this behaviour
by providing the forceRefresh
flag to the hook options:
const tokenResult = useAuthIdToken(["token"], auth, {
forceRefresh: true,
});
Each time the query runs, your token will be fetched and update no matter the expiration time.
Using the token
Displaying the token isn't really that useful. Instead we're more likely to use it when performing API requests. Luckily React Query makes it easy to get the data of a query outside of the scope of a component, or within an extracted hook.
Imagine we've got a custom useApiRequest
hook within our application, using the same Query Key we can get the
token before the request and attach it to the API request.
import { useQueryClient, useQuery } from "react-query";
function useApiRequest(url) {
const client = useQueryClient();
return useQuery(url, () => {
return fetch(url, {
headers: new Headers({
"X-ID-Token": client.getQueryData("token")?.token ?? "",
}),
});
});
}
If the Query Key has a IDTokenResult
stored, we'll extract the token from it and pass it as a header.
Returning the token
Sometimes you just want the actual ID Token, rather than the full IDTokenResult
. Luckily React Query
makes this simple by providing a data selector:
useAuthIdToken(["token"], auth, {
select(result) {
if (result) {
return result.token;
} else {
return "";
}
},
});
Now the Query Key token
will always ensure a string is value is returned.
React Query options
The hook also allows us to provide React Query options, supporting all of the options the
useQuery
supports! For example, we could handle
side effects with ease:
useAuthIdToken(["token"], auth, {
onSuccess(result) {
if (result) {
localStorage.setItem("token", result.token);
} else {
localStorage.removeItem("token");
}
},
});