Quick Start
Get started with NDK Sessions in minutes.
Installation
sh
npm i @nostr-dev-kit/sessionssh
pnpm add @nostr-dev-kit/sessionssh
yarn add @nostr-dev-kit/sessionssh
bun add @nostr-dev-kit/sessionsBasic Setup
1. Initialize NDK
First, create and initialise your NDK instance:
ts
// Import the package
import NDK from "@nostr-dev-kit/ndk";
// Create a new NDK instance with explicit relays
const ndk = new NDK({
explicitRelayUrls: ["wss://relay.damus.io", "wss://nos.lol", "wss://relay.nostr.band"],
});
// Now connect to specified relays
await ndk.connect();Additional information about relay connections in the connection section.
2. Create Session Manager
Create a session manager with your preferred storage:
ts
import NDK from "@nostr-dev-kit/ndk";
import { LocalStorage, NDKSessionManager } from "@nostr-dev-kit/sessions";
// Create a new NDK instance with explicit relays
const ndk = new NDK({
explicitRelayUrls: ["wss://relay.damus.io", "wss://nos.lol", "wss://relay.nostr.band"],
});
const sessions = new NDKSessionManager(ndk, {
storage: new LocalStorage(),
autoSave: true, // Automatically save changes
saveDebounceMs: 500, // Debounce auto-saves
});More about storage options.
3. Restore Previous Sessions
Restore any previously saved sessions:
ts
await sessions.restore();
if (sessions.activeUser) {
console.log("Welcome back!", sessions.activeUser.npub);
}4. Login (and auto-fetch)
Login with a signer. To automatically fetch user data, configure fetches in the constructor:
ts
import { NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
const sessions = new NDKSessionManager(ndk, {
storage: new LocalStorage(),
autoSave: true,
fetches: {
follows: true, // Fetch contact list
mutes: true, // Fetch mute list
relayList: true, // Fetch relay list
wallet: true, // Fetch NIP-60 wallet
},
});
const signer = new NDKPrivateKeySigner(nsecKey);
await sessions.login(signer);
// Access session data
console.log("Following:", sessions.activeSession?.followSet?.size, "users");
console.log("Muted:", sessions.activeSession?.muteSet?.size, "items");Read-only Sessions
TODO -> Write
Logging out
typescript
// Logout specific account
sessions.logout(pubkey1);
// Or logout current active account
sessions.logout();