Skip to main content

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.

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:

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 */