API Reference
Complete API documentation for @nostr-dev-kit/sessions.
NDKSessionManager
The main class for managing user sessions.
Constructor
new NDKSessionManager(ndk: NDK, options?: SessionManagerOptions)Parameters:
ndk: NDK- The NDK instance to useoptions?: SessionManagerOptions- Configuration options
SessionManagerOptions:
interface SessionManagerOptions {
storage?: SessionStorage; // Storage backend (default: MemoryStorage)
autoSave?: boolean; // Auto-persist on changes (default: true)
saveDebounceMs?: number; // Debounce time for auto-save (default: 500ms)
fetches?: SessionStartOptions; // What to fetch on login/restore
}Example:
import { NDKSessionManager, LocalStorage } from '@nostr-dev-kit/sessions';
const sessions = new NDKSessionManager(ndk, {
storage: new LocalStorage(),
autoSave: true,
saveDebounceMs: 500,
fetches: {
follows: true,
mutes: true
}
});Methods
login()
Login with a signer or user.
async login(
userOrSigner: NDKUser | NDKSigner,
options?: { setActive?: boolean }
): Promise<Hexpubkey>Parameters:
userOrSigner- An NDKSigner for full sessions or NDKUser for read-onlyoptions?: { setActive?: boolean }- Whether to set as active session (default: true)
Returns: Promise<Hexpubkey> - The public key of the logged-in user
Example:
const signer = new NDKPrivateKeySigner(nsec);
// Configure fetches in constructor
const sessions = new NDKSessionManager(ndk, {
fetches: {
follows: true,
mutes: true,
relayList: true,
wallet: true
}
});
const pubkey = await sessions.login(signer);
console.log('Logged in:', pubkey);
// Or don't set as active
const pubkey2 = await sessions.login(signer2, { setActive: false });logout()
Remove a session. If no pubkey provided, removes the active session.
logout(pubkey?: Hexpubkey): voidParameters:
pubkey?: Hexpubkey- Public key of session to remove (optional)
Example:
// Logout specific user
sessions.logout(somePubkey);
// Logout active user
sessions.logout();switchTo()
Switch the active session to a different user.
switchTo(pubkey: Hexpubkey): voidParameters:
pubkey: Hexpubkey- Public key of session to activate
Example:
sessions.switchTo(pubkey);
console.log('Now active:', sessions.activePubkey);restore()
Restore sessions from storage.
async restore(): Promise<void>Example:
await sessions.restore();
if (sessions.activeUser) {
console.log('Restored session for', sessions.activeUser.npub);
}persist()
Manually persist sessions to storage.
async persist(): Promise<void>Example:
await sessions.persist();clear()
Clear all sessions from storage.
async clear(): Promise<void>Example:
await sessions.clear();subscribe()
Subscribe to session state changes.
subscribe(callback: (state: SessionState) => void): UnsubscribeFnParameters:
callback- Function called when state changes
Returns: UnsubscribeFn - Function to unsubscribe
SessionState:
interface SessionState {
sessions: Map<Hexpubkey, NDKSession>;
activePubkey?: Hexpubkey;
}Example:
const unsubscribe = sessions.subscribe((state) => {
console.log('Active:', state.activePubkey);
console.log('Sessions:', state.sessions.size);
});
// Later...
unsubscribe();destroy()
Cleanup and stop all subscriptions and timers.
destroy(): voidExample:
sessions.destroy();getSessions()
Get all sessions.
getSessions(): Map<Hexpubkey, NDKSession>Example:
const allSessions = sessions.getSessions();
for (const [pubkey, session] of allSessions) {
console.log(pubkey, session.user.profile?.name);
}getSession()
Get a specific session by pubkey.
getSession(pubkey: Hexpubkey): NDKSession | undefinedParameters:
pubkey: Hexpubkey- Public key of session to get
Example:
const session = sessions.getSession(pubkey);
if (session) {
console.log('Follows:', session.followSet?.size);
}Properties
activeSession
Get the currently active session.
get activeSession(): NDKSession | undefinedExample:
const session = sessions.activeSession;
if (session) {
console.log('Follows:', session.followSet?.size);
console.log('Mutes:', session.muteSet?.size);
}activeUser
Get the currently active user.
get activeUser(): NDKUser | undefinedExample:
const user = sessions.activeUser;
if (user) {
console.log('Active user:', user.npub);
console.log('Profile:', user.profile?.name);
}activePubkey
Get the currently active pubkey.
get activePubkey(): Hexpubkey | undefinedExample:
console.log('Active pubkey:', sessions.activePubkey);NDKSession
Represents an individual user session.
Properties
interface NDKSession {
// User instance
user: NDKUser;
// Signer for this session (undefined for read-only sessions)
signer?: NDKSigner;
// Set of followed pubkeys
followSet?: Set<Hexpubkey>;
// Set of muted items (users, events, words, hashtags)
muteSet?: Set<MuteItem>;
// User's relay list
relayList?: NDKRelayList;
// Blocked relay URLs
blockedRelayUrls?: Set<string>;
// NIP-60 wallet event
wallet?: NDKEvent;
// Additional fetched events by kind
events: Map<NDKKind, NDKEvent>;
}Storage Implementations
LocalStorage
Browser localStorage implementation.
new LocalStorage(key?: string)Parameters:
key?: string- Storage key (default:'ndk-sessions')
Example:
import { LocalStorage } from '@nostr-dev-kit/sessions';
const storage = new LocalStorage('my-app-sessions');FileStorage
Node.js filesystem implementation.
new FileStorage(filePath?: string)Parameters:
filePath?: string- File path (default:'./.ndk-sessions.json')
Example:
import { FileStorage } from '@nostr-dev-kit/sessions';
const storage = new FileStorage('~/.config/myapp/sessions.json');MemoryStorage
In-memory implementation (no persistence).
new MemoryStorage()Example:
import { MemoryStorage } from '@nostr-dev-kit/sessions';
const storage = new MemoryStorage();Custom Storage
Implement the SessionStorage interface for custom storage:
interface SessionStorage {
save(
sessions: Map<Hexpubkey, SerializedSession>,
activePubkey?: Hexpubkey
): Promise<void>;
load(): Promise<{
sessions: Map<Hexpubkey, SerializedSession>;
activePubkey?: Hexpubkey;
}>;
clear(): Promise<void>;
}Example:
class MyCustomStorage implements SessionStorage {
async save(sessions, activePubkey) {
// Save to your backend...
}
async load() {
// Load from your backend...
return { sessions: new Map(), activePubkey: undefined };
}
async clear() {
// Clear from your backend...
}
}
const storage = new MyCustomStorage();
const sessions = new NDKSessionManager(ndk, { storage });Types
Hexpubkey
type Hexpubkey = string;Hex-encoded public key string.
MuteItem
type MuteItem = {
type: 'user' | 'event' | 'word' | 'hashtag';
value: string;
// ... other properties
};Represents a muted item.
SerializedSession
interface SerializedSession {
pubkey: Hexpubkey;
signer?: string; // Serialized signer
followSet?: Hexpubkey[];
muteSet?: MuteItem[];
relayList?: RelayListData;
blockedRelayUrls?: string[];
wallet?: NostrEvent;
events?: [NDKKind, NostrEvent][];
}Serialized session format for storage.
UnsubscribeFn
type UnsubscribeFn = () => void;Function to call to unsubscribe from updates.
Error Handling
The sessions package may throw errors during:
- Login (invalid signer, network errors)
- Storage operations (permissions, disk full)
- Restoration (corrupted data)
Always wrap async operations in try-catch:
try {
await sessions.login(signer);
} catch (error) {
console.error('Login failed:', error);
}
try {
await sessions.restore();
} catch (error) {
console.error('Failed to restore sessions:', error);
}Best Practices
1. Always Call destroy()
// In your cleanup code
sessions.destroy();2. Use autoSave
const sessions = new NDKSessionManager(ndk, {
autoSave: true,
saveDebounceMs: 500
});3. Handle No Active Session
if (!sessions.activeUser) {
// Show login UI
}4. Subscribe to Changes
const unsubscribe = sessions.subscribe((state) => {
// Update UI when sessions change
});5. Security
// ⚠️ NEVER commit .ndk-sessions.json to git!
// Add to .gitignore:
// .ndk-sessions.json
// Use environment variables for sensitive keys
const nsec = process.env.NOSTR_NSEC;