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 Auth token in the request, to identify the user making the request and to confirm that they have successfully authenticated with your app.

Getting the auth token

You can get the current user's Privy Auth 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.

Attaching the auth token to a request

Once you have the current user's Privy Auth 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 */
}
});