Appearance
Documentation / server-auth / PrivyClient
Class: PrivyClient
The Privy client performs operations against the Privy API.
typescript
import {PrivyClient} from '@privy-io/server-auth';
Constructors
new PrivyClient(appId, appSecret, options)
new PrivyClient(
appId
,appSecret
,options
):PrivyClient
Creates a new Privy client.
Parameters
• appId: string
The app id from your console.
• appSecret: string
The app secret, only visible once on app creation in the console.
• options: Object
= {}
Initialization options.
• options.apiURL?: string
The URL of the Privy API. Defaults to https://auth.privy.io
.
• options.timeout?: number
Time in milliseconds after which to timeout requests to the API. Defaults to 10000
(10 seconds).
• options.walletApi?: Object
Configuration for Privy's wallet API.
• options.walletApi.apiURL?: string
The URL of the wallets API. Defaults to https://api.privy.io
.
• options.walletApi.authorizationPrivateKey?: string
Private key for your app's authorization keypair.
If your app has an authorization keypair registered in the Privy Dashboard, you must pass the corresponding private key here, otherwise wallet RPC requests will fail.
Returns
Properties
api
private
api:Http
appId
private
appId:string
verificationKey
private
verificationKey:null
|string
=null
walletApi
walletApi:
WalletApi
Methods
createWallets()
createWallets(
__namedParameters
):Promise
<User
>
Create embedded and smart wallets for an existing user on Privy.
typescript
const user = await client.createWallets({
createEthereumWallet: true,
createSolanaWallet: false,
createEthereumSmartWallet: true,
numberOfEthereumWalletsToCreate: 2
});
Parameters
• __namedParameters: CreateWalletInput
Returns
Promise
<User
>
deleteUser()
deleteUser(
userId
):Promise
<void
>
Delete the user object associated with the given user DID (decentralized ID).
typescript
const user = await client.deleteUser("did:privy:XXXXX");
Parameters
• userId: string
The Privy DID of the user.
Returns
Promise
<void
>
getAllowlist()
getAllowlist():
Promise
<AllowlistEntry
[]>
Get the allowlist entries for a the given app. This is a list of users that are allowed to access the app, if the allowlist is enabled.
typescript
const allowlist = await client.getAllowlist();
Returns
Promise
<AllowlistEntry
[]>
a list of AllowlistEntry objects.
getAppSettings()
getAppSettings():
Promise
<AppSettings
>
Get the app settings associated with the given app.
Returns
Promise
<AppSettings
>
the AppSettings
getTestAccessToken()
getTestAccessToken():
Promise
<Object
>
Get an access token for the test account for your app. Will throw an error if you have not enabled test credentials in the dashboard. Will throw an error if allowed origins or base domain are enabled for the app.
Returns
Promise
<Object
>
accessToken
accessToken:
string
=authenticateResponse.data.token
getUser()
getUser(props)
getUser(
props
):Promise
<User
>
Gets a user from the identity token. First, this verifies the token is valid and then parses the payload into a User
object. Note the user object may be incomplete due to identity token size constraints
typescript
const idToken = req.cookies.get('privy-id-token'); // or however your framework surfaces cookies
const user = await client.getUser({idToken});
Parameters
• props: Object
• props.idToken: string
the identity token set as a cookie on the users browser
Returns
Promise
<User
>
the user object with parsed from the ID token
getUser(userId)
getUser(
userId
):Promise
<User
>
Parameters
• userId: string
The Privy DID of the user.
Returns
Promise
<User
>
A User if the user exists.
Deprecated
For performance reasons, we recommend getUser({idToken: string}) to avoid rate limits as your app scales.
Get the user object associated with the given user DID (decentralized ID).
typescript
const user = await client.getUser("did:privy:XXXXX");
getUserByCustomAuthId()
getUserByCustomAuthId(
customUserId
):Promise
<null
|User
>
Gets a user object by their custom JWT auth ID, which is scoped to an individual app.
typescript
const user = await client.getUserByCustomAuthId(customUserId);
Parameters
• customUserId: string
The custom identifier of the user defined by their JWT
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByDiscordUsername()
getUserByDiscordUsername(
username
):Promise
<null
|User
>
Get the user object associated with a Discord username.
typescript
const user = await client.getUserByDiscordUsername(username);
Parameters
• username: string
Discord username to search for
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByEmail()
getUserByEmail(
address
):Promise
<null
|User
>
Get the user object associated with an email address.
typescript
const user = await client.getUserByEmail(emailAddress);
Parameters
• address: string
The email address of the user to find.
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByFarcasterId()
getUserByFarcasterId(
fid
):Promise
<null
|User
>
Get the user object associated with a farcaster ID.
typescript
const user = await client.getUserByFarcasterId(fid);
Parameters
• fid: number
The farcaster ID (a number).
Returns
Promise
<null
| User
>
A User if the user exists.
getUserById()
getUserById(
userId
):Promise
<User
>
Parameters
• userId: string
Returns
Promise
<User
>
getUserByPhoneNumber()
getUserByPhoneNumber(
number
):Promise
<null
|User
>
Get the user object associated with a phone number.
typescript
const user = await client.getUserByPhoneNumber(number);
Parameters
• number: string
The phone number of the user to find.
Returns
Promise
<null
| User
>
A User if the user exists.
getUserBySmartWalletAddress()
getUserBySmartWalletAddress(
walletAddress
):Promise
<null
|User
>
Get the user object associated with a smart wallet address.
typescript
const user = await client.getUserBySmartWalletAddress(walletAddress);
Parameters
• walletAddress: string
The smart wallet address of the user to find.
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByTelegramUserId()
getUserByTelegramUserId(
telegramUserId
):Promise
<null
|User
>
Get the user object associated with a telegram user ID.
typescript
const user = await client.getUserByTelegramUserId(telegramUserId);
Parameters
• telegramUserId: string
Telegram user ID to search for
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByTelegramUsername()
getUserByTelegramUsername(
username
):Promise
<null
|User
>
Get the user object associated with a telegram username.
typescript
const user = await client.getUserByTelegramUsername(telegramUsername);
Parameters
• username: string
Telegram username to search for
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByTwitterSubject()
getUserByTwitterSubject(
subject
):Promise
<null
|User
>
Get the user object associated with a twitter oauth subject (ID).
typescript
const user = await client.getUserByTwitterSubject(subject);
Parameters
• subject: string
Twitter subject to search for
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByTwitterUsername()
getUserByTwitterUsername(
username
):Promise
<null
|User
>
Get the user object associated with a twitter username.
typescript
const user = await client.getUserByTwitterUsername(username);
Parameters
• username: string
Twitter username to search for
Returns
Promise
<null
| User
>
A User if the user exists.
getUserByWalletAddress()
getUserByWalletAddress(
walletAddress
):Promise
<null
|User
>
Get the user object associated with a wallet address.
typescript
const user = await client.getUserByWalletAddress(walletAddress);
Parameters
• walletAddress: string
The wallet address of the user to find.
Returns
Promise
<null
| User
>
A User if the user exists.
getUserFromIdToken()
getUserFromIdToken(
idToken
):Promise
<User
>
Gets a user from the identity token. First, this verifies the token is valid and then parses the payload into a User
object. Note the user object may be incomplete due to identity token size constraints
typescript
const user = await client.getUser({idToken: cookieIdToken});
Parameters
• idToken: string
the identity token set as a cookie on the users browser
Returns
Promise
<User
>
the user object with parsed from the ID token
getUsers()
getUsers(undefined)
getUsers():
Promise
<User
[]>
Get the list of users associated with this app.
typescript
const users = await client.getUsers();
Returns
Promise
<User
[]>
A list of users.
getUsers(searchTerm)
getUsers(
searchTerm
):Promise
<User
[]>
Get the list of users associated with this app whose email, phone number, wallet address, name, or username match a search term.
typescript
const users = await client.getUsers("@privy.io");
Parameters
• searchTerm: string
(optional) The value used to search the list of users.
Returns
Promise
<User
[]>
A list of users.
Deprecated
Use custom helper functions to search
getUsers(bulkParams)
getUsers(
bulkParams
):Promise
<User
[]>
Get multiple users associated with this app by email, phone number, and wallet address
typescript
const users = await client.getUsers({
emails: ["[email protected]", "[email protected]"]
});
Parameters
• bulkParams: BulkParams
The values used to search the list of users.
Returns
Promise
<User
[]>
A list of users.
getVerificationKey()
getVerificationKey():
Promise
<string
>
Get the auth token verification key.
Note that the verification key is pulled from app settings for the first time only and then cached. On subsequent calls the cached verification key is returned.
Returns
Promise
<string
>
String holding the verification key.
importUser()
importUser(
importUserInput
):Promise
<User
>
Import existing user data into Privy, including their linked account data.
This allows your users to interact with all their linked accounts normally after your migration to Privy.
typescript
const user = await client.importUser({
createEthereumWallet: false,
createSolanaWallet: false,
createEthereumSmartWallet: false,
linkedAccounts: [
{
"subject": "123456789123456789",
"username": "batman#1234",
"email": "[email protected]",
"type": "discord_oauth"
},
{
"number": "+1 123 456 7890",
"type": "phone"
},
{
"address": "0x3DAF84b3f09A0E2092302F7560888dBc0952b7B7",
"type": "wallet",
"chainType": "ethereum"
}
]);
Parameters
• importUserInput: ImportUserInput
The user object ImportUserInput, containing linked accounts to import.
Returns
Promise
<User
>
The resultant user User object.
inviteToAllowlist()
inviteToAllowlist(
allowlistEntry
):Promise
<AllowlistEntry
>
Add an allowlist entry for the given app, to give that user access.
The allowlist must enabled for the app, otherwise this will fail.
typescript
const entry = await client.inviteToAllowlist({ type: 'email', value: '[email protected]'});
Parameters
• allowlistEntry: AllowlistEntryInput
The [AllowlistEntryInput]([object Object]) to add to the allowlist.
Returns
Promise
<AllowlistEntry
>
the created AllowlistEntry object.
removeFromAllowlist()
removeFromAllowlist(
allowlistEntry
):Promise
<AllowlistEntry
>
Remove an entry from the allowlist for a Privy app.
The allowlist must enabled for the app, otherwise this will fail.
typescript
await client.removeFromAllowlist();
Parameters
• allowlistEntry: AllowlistEntryInput
The [AllowlistEntryInput]([object Object]) to remove from the allowlist.
Returns
Promise
<AllowlistEntry
>
the deleted AllowlistEntry object.
setCustomMetadata()
setCustomMetadata<
CustomMetadataInput
>(userId
,customMetadata
):Promise
<User
>
Add customMetadata field to the user object.
Type parameters
• CustomMetadataInput extends Record
<string
, string
| number
| boolean
>
Parameters
• userId: string
DID of the user to set custom metadata for
• customMetadata: CustomMetadataInput
the custom metadata to set for the user
Returns
Promise
<User
>
user object updated with custom metadata
verifyAuthToken()
verifyAuthToken(
token
,verificationKeyOverride
):Promise
<AuthTokenClaims
>
Verify the auth token format, signature, and claims.
Example usage given e.g. a NextApiRequest
request:
typescript
const header = request.headers.authorization;
const token = header.replace(/^Bearer /, '');
const verifiedClaims = await verifyAuthToken(token);
Parameters
• token: string
The auth token (JWT).
• verificationKeyOverride: string
= ''
Overrides the default ES256 JWT verification key loaded from app settings.
Returns
Promise
<AuthTokenClaims
>
Object containing auth token claims.
verifyWebhook()
verifyWebhook(
payload
,headers
,secret
):Promise
<unknown
>
Verifies a webhook request by checking the signature and asserting the timestamp is within 5 minutes of the current time to prevent replay attacks.
Parameters
• payload: Object
The raw JSON payload/body of the webhook request. This must be unaltered or signature verification will fail.
• headers: WebhooksVerificationHeaderInput
A JSON object containing the webhook's ID, timestamp, and signature sent in the headers of the webhook request. This input object must contain id
, timestamp
, and signature
keys.
• secret: string
The webhook secret to use for verifying the webhook request.
Returns
Promise
<unknown
>
verified payload if the webhook signature is valid otherwise throws.