Events
Events are at the heart of the Nostr protocol and described in NIP-01.. To support a wide range of functionality, Nostr comes with a number of event types but you can also create your own.
Creating an event
This is the simplest example of creating a text note kind:1 event.
import NDK, { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk";
const ndk = new NDK(/* initialization options for the ndk singleton */);
const event = new NDKEvent(ndk, {
kind: NDKKind.Text,
content: "Hello world",
});No need to fill in event's id, tags, pubkey, created_at, NDK will do that (if not set).
Tagging users (or events)
Tags tell the protocol about related entities like mentioned users, relays, topics, other events, etc. Details about tags can be found in the tags section of NIP-01 and in the reference list of standardized tags.
NDK automatically adds the appropriate tags for mentions in the content when a user or event is mentioned.
import NDK, { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk";
const ndk = new NDK();
const event = new NDKEvent(ndk, {
kind: NDKKind.Text,
content:
"Hello, nostr:npub1l2vyh47mk2p0qlsku7hg0vn29faehy9hy34ygaclpn66ukqp3afqutajft this is a test from an NDK snippet.",
});
await event.sign();Calling event.sign() will finalize the event, adding the appropriate tags.
The resulting event will look like:
{
"created_at": 1742904504,
"content": "Hello, nostr:npub1l2vyh47mk2p0qlsku7hg0vn29faehy9hy34ygaclpn66ukqp3afqutajft this is a test from an NDK snippet.",
"tags": [["p", "fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52"]],
"kind": 1,
"pubkey": "cbf66fa8cf9877ba98cd218a96d77bed5abdbfd56fdd3d0393d7859d58a313fb",
"id": "26df08155ceb82de8995081bf63a36017cbfd3a616fe49820d8427d22e0af20f",
"sig": "eb6125248cf4375d650b13fa284e81f4270eaa8cb3cae6366ab8cda27dc99c1babe5b5a2782244a9673644f53efa72aba6973ac3fc5465cf334413d90f4ea1b0"
}Signing Events
NDK uses the default signer ndk.signer to sign events.
import NDK, { NDKEvent, NDKNip07Signer } from "@nostr-dev-kit/ndk";
const nip07signer = new NDKNip07Signer();
const ndk = new NDK({ signer: nip07signer });
const event = new NDKEvent(ndk);
event.kind = 1;
event.content = "Hello world";
await event.sign();Read more about signers in the signer documentation
Code Snippets
More snippets and examples can be found in the snippets directory.