Repository navigation
Build a Client
Quick start got one event onto a relay. This page builds what users actually see: log in, load a profile and follows, fetch a home feed from the right relays, render it, and reply or like. It uses JavaScript with nostr-tools 2.25. The code was run against live relays in October 2026, and the same steps apply in any library.
Steps: 1 Log in · 2 Profile and follows · 3 Find relays · 4 Fetch the feed · 5 Render · 6 Reply and like
npm i nostr-toolsDon't ask users for their nsec. In the browser, a NIP-07 extension gives you a pubkey and signs on request:
if (!window.nostr) throw new Error('Install a Nostr signer extension, or use a bunker:// login')
// hex pubkey
const me = await window.nostr.getPublicKey()
// signer.signEvent(template) returns a signed event
const signer = window.nostrOn phones, or without an extension, use a remote signer (NIP-46) instead. Signers & login has tested code for bunker:// and nostrconnect://. Both give you the same getPublicKey() and signEvent() interface, so the rest of this page doesn't change.
Start from a few bootstrap relays: big general relays plus purplepag.es, which indexes profiles and relay lists.
import { SimplePool } from 'nostr-tools/pool'
const pool = new SimplePool()
// remember which relay each event came from (for relay hints)
pool.trackRelays = true
const BOOTSTRAP = ['wss://purplepag.es', 'wss://relay.primal.net', 'wss://relay.nostr.net']
// the user's own relay list first: their kind 0 and 3 may only live there
const myList = await pool.get(BOOTSTRAP, { kinds: [10002], authors: [me] })
const myRelays = (myList?.tags ?? []).filter(t => t[0] === 'r').map(t => t[1])
const where = [...new Set([...myRelays, ...BOOTSTRAP])]
// kind 0: profile JSON (name, display_name, picture, about, nip05, lud16 …)
const meta = await pool.get(where, { kinds: [0], authors: [me] })
const profile = meta ? JSON.parse(meta.content) : {}
// kind 3: follow list, one ["p", pubkey] tag per follow
const contacts = await pool.get(where, { kinds: [3], authors: [me] })
const follows = (contacts?.tags ?? []).filter(t => t[0] === 'p').map(t => t[1])Kinds 0, 3 and 10002 are replaceable: only the newest one counts. pool.get returns the newest it sees. When you collect several, keep the highest created_at per author yourself.
There's no central server, so people post to their own relays. Each user publishes a kind 10002 list (NIP-65). Read notes from each author's write relays. This is the outbox model, and skipping it is the most common reason a new client "can't find" posts.
async function writeRelays(pubkeys) {
const lists = await pool.querySync(BOOTSTRAP, { kinds: [10002], authors: pubkeys })
// keep the newest list per author
const latest = new Map()
for (const ev of lists) {
if ((latest.get(ev.pubkey)?.created_at ?? 0) < ev.created_at) latest.set(ev.pubkey, ev)
}
const out = new Map()
for (const [pk, ev] of latest) {
const urls = ev.tags
.filter(t => t[0] === 'r' && (t[2] === undefined || t[2] === 'write'))
.map(t => t[1])
// a few relays per author is plenty
out.set(pk, urls.slice(0, 3))
}
return out
}
const relaysOf = await writeRelays(follows)
// group authors by relay, then keep the 20 relays that cover the most people
const byRelay = new Map()
for (const pk of follows) {
for (const url of relaysOf.get(pk) ?? BOOTSTRAP.slice(1)) {
if (!byRelay.has(url)) byRelay.set(url, [])
byRelay.get(url).push(pk)
}
}
const requests = [...byRelay]
.sort((a, b) => b[1].length - a[1].length)
.slice(0, 20)
.map(([url, authors]) => ({ url, filter: { kinds: [1], authors, limit: 20 } }))In testing, 199 follows pointed at 129 different relays, and the top 20 covered almost everyone. Query anyone left uncovered on the bootstrap relays. Production clients also cache relay lists and track which relays fail. Libraries such as applesauce, @nostr/gadgets, welshman, NDK and nostr-sdk do this routing for you.
subscribeMap sends a different filter to each relay over one pool. Events arrive in any order and often more than once, so dedupe by id and sort by created_at.
const feed = new Map()
const sub = pool.subscribeMap(requests, {
onevent(ev) {
// the same note from 3 relays is 1 entry
feed.set(ev.id, ev)
// debounce this in a real UI
const sorted = [...feed.values()]
.sort((a, b) => b.created_at - a.created_at)
render(sorted)
},
// stored events are in; new ones keep streaming
oneose() {},
maxWait: 8000,
})
// later, when the view goes away:
sub.close()For older pages, repeat the query with until set to the oldest created_at you have.
Relays push back. On auth-required:, sign a NIP-42 AUTH and retry: pass { onauth: t => signer.signEvent(t) } to publish or subscribeMany, but only for the user's own relays, since AUTH tells a relay who the user is. On rate-limited:, back off. Read each relay's NIP-11 limitation (max_subscriptions, max_limit, max_filters) and split big authors lists to fit. SimplePool verifies every signature by default. Keep it that way.
Note content is plain text with nostr: references (NIP-27), URLs and hashtags. Thread position comes from tags (NIP-10). nostr-tools parses both. Content is untrusted input, so escape every piece before it becomes HTML:
import * as nip10 from 'nostr-tools/nip10'
import * as nip19 from 'nostr-tools/nip19'
import * as nip27 from 'nostr-tools/nip27'
const esc = s => s.replace(/[&<>"']/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
const safeUrl = u => /^https:\/\//i.test(u) ? esc(u) : null
// returns HTML in which every piece of user content is escaped
function toHtml(ev) {
return [...nip27.parse(ev.content)].map(b => {
if (b.type === 'text') return esc(b.text).replace(/\n/g, '<br>')
if (b.type === 'hashtag')
return `<a href="/t/${encodeURIComponent(b.value)}">#${esc(b.value)}</a>`
if (b.type === 'image' && safeUrl(b.url))
return `<img src="${safeUrl(b.url)}" loading="lazy">`
if ((b.type === 'url' || b.type === 'image') && safeUrl(b.url))
return `<a href="${safeUrl(b.url)}" rel="nofollow noopener">${esc(b.url)}</a>`
if (b.type === 'reference' && !('id' in b.pointer) && !('identifier' in b.pointer)) {
// a mention: show a short npub, swap in their kind 0 name once loaded
const npub = nip19.npubEncode(b.pointer.pubkey)
return `<a href="/p/${npub}">@${npub.slice(0, 12)}…</a>`
}
// nevent / naddr: fetch the referenced event and embed it
if (b.type === 'reference') return '<span class="quote">[quoted event]</span>'
return ''
}).join('')
}
// for a note `ev`: EventPointers, or undefined for a top-level note
const { root, reply } = nip10.parse(ev)Tested against a hostile note: <script>, javascript: links and "><img onerror=…> all come out as inert text. If you use a framework, rendering text nodes, as React or Svelte do by default, gets you the same safety.
Build an event template, have the signer sign it, then publish to the user's write relays (myRelays from step 2), plus the author's read relays if you want them to see it.
// `parent` is the note being replied to, from your feed
const now = () => Math.floor(Date.now() / 1000)
// a relay where the parent was seen ("" is allowed)
const relayHint = [...(pool.seenOn.get(parent.id) ?? [])][0]?.url ?? ''
// notify everyone in the thread, not just the author
const pTags = [...new Set([...parent.tags.filter(t => t[0] === 'p').map(t => t[1]), parent.pubkey])]
.map(pk => ['p', pk])
// reply (NIP-10): mark the thread root, tag the author.
// Deeper in a thread, add the root AND a 'reply' marker for the parent.
const replyEv = await signer.signEvent({
kind: 1,
created_at: now(),
content: 'nice post!',
tags: [
['e', parent.id, relayHint, 'root', parent.pubkey],
...pTags,
],
})
// like (NIP-25)
const likeEv = await signer.signEvent({
kind: 7,
created_at: now(),
content: '+',
tags: [['e', parent.id, relayHint], ['p', parent.pubkey], ['k', String(parent.kind)]],
})
// pool.publish returns one promise per relay: check them all
const onauth = t => signer.signEvent(t)
const results = await Promise.allSettled(pool.publish(myRelays, replyEv, { onauth }))To load replies and reactions for a note, query { kinds: [1, 1111, 7, 6, 9735, 5], "#e": [note.id] } plus { kinds: [1111], "#E": [note.id] }. NIP-22 comments deeper in a thread tag the root with uppercase E, and since August 2026 some clients reply to notes with kind 1111. Split the results by kind: replies, likes, reposts, zaps. Hide anything covered by a kind 5 deletion from the same author.
| Add… | Read |
|---|---|
| Names and avatars for mentions | Batch a kind 0 query for every pubkey you display, then cache it |
| Private messages | NIP-17, gift-wrapped and sent to the recipient's kind 10050 relays. Don't use NIP-04. Read the traps below first |
| Images and video uploads | Upload to the user's Blossom servers from their kind 10063 list (NIP-B7), with a kind 24242 auth event (BUD-11). Upload to one server and mirror to the rest, then describe the file with imeta (NIP-92) |
| Zaps and wallets |
NIP-57 zaps and NIP-47 Wallet Connect (@getalby/sdk) |
| Mute lists and spam filtering | Kind 10000 (NIP-51) and web-of-trust filtering, see Social graph |
| Real-world reference code | Open-source clients |
Warning
NIP-17 traps. First DM implementations usually hit at least one of these:
- The kind 14 message is an unsigned rumor. If you sign it, anyone it leaks to can republish it publicly.
- After unwrapping, check that the seal's (kind 13)
pubkeyequals the rumor'spubkey. Otherwise anyone can impersonate anyone. - Wrap one copy per recipient and one for yourself, or sent messages vanish on the user's other devices.
- Publish only to the recipient's kind 10050 relays. No 10050 means they can't receive DMs, so don't fall back to other relays.
- DM relays usually serve kind 1059 only after NIP-42 AUTH.
- Gift-wrap
created_atis randomised up to two days into the past, so query withsinceat least two days back, and sort by the rumor'screated_at. - Over a NIP-46 bunker, every decrypt is a network round trip. Cache plaintext locally and decrypt lazily.
← Quick start · Next: Protocol basics →
Nostr Developer Guide · maintained by the W3C Nostr Community Group (a Community Group work, not a W3C Standard) · last reviewed 22 October 2026 · report a problem · guide site