Helpers
NDK comes with a ton of useful helpers and utilities to do things faster and easier.
Quite a number of those utilities come from the nostr-tools library which is included as part of NDK
NIP-19 Identifiers
NDK re-exports NIP-19 from the nostr-tools library:
ts
import { nip19 } from "@nostr-dev-kit/ndk";
// Encode a pubkey as npub
const npub = nip19.npubEncode("3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d");
console.log(npub); //
// Decode any NIP-19 identifier
const decoded = nip19.decode("npub1...");
console.log(decoded.type); // "npub"
console.log(decoded.data); // hex pubkey
// Encode events
const nevent = nip19.neventEncode({
id: "574033c986bea1d7493738b46fec1bb98dd6a826391d6aa893137e89790027ec",
relays: ["wss://relay.example.com"],
author: "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
});
console.log(nevent);NIP-49 Encryption
NDK re-exports NIP-49 from the nostr-tools library:
ts
import {bytesToHex, hexToBytes} from "@noble/hashes/utils";
import {nip49} from "@nostr-dev-kit/ndk";
// Encrypt raw private key bytes
const privateKeyHex = "14c226dbdd865d5e1645e72c7470fd0a17feb42cc87b750bab6538171b3a3f8a";
const privateKeyBytes = hexToBytes(privateKeyHex);
const password = "my-password";
const ncryptsec = nip49.encrypt(privateKeyBytes, password, 16, 0x02);
console.log("Encrypted:", ncryptsec);
// Decrypt to raw bytes
const decryptedBytes = nip49.decrypt(ncryptsec, password);
const decryptedHex = bytesToHex(decryptedBytes);
console.log("Decrypted:", decryptedHex);Managing Users
ts
import NDK from "@nostr-dev-kit/ndk";
const ndk = new NDK({});
// From hex pubkey
const user1 = await ndk.fetchUser("3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d");
// From npub (NIP-19 encoded)
const user2 = await ndk.fetchUser("npub1n0sturny6w9zn2wwexju3m6asu7zh7jnv2jt2kx6tlmfhs7thq0qnflahe");
// From nprofile (includes relay hints)
const user3 = await ndk.fetchUser(
"nprofile1qqsrhuxx8l9ex335q7he0f09aej04zpazpl0ne2cgukyawd24mayt8gpp4mhxue69uhhytnc9e3k7mgpz4mhxue69uhkg6nzv9ejuumpv34kytnrdaksjlyr9p",
);
// From NIP-05 identifier
const user4 = await ndk.fetchUser("pablo@test.com");
const user5 = await ndk.fetchUser("test.com"); // Uses _@test.com
// The method automatically detects the format
const user6 = await ndk.fetchUser("deadbeef..."); // Assumes hex pubkey