Integrating with tRPC
tRPC is an end-to-end typesafe API built in Typescript. This guide shows how to integrate Privy into any tRPC application.
There are two steps to enable auth in tRPC with Privy:
- in your client, include the user’s access token on requests
- in your server, secure procedures by validating the token included on requests
If you’re using tRPC with zod, check out this transformation tool to automatically generate zod schemas from Privy’s types (e.g. user.email
).
Configuring your client
When your client (frontend) makes a request to one of your tRPC procedures, you should include the Privy auth token, so that your server can verify that the user is authenticated.
The following works for both createTRPCProxyClient
(vanilla) or createTRPCNextClient
(Next.js). Note that while the configuration method signature is different between the two, the inner configuration object/strategy will remain the same. The example shown is for NextJS.
When scaffolding the tRPC client, pass the Privy auth token through the header of every request, via an httpBatchLink
within the links
configuration. Below is an example:
Protecting routes on your server
When your server receives a request from the client, it should validate the Privy auth token to confirm included in the request to ensure that it is authenticated.
First, parse the passed token using jose where you create your tRPC context:
Next, create a middleware procedure for protecting routes:
Finally, when defining routes, you can use your procedure middleware to ensure the user is properly authenticated.
Was this page helpful?