Skip to main content

Validating tokens

When your backend receives a request, you may want to check if the request originated from an authenticated user of your app (as part of your API middleware, or otherwise). A common pattern for doing this is to verify the authorization headers on incoming requests against the Privy public key for your app.

To authorize a request received by your backend, you should first extract the auth token from the incoming request. For example, in NextJS, you might extract the auth token from a NextApiRequest as follows:

const authToken = await (req.headers.authorization).replace('Bearer ', '')

Then, you should pass the auth token from the request to Privy's verifyAuthToken method, which will verify the token against the Privy public key for your app.

Example Token Verification using Privy
// In this example, the variable 'privy' refers to your instance of the PrivyClient.
try {
const verifiedClaims = await privy.verifyAuthToken(authToken);
} catch (error) {
console.log(`Token verification failed with error ${error}.`)
}

If the token is valid, verifyAuthToken will return an AuthTokenClaims object (verifiedClaims in the code example above) with additional information about the request. For example, you might use verifiedClaims.userId to get the Privy DID for the user who made the request.

If the token is invalid, verifyAuthToken will throw an error and you should not treat the request as authorized. This generally only occurs if the token has expired or has an invalid signature (e.g. one that corresponds to a different Privy App ID).