Skip to main content

Granting access to your users

When using the privy-browser client, your users interact directly with Privy. In order for Privy identify your users, you can issue access tokens to your users from your backend. An access token is a JWT that is used to authenticate requests to Privy to access data, i.e. via privy.get().

note

Privy's access token API must be called from your backend.

Because authentication gives users direct access to data, access tokens have to be generated server-side and securely passed to your user's browser. This means you must run a backend to issue access tokens yourself.

If your app does not have a backend, consider integrating Privy with your user's wallet instead.

Generating access tokens on your backend and issuing to the frontend

Privy access tokens are JSON Web Tokens (JWTs). They can be generated by calling the createAccessToken() method in privy-node.

If using privy-browser in the frontend, the backend must provide a way to get an access token. Typically, this would be a protected API route. For example, in Next.js, you would create a file tokens.tsx in the api folder and hook it up to a route in your backend e.g. /api/privy/tokens.

import {PrivyClient} from '@privy-io/privy-node';
const client = new PrivyClient(process.env.PRIVY_API_KEY, process.env.PRIVY_API_SECRET);

// Handler for your backend `/api/privy/tokens` endpoint.
export default async function handler(req: NextApiRequest, res: NextApiResponse<{token: string}>) {
// ...
// Your auth system verifies the logged in user.
// ...
const token = await client.createAccessToken(req.user.id);

res.status(200).json({token});
}

Now use privy-browser in your frontend to fetch an access token from your backend.

Initialize the PrivyClient with a CustomSession object and implement the authenticate function. The authenticate function calls the backend API route that issues Privy tokens.

Using the example API route from above, this might look like:

import axios from 'axios';
import {PrivyClient, CustomSession} from '@privy-io/privy-browser';

// This can be any async function that returns a valid Privy access token
const authenticate = async () => {
const response = await axios.post<{token: string}>('/api/privy/tokens');
return response.data.token;
};

const client = new PrivyClient({
session: new CustomSession(authenticate),
});
note

Tokens expire every 10 minutes. When the token expires, the session will automatically call the authenticate function again.