Skip to content

Mocking Privy tokens for tests

If your project uses automated testing (e.g. with Jest), your test setup may need access to a Privy token in order to mock out an authenticated session, authorized API calls, and more.

To obtain a Privy token for tests, we do not recommend using an actual auth token issued by Privy's production service. Rather, you should construct a test JWT in the Privy format and then sign it with a key that you control.


At a high-level, the instructions for creating and signing a JWT in the Privy format are:

  1. Generate your signing & verification keys for tests. Privy uses an asymmetric ECDSA P256 keypair, but you can choose any key setup you like.
  2. Construct a JWT with the Privy claims. For tests, you can use any arbitrary Privy DID for the sub claim and any arbitrary session ID for the sid claim.
  3. Sign your JWT with your signing key. Privy uses the ES256 algorithm to sign & verify JWTs for your app, but you can choose any signing algorithm you like, as long as it is compatible with your key setup from Step 1.

Below is a reference implementation in JavaScript for generating keys, signing JWTs in the Privy format, and verifying those JWTs using the library jose.

Generating signing & verification keys for tests

Generate a keypair using jose's generateKeyPair method, specifying the 'ES256' algorithm as a parameter.

const {publicKey, privateKey} = await jose.generateKeyPair('ES256');

You can now use the privateKey to sign JWTs and the publicKey to verify JWTs in your tests.

Creating and signing test JWTs

First, define the values you will use to populate your test JWT's claims.

const session = /* an arbitrary session ID */
const subject = /* an arbitrary Privy DID */
const issuer = '';
const audience = /* your Privy app ID */
const expiration = '1h';

Next, create and sign your test JWT with your test privateKey using jose's SignJWT class.

const authToken = await new jose.SignJWT({sid: session})
  .setProtectedHeader({alg: 'ES256', typ: 'JWT'})

Verifying test JWTs

Use jose's jwtVerify method to verify your test JWT against your test publicKey

try {
	const payload = await jose.jwtVerify(authToken, verificationKey, {
		issuer: '',
		audience: /* your Privy App ID */
} catch (error) {
	console.log(`JWT failed to verify with error ${error}.`);