Authorizing requests from your frontend
When your frontend makes a request to your backend, you should include the current user's Privy token in the request. This allows your backend identify the user making the request and to confirm that they have successfully authenticated with your app.
Make sure to follow the appropriate instructions below, depending on if your app uses local storage or cookies.
- Using local storage
- Using cookies
You can get the current user's Privy token as a string using the getAccessToken
method from the usePrivy
hook.
const { getAccessToken } = usePrivy();
const authToken = await getAccessToken();
For a user who is authenticated, getAccessToken
returns a Promise on valid auth token for the user. The method will automatically refresh the user's auth token if the token is expired or is close to expiring. For a user who is not authenticated, getAccessToken
returns null
.
Need to get a user's auth token from outside Privy's React context? See this!
If you need to get a user's Privy token outside of Privy's React context, you can directly import the getAccessToken
method, instead of using the usePrivy
hook, like below:
import {getAccessToken} from '@privy-io/react-auth';
...
const authToken = await getAccessToken();
Note that:
- You should only import
getAccessToken
as above in special cases. Generally, this is only necessary if callinggetAccessToken
from a non-component file, or from a component that has not been wrapped byPrivyProvider
. In most other cases, you should retrievegetAccessToken
from theusePrivy
hook. - If you directly import the
getAccessToken
method, make sure that you do not invoke the method beforePrivyProvider
has rendered.
Once you have the current user's Privy token, you can then include the token in your request's authorization header.
For example, on a fetch request, you might include the user's auth token as follows:
const authToken = await getAccessToken();
const response = await fetch(<your-api-route>, {
method: <your-request-method>
body: <your-request-body>,
headers: {
'Authorization': `Bearer ${authToken}`,
/* Add any other request headers you'd like */
}
});
There is nothing you need to do to include the user's auth token on a request sent from your frontend to your backend.
Since the user's auth token is stored in a first-party cookie, the browser will automatically include the cookie in requests sent to your backend. You're good to go!