Skip to main content

Accessing data

All data in Privy is stored in a field and associated with a user_id.

For full documentation, please see the Privy API references.

Initializing a session using privy-browser

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

const session = new CustomSession(async function authenticate() {
const response = await axios.post<{token: string}>(`/your/custom/endpoint`);
return response.data.token;
});

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

Writing data

// Single field
const email = await client.put(userId, 'email', 'foo@example.com');

// Multiple fields. Resulting list is ordered according to input list.
const [firstName, lastName] = await client.put(userId, [
{field: 'first-name', value: 'Jane'},
{field: 'last-name', value: 'Doe'},
]);

Reading data

// NOTE: When reading field values, resulting objects may
// be null if no value exists for that user and field yet.

// Single field
const email = await client.get(userId, 'email');

// Multiple fields. Resulting list is ordered according to input list.
const [firstName, lastName, avatarUrl] = await client.get(userId, [
'first-name',
'last-name',
'avatar-url',
]);

console.log(email !== null ? email.text() : 'N/A'); // foo@example.com
console.log(firstName !== null ? firstName.text() : 'N/A'); // Jane
console.log(lastName !== null ? lastName.text() : 'N/A'); // Doe
console.log(avatarUrl !== null ? avatarUrl.text() : 'N/A'); // N/A

Writing files

Privy supports unstructured data handling (useful for e.g. videos, images, etc). You can access them as follows.

const onUpdateAvatar = async (avatar: File) => {
try {
await client.putFile(userId, 'avatar', avatar);
} catch (error) {
console.log(error);
}
};

Reading files

const avatar = await client.getFile(userId, 'avatar');

if (avatar !== null) {
download(avatar.integrity_hash, avatar.blob());
}

function download(uniqueId: string, blob: Blob) {
const data = window.URL.createObjectURL(blob);

// Lookup extension by mime type (included on blob)
const ext = getExtensionFromMIMEType(blob.type);
const filename = `${uniqueId}.${ext}`;

// Create a link pointing to the ObjectURL containing the blob.
const link = document.createElement('a');
link.style = 'display: none;';
link.href = data;
link.download = filename;
link.click();

// Cleanup
window.URL.revokeObjectURL(data);
link.remove();
}

Reading a field by its integrity hash

Privy also allows you to query files by a unique identifier: their integrity hash. Read more about integrity hashes.

const ssn = await client.put(userId, 'ssn', '123-45-6789');
const ssnIntegrityHash = ssn.integrityHash;

// later on...
const ssn = await client.getByIntegrityHash(ssnIntegrityHash);
console.log(ssn.text()); // '123-45-6789'