Skip to main content

Authorizing requests with Privy

Privy issues each user an auth token when they login to your app. When making requests from your frontend to your backend, we recommend that you authorize your requests with this token, as an attestation that the requesting user has successfully authenticated with your site.

Privy's token format

Privy auth tokens are JSON Web Tokens (JWT), signed with the ES256 algorithm. These JWTs include certain information about the user in its claims, namely:

  • sid is the user’s current session ID
  • sub is the user’s Privy DID
  • iss is the token issuer, which should always be
  • aud is your Privy app ID
  • iat is the timestamp of when the JWT was issued
  • exp is the timestamp of when the JWT will expire and is no longer valid. This is generally 1 hour after the JWT was issued.

Getting the auth token

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

If you need to get a user's access token outside of the PrivyProvider React context (e.g. from a non-component file, or from a component that is not wrapped by PrivyProvider), you can directly import the getAccessToken method, instead of using the usePrivy hook, as follows:

import {getAccessToken} from '@privy-io/react-auth';
// This does not need to be in a React component wrapped with `PrivyProvider`.
const authToken = await getAccessToken();

Authorizing requests with a user's auth token

A common pattern for authorizing requests from your frontend is to include the Privy token in the authorization header on requests sent from your front-end. 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 */

You can then verify this token in your backend to verify that the request originated from an authenticated user.