Tools for developing Nostr clients.
Go to file
Chris McCormick bc1294e4e6
Reconnect with exponential backoff flag: `enableReconnect` (#507)
https://github.com/nbd-wtf/nostr-tools/pull/507
2025-09-30 10:01:07 -03:00
.devcontainer including nostr specialized types (#409) 2024-09-09 14:16:23 -03:00
.github/workflows Remove GitHub actions flow for publishing to JSR because it's not working 2024-03-18 13:23:29 -05:00
.editorconfig Add .editorconfig 2023-04-01 08:18:57 -03:00
.eslintrc.json get rid of nip96 and unnecessary dependencies. 2025-04-02 11:51:02 -03:00
.gitignore unsplit, backwards-compatibility, wasm relay and pool must be configured manually from the abstract classes. 2023-12-21 19:57:28 -03:00
.prettierrc.yaml prettier: increase printWidth, enable bracketSpacing, alphabetize 2023-08-31 13:00:50 -05:00
LICENSE Add Unlicense 2023-04-20 12:22:39 -03:00
README.md Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
abstract-pool.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
abstract-relay.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
benchmarks.ts Add missing file extensions to imports 2024-03-18 11:51:00 -05:00
build.js fix problem when required from CommonJS 2023-12-23 08:31:39 -03:00
bun.lockb publish: --allow-slow-types for now 2024-03-11 15:15:41 -05:00
core.test.ts fix: move NostrTypeGuard tests to nip19.test.ts 2024-10-11 07:48:46 -03:00
core.ts some small bugs codebuff found. 2025-04-03 23:31:34 -03:00
fakejson.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
fakejson.ts fakejson match subscription id. 2023-02-08 14:15:54 -03:00
filter.test.ts getFilterLimit: handle parameterized replaceable events 2024-07-20 22:00:28 -03:00
filter.ts rename "parameterized replaceable" to "addressable". 2025-01-23 14:08:22 -03:00
helpers.ts fix yieldThread memory leak 2023-12-30 13:50:44 -03:00
index.ts nip54 normalizeIdentifier function 2025-02-25 13:52:40 -03:00
jsr.json chore: Bump version and document NIP-46 usage 2025-08-25 11:00:06 -03:00
justfile publish to jsr before npm. 2025-05-12 05:27:16 -03:00
kinds.test.ts Suggestion: export kinds as named types (#447) 2024-10-23 10:39:39 -03:00
kinds.ts remove two deprecated things. 2025-05-31 20:04:46 -03:00
nip04.test.ts use @noble/ciphers instead of webcrypto on nip04. 2024-02-17 18:15:42 -03:00
nip04.ts nip04: functions shouldn't be async. 2025-04-02 10:19:27 -03:00
nip05.test.ts nip05: use stub to test queryProfile(). 2024-10-31 07:51:53 -03:00
nip05.ts fix lint error. 2024-10-31 20:43:03 +09:00
nip06.test.ts test: fixed nip06 assertion 2024-10-20 10:53:08 -03:00
nip06.ts nip06: return Uint8 instead of string 2024-10-20 10:53:08 -03:00
nip07.ts nip07: return a VerifiedEvent 2025-04-11 17:31:57 -03:00
nip10.test.ts nip10: improve, support quotes, author hints, change the way legacy refs are discovered. 2024-11-04 15:37:39 -03:00
nip10.ts nip10: fix. 2024-11-13 01:21:54 -03:00
nip11.test.ts update nip11 test. 2025-03-14 09:30:35 -03:00
nip11.ts export retention details 2025-02-10 09:25:33 -03:00
nip13.test.ts nip13: speed improvements. 2024-10-22 13:03:29 -03:00
nip13.ts nip13: speed improvements. 2024-10-22 13:03:29 -03:00
nip17.test.ts improve signature for decode function (#489) 2025-06-01 11:08:57 -03:00
nip17.ts fix slow types so we can publish to jsr.io 2024-10-26 14:23:28 -03:00
nip18.test.ts Generic repost 2025-03-10 01:58:00 -03:00
nip18.ts Generic repost 2025-03-10 01:58:00 -03:00
nip19.test.ts Get pingpong working in the browser with dummy REQ (#499) 2025-07-24 11:22:15 -03:00
nip19.ts improve signature for decode function (#489) 2025-06-01 11:08:57 -03:00
nip21.test.ts Revert "nip19: remove note1." 2024-11-26 11:59:58 -03:00
nip21.ts fix types from latest nip19 type change. 2025-05-12 05:23:54 -03:00
nip25.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip25.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip27.test.ts nip27: rewrite to support urls and references in a simpler API for rich UIs. 2025-03-14 09:26:40 -03:00
nip27.ts ensures consistency for .jpg/.JPG, .mp4/.MP4, etc 2025-08-27 10:32:45 -03:00
nip28.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip28.ts Implemented NIP-17 support (#449) 2024-10-24 21:10:09 -03:00
nip29.ts cleanup. 2025-07-23 16:22:25 -03:00
nip30.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip30.ts Fix (most) slow types by adding explicit return types 2024-03-07 07:22:44 -03:00
nip39.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip39.ts just format 2023-08-31 13:42:15 -05:00
nip40.test.ts format with prettier 2024-01-18 11:51:13 -03:00
nip40.ts format with prettier 2024-01-18 11:51:13 -03:00
nip42.test.ts delete some unnecessary code from mock-relay implementation. 2024-01-20 12:48:46 -03:00
nip42.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
nip44.test.ts fix for updated typescript. 2025-04-02 11:44:41 -03:00
nip44.ts nip44: make the api less classy. 2024-05-19 14:40:23 -03:00
nip44.vectors.json Add nip44 v2 2023-12-21 08:55:23 -03:00
nip46.ts chore: Bump version and document NIP-46 usage 2025-08-25 11:00:06 -03:00
nip47.test.ts enhance parseConnectionString to support double slash URL format 2025-07-13 11:59:04 -03:00
nip47.ts enhance parseConnectionString to support double slash URL format 2025-07-13 11:59:04 -03:00
nip49.test.ts Add missing file extensions to imports 2024-03-18 11:51:00 -05:00
nip49.ts nip19/nip49: remove nrelay and move bech32 string guard methods from core to nip19. 2024-09-09 14:20:35 -03:00
nip54.test.ts nip54 normalizeIdentifier function 2025-02-25 13:52:40 -03:00
nip54.ts nip54 normalizeIdentifier function 2025-02-25 13:52:40 -03:00
nip55.test.ts nip55: remove getRelays() 2025-03-02 01:25:39 -03:00
nip55.ts nip55: remove getRelays() 2025-03-02 01:25:39 -03:00
nip57.test.ts nip57: cleanup useless tests. 2025-08-01 20:28:49 -03:00
nip57.ts nip57: include "e" tag. 2025-08-04 15:23:29 -03:00
nip58.test.ts Nip58 Implementation (#386) 2024-03-16 13:44:56 -03:00
nip58.ts Add missing file extensions to imports 2024-03-18 11:51:00 -05:00
nip59.test.ts fix types from latest nip19 type change. 2025-05-12 05:23:54 -03:00
nip59.ts fix slow types so we can publish to jsr.io 2024-10-26 14:23:28 -03:00
nip75.test.ts add tests for nip75 2024-02-14 19:48:07 -03:00
nip75.ts Add missing file extensions to imports 2024-03-18 11:51:00 -05:00
nip94.test.ts support fallback tag in NIP-94 2024-07-04 15:07:37 -03:00
nip94.ts support fallback tag in NIP-94 2024-07-04 15:07:37 -03:00
nip98.test.ts refactor and add more test cases 2024-01-17 18:13:10 +03:30
nip98.ts fix some bugs, refactor to smaller parts, add docs 2024-01-17 17:50:48 +03:30
nip99.test.ts Add missing file extensions to imports 2024-03-18 11:51:00 -05:00
nip99.ts remove un-used imports 2024-01-18 17:16:24 +03:30
nipb7.test.ts blossom test. 2025-06-04 21:45:43 -03:00
nipb7.ts nipB7 (blossom) and a generic signer interface. 2025-06-04 21:28:33 -03:00
package.json chore: Bump version and document NIP-46 usage 2025-08-25 11:00:06 -03:00
pool.test.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
pool.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
pure.test.ts core.test.ts -> pure.test.ts 2024-04-12 17:44:36 -05:00
pure.ts Fix (most) slow types by adding explicit return types 2024-03-07 07:22:44 -03:00
references.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
references.ts Revert "nip19: remove note1." 2024-11-26 11:59:58 -03:00
relay.test.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
relay.ts Reconnect with exponential backoff flag: `enableReconnect` (#507) 2025-09-30 10:01:07 -03:00
signer.ts blossom test. 2025-06-04 21:45:43 -03:00
test-helpers.ts Improvements to enablePing() & tests (#506) 2025-09-29 10:41:40 -03:00
tsconfig.json Revert "tsconfig: for sanity, go back to moduleResolution bundler and see if that fixes it" 2024-03-18 13:02:35 -05:00
utils.test.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
utils.ts expose hexToBytes and bytesToHex helpers. 2025-05-28 14:50:25 -03:00
wasm.ts Wasm: add explicit type to `i` 2024-03-18 13:04:21 -05:00

README.md

JSR nostr-tools

Tools for developing Nostr clients.

Only depends on @scure and @noble packages.

This package is only providing lower-level functionality. If you want higher-level features, take a look at @nostr/gadgets which is based on this library and expands upon it and has other goodies (it's only available on jsr).

Installation

# npm
npm install --save nostr-tools

# jsr
npx jsr add @nostr/tools

If using TypeScript, this package requires TypeScript >= 5.0.

Documentation

https://jsr.io/@nostr/tools/doc

Usage

Generating a private key and a public key

import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'

let sk = generateSecretKey() // `sk` is a Uint8Array
let pk = getPublicKey(sk) // `pk` is a hex string

To get the secret key in hex format, use

import { bytesToHex, hexToBytes } from '@noble/hashes/utils' // already an installed dependency

let skHex = bytesToHex(sk)
let backToBytes = hexToBytes(skHex)

Creating, signing and verifying events

import { finalizeEvent, verifyEvent } from 'nostr-tools/pure'

let event = finalizeEvent({
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'hello',
}, sk)

let isGood = verifyEvent(event)

Interacting with one or multiple relays

Doesn't matter what you do, you always should be using a SimplePool:

import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure'
import { SimplePool } from 'nostr-tools/pool'

const pool = new SimplePool()

const relays = ['wss://relay.example.com', 'wss://relay.example2.com']

// let's query for one event that exists
const event = pool.get(
  relays,
  {
    ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'],
  },
)
if (event) {
  console.log('it exists indeed on this relay:', event)
}

// let's query for more than one event that exists
const events = pool.querySync(
  relays,
  {
    kinds: [1],
    limit: 10
  },
)
if (events) {
  console.log('it exists indeed on this relay:', events)
}

// let's publish a new event while simultaneously monitoring the relay for it
let sk = generateSecretKey()
let pk = getPublicKey(sk)

pool.subscribe(
  ['wss://a.com', 'wss://b.com', 'wss://c.com'],
  {
    kinds: [1],
    authors: [pk],
  },
  {
    onevent(event) {
      console.log('got event:', event)
    }
  }
)

let eventTemplate = {
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'hello world',
}

// this assigns the pubkey, calculates the event id and signs the event in a single step
const signedEvent = finalizeEvent(eventTemplate, sk)
await Promise.any(pool.publish(['wss://a.com', 'wss://b.com'], signedEvent))

relay.close()

To use this on Node.js you first must install ws and call something like this:

import { useWebSocketImplementation } from 'nostr-tools/pool'
// or import { useWebSocketImplementation } from 'nostr-tools/relay' if you're using the Relay directly

import WebSocket from 'ws'
useWebSocketImplementation(WebSocket)

enablePing

You can enable regular pings of connected relays with the enablePing option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms, like Node.js, don't report websocket disconnections due to network issues, and enabling this can increase the reliability of the onclose event.

import { SimplePool } from 'nostr-tools/pool'

const pool = new SimplePool({ enablePing: true })

enableReconnect

You can also enable automatic reconnection with the enableReconnect option. This will make the pool try to reconnect to relays with an exponential backoff delay if the connection is lost unexpectedly.

import { SimplePool } from 'nostr-tools/pool'

const pool = new SimplePool({ enableReconnect: true })

Using both enablePing: true and enableReconnect: true is recommended as it will improve the reliability and timeliness of the reconnection (at the expense of slighly higher bandwidth due to the ping messages).

// on Node.js
const pool = new SimplePool({ enablePing: true, enableReconnect: true })

The enableReconnect option can also be a callback function which will receive the current subscription filters and should return a new set of filters. This is useful if you want to modify the subscription on reconnect, for example, to update the since parameter to fetch only new events.

const pool = new SimplePool({
  enableReconnect: (filters) => {
    const newSince = Math.floor(Date.now() / 1000)
    return filters.map(filter => ({ ...filter, since: newSince }))
  }
})

Parsing references (mentions) from a content based on NIP-27

import * as nip27 from '@nostr/tools/nip27'

for (let block of nip27.parse(evt.content)) {
  switch (block.type) {
    case 'text':
      console.log(block.text)
      break
    case 'reference': {
      if ('id' in block.pointer) {
        console.log("it's a nevent1 uri", block.pointer)
      } else if ('identifier' in block.pointer) {
        console.log("it's a naddr1 uri", block.pointer)
      } else {
        console.log("it's an npub1 or nprofile1 uri", block.pointer)
      }
      break
    }
    case 'url': {
      console.log("it's a normal url:", block.url)
      break
    }
    case 'image':
    case 'video':
    case 'audio':
      console.log("it's a media url:", block.url)
      break
    case 'relay':
      console.log("it's a websocket url, probably a relay address:", block.url)
      break
    default:
      break
  }
}

Connecting to a bunker using NIP-46

BunkerSigner allows your application to request signatures and other actions from a remote NIP-46 signer, often called a "bunker". There are two primary ways to establish a connection, depending on whether the client or the bunker initiates the connection.

A local secret key is required for the client to communicate securely with the bunker. This key should generally be persisted for the user's session.

import { generateSecretKey } from '@nostr/tools/pure'

const localSecretKey = generateSecretKey()

Method 1: Using a Bunker URI (bunker://)

This is the bunker-initiated flow. Your client receives a bunker:// string or a NIP-05 identifier from the user. You use BunkerSigner.fromBunker() to create an instance, which returns immediately. For the initial connection with a new bunker, you must explicitly call await bunker.connect() to establish the connection and receive authorization.

import { BunkerSigner, parseBunkerInput } from '@nostr/tools/nip46'
import { SimplePool } from '@nostr/tools/pool'

// parse a bunker URI
const bunkerPointer = await parseBunkerInput('bunker://abcd...?relay=wss://relay.example.com')
if (!bunkerPointer) {
  throw new Error('Invalid bunker input')
}

// create the bunker instance
const pool = new SimplePool()
const bunker = BunkerSigner.fromBunker(localSecretKey, bunkerPointer, { pool })
await bunker.connect()

// and use it
const pubkey = await bunker.getPublicKey()
const event = await bunker.signEvent({
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'Hello from bunker!'
})

// cleanup
await signer.close()
pool.close([])

Note on Reconnecting: Once a connection has been successfully established and the BunkerPointer is stored, you do not need to call await bunker.connect() on subsequent sessions.

Method 2: Using a Client-generated URI (nostrconnect://)

This is the client-initiated flow, which generally provides a better user experience for first-time connections (e.g., via QR code). Your client generates a nostrconnect:// URI and waits for the bunker to connect to it.

BunkerSigner.fromURI() is an asynchronous method. It returns a Promise that resolves only after the bunker has successfully connected. Therefore, the returned signer instance is already fully connected and ready to use, so you do not need to call .connect() on it.

import { getPublicKey } from '@nostr/tools/pure'
import { BunkerSigner, createNostrConnectURI } from '@nostr/tools/nip46'
import { SimplePool } from '@nostr/tools/pool'

const clientPubkey = getPublicKey(localSecretKey)

// generate a connection URI for the bunker to scan
const connectionUri = createNostrConnectURI({
  clientPubkey,
  relays: ['wss://relay.damus.io', 'wss://relay.primal.net'],
  secret: 'a-random-secret-string', // A secret to verify the bunker's response
  name: 'My Awesome App'
})

// wait for the bunker to connect
const pool = new SimplePool()
const signer = await BunkerSigner.fromURI(localSecretKey, connectionUri, { pool })

// and use it
const pubkey = await signer.getPublicKey()
const event = await signer.signEvent({
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'Hello from a client-initiated connection!'
})

// cleanup
await signer.close()
pool.close([])

Note on Persistence: This method is ideal for the initial sign-in. To allow users to stay logged in across sessions, you should store the connection details and use Method 1 for subsequent reconnections.

Parsing thread from any note based on NIP-10

import * as nip10 from '@nostr/tools/nip10'

// event is a nostr event with tags
const refs = nip10.parse(event)

// get the root event of the thread
if (refs.root) {
  console.log('root event:', refs.root.id)
  console.log('root event relay hints:', refs.root.relays)
  console.log('root event author:', refs.root.author)
}

// get the immediate parent being replied to
if (refs.reply) {
  console.log('reply to:', refs.reply.id)
  console.log('reply relay hints:', refs.reply.relays)
  console.log('reply author:', refs.reply.author)
}

// get any mentioned events
for (let mention of refs.mentions) {
  console.log('mentioned event:', mention.id)
  console.log('mention relay hints:', mention.relays)
  console.log('mention author:', mention.author)
}

// get any quoted events
for (let quote of refs.quotes) {
  console.log('quoted event:', quote.id)
  console.log('quote relay hints:', quote.relays)
}

// get any referenced profiles
for (let profile of refs.profiles) {
  console.log('referenced profile:', profile.pubkey)
  console.log('profile relay hints:', profile.relays)
}

Querying profile data from a NIP-05 address

import { queryProfile } from 'nostr-tools/nip05'

let profile = await queryProfile('jb55.com')
console.log(profile.pubkey)
// prints: 32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245
console.log(profile.relays)
// prints: [wss://relay.damus.io]

To use this on Node.js < v18, you first must install node-fetch@2 and call something like this:

import { useFetchImplementation } from 'nostr-tools/nip05'
useFetchImplementation(require('node-fetch'))

Including NIP-07 types

import type { WindowNostr } from 'nostr-tools/nip07'

declare global {
  interface Window {
    nostr?: WindowNostr;
  }
}

Encoding and decoding NIP-19 codes

import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'
import * as nip19 from 'nostr-tools/nip19'

let sk = generateSecretKey()
let nsec = nip19.nsecEncode(sk)
let { type, data } = nip19.decode(nsec)
assert(type === 'nsec')
assert(data === sk)

let pk = getPublicKey(generateSecretKey())
let npub = nip19.npubEncode(pk)
let { type, data } = nip19.decode(npub)
assert(type === 'npub')
assert(data === pk)

let pk = getPublicKey(generateSecretKey())
let relays = ['wss://relay.nostr.example.mydomain.example.com', 'wss://nostr.banana.com']
let nprofile = nip19.nprofileEncode({ pubkey: pk, relays })
let { type, data } = nip19.decode(nprofile)
assert(type === 'nprofile')
assert(data.pubkey === pk)
assert(data.relays.length === 2)

Using it with nostr-wasm

nostr-wasm is a thin wrapper over libsecp256k1 compiled to WASM just for hashing, signing and verifying Nostr events.

import { setNostrWasm, generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/wasm'
import { initNostrWasm } from 'nostr-wasm'

// make sure this promise resolves before your app starts calling finalizeEvent or verifyEvent
initNostrWasm().then(setNostrWasm)

// or use 'nostr-wasm/gzipped' or even 'nostr-wasm/headless',
// see https://www.npmjs.com/package/nostr-wasm for options

If you're going to use Relay and SimplePool you must also import nostr-tools/abstract-relay and/or nostr-tools/abstract-pool instead of the defaults and then instantiate them by passing the verifyEvent:

import { setNostrWasm, verifyEvent } from 'nostr-tools/wasm'
import { AbstractRelay } from 'nostr-tools/abstract-relay'
import { AbstractSimplePool } from 'nostr-tools/abstract-pool'
import { initNostrWasm } from 'nostr-wasm'

initNostrWasm().then(setNostrWasm)

const relay = AbstractRelay.connect('wss://relayable.org', { verifyEvent })
const pool = new AbstractSimplePool({ verifyEvent })

This may be faster than the pure-JS noble libraries used by default and in nostr-tools/pure. Benchmarks:

benchmark      time (avg)             (min … max)       p75       p99      p995
------------------------------------------------- -----------------------------
• relay read message and verify event (many events)
------------------------------------------------- -----------------------------
wasm        34.94 ms/iter   (34.61 ms … 35.73 ms)  35.07 ms  35.73 ms  35.73 ms
pure js     239.7 ms/iter (235.41 ms … 243.69 ms) 240.51 ms 243.69 ms 243.69 ms
trusted    402.71 µs/iter   (344.57 µs … 2.98 ms) 407.39 µs 745.62 µs 812.59 µs

summary for relay read message and verify event
  wasm
   86.77x slower than trusted
   6.86x faster than pure js

Using from the browser (if you don't want to use a bundler)

<script src="https://unpkg.com/nostr-tools/lib/nostr.bundle.js"></script>
<script>
  window.NostrTools.generateSecretKey('...') // and so on
</script>

Plumbing

To develop nostr-tools, install just and run just -l to see commands available.

License

This is free and unencumbered software released into the public domain. By submitting patches to this project, you agree to dedicate any and all copyright interest in this software to the public domain.

Contributing to this repository

Use NIP-34 to send your patches to:

naddr1qq9kummnw3ez6ar0dak8xqg5waehxw309aex2mrp0yhxummnw3ezucn8qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqpzemhxue69uhhyetvv9ujuurjd9kkzmpwdejhgq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqpmejdv00jq