Skip to content
LogoLogo

Plugins

A plugin adds a namespace of actions to the instance, and runs code at the instance's sign-in and sign-out.

Overview

Each sign-in method and each set of actions of the package is a plugin, such as dialog and viem. An app writes a plugin of its own with Plugin.from, as the built-in plugins do. Its actions share the instance's configuration and session, and its hooks run at the instance's sign-in and sign-out.

The plugin's id names its namespace on the instance, such as accounts.analytics. The instance's type holds the namespace and each action, inferred from the plugin, so an app declares no types for it.

The demo adds an analytics plugin. Its action tracks an event of the signed-in user, and its hooks track each sign-in and sign-out.

Track events with a pluginDemo

Walkthrough

These steps add an analytics plugin to a React app.

Install the packages

Define the plugin

A function takes the plugin's options and returns the plugin, as each built-in plugin does. id names the namespace. actions runs once at Accounts.create, and returns the namespace.

Each action reads the instance through the context that actions receives. track attaches the instance's chain and the signed-in user's ID to each event.

analytics.ts
import { Plugin } from 'accounts'
 
export function analytics(options: analytics.Options) {
  const { send } = options
 
  return Plugin.from({
    actions: (context) => ({
      track: (name: string) =>
        send({
          chainId: context.chain.get(),
          name,
          userId: context.session.get()?.user?.id,
        }),
    }),
    id: 'analytics',
  })
}
 
export declare namespace analytics {
  type Event = {
    chainId: number
    name: string
    userId?: string | undefined
  }
 
  type Options = {
    send: (event: Event) => void
  }
}

If an id names a member of every instance, such as session, or the id of another plugin, Accounts.create throws. A plugin with the id of a sign-in plugin, such as dialog, replaces the default dialog plugin.

Track sign-ins and sign-outs

afterSignIn runs after each change that sets a session, with the session. afterSignOut runs after each sign-out. Both also run after a sign-in or a sign-out in another tab, or in another instance on a store with connect, such as Store.memory in React Native or Node.

The sign-in waits for each afterSignIn hook, so the hook sends the event without an await.

analytics.ts
import { Plugin } from 'accounts'
 
export function analytics(options: analytics.Options) {
  const { send } = options
 
  return Plugin.from({
    actions: (context) => ({
      track: (name: string) =>
        send({
          chainId: context.chain.get(),
          name,
          userId: context.session.get()?.user?.id,
        }),
    }),
    hooks: {
      afterSignIn: (context, session) =>
        send({
          chainId: context.chain.get(),
          name: 'signIn',
          userId: session.user?.id,
        }),
      afterSignOut: (context) =>
        send({ chainId: context.chain.get(), name: 'signOut' }),
    },
    id: 'analytics',
  })
}
 
export declare namespace analytics {
  type Event = {
    chainId: number
    name: string
    userId?: string | undefined
  }
 
  type Options = {
    send: (event: Event) => void
  }
}

Add the plugin to the instance

send posts each event to the app's API with navigator.sendBeacon, which returns before the request completes.

import { Accounts } from 'accounts'
import { react } from 'accounts/react'
import { analytics } from './analytics.js'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  plugins: [
    react(),
    analytics({
      send: (event) => {
        navigator.sendBeacon('/api/events', JSON.stringify(event))
      },
    }),
  ],
})

Call the action

The instance holds the plugin's namespace under its id, so accounts.analytics.track sends an event.

import { accounts } from './tempo.config.js'
 
export function App() {
  const { session } = accounts.useSession()
 
  if (!session)
    return (
      <button onClick={() => accounts.dialog.signIn()} type="button">
        Sign in
      </button>
    )
 
  return (
    <button
      onClick={() => accounts.analytics.track('checkout.start')}
      type="button"
    >
      Check out
    </button>
  )
}

Use cases

Each use case sets an option of Plugin.from, or passes plugins to Accounts.create.

Run code at creation

setup runs once at Accounts.create, after the plugin's actions. This plugin subscribes to the instance's chain with context.chain.subscribe, and tracks each switchChain.

chains.ts
import { Plugin } from 'accounts'
 
export function chains(options: chains.Options) {
  const { send } = options
 
  return Plugin.from({
    id: 'chains',
    setup: (context) => {
      context.chain.subscribe((chainId, previous) => send({ chainId, previous }))
    },
  })
}
 
export declare namespace chains {
  type Options = {
    send: (event: { chainId: number; previous: number }) => void
  }
}

Add members to the instance

extend adds members to the instance itself, beside its namespaces. It receives the instance, so a member calls the instance's own members, such as session.fetch. If a member's name is a member of the instance already, Accounts.create throws.

import { Plugin } from 'accounts'
 
export function api(options: api.Options) {
  const { url } = options
 
  return Plugin.from({
    extend: (instance) => ({
      api: (path: string) =>
        instance.session.fetch({ url: new URL(path, url).href }),
    }),
    id: 'api',
  })
}
 
export declare namespace api {
  type Options = {
    url: string
  }
}

Set options of the instance

config returns options of Accounts.create, such as the redirectUri of a platform. The options that Accounts.create receives win over them, and a later plugin's options win over an earlier plugin's.

platform.ts
import { Plugin } from 'accounts'
 
export function platform(options: platform.Options) {
  const { redirectUri } = options
 
  return Plugin.from({
    config: () => ({ redirectUri }), 
    id: 'platform',
  })
}
 
export declare namespace platform {
  type Options = {
    redirectUri: string
  }
}

Combine plugins in a preset

An entry of plugins can be a list of plugins, such as the list that a preset returns. Plugin.Option types each entry. Accounts.create flattens each list in order, and the instance's type holds the namespace of each plugin.

import { Plugin } from 'accounts'
import { redirect, viem } from 'accounts/plugins'
 
export function preset(options: preset.Options) {
  const { redirectUri } = options
 
  return [
    Plugin.from({ config: () => ({ redirectUri }), id: 'preset' }),
    redirect(),
    viem(),
  ] satisfies readonly Plugin.Option[]
}
 
export declare namespace preset {
  type Options = {
    redirectUri: string
  }
}

Add a plugin conditionally

A falsy entry of plugins adds nothing, so enabled && analytics() adds the plugin only while enabled holds.

tempo.config.ts
import { Accounts } from 'accounts'
import { analytics } from './analytics.js'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  plugins: [
    import.meta.env.PROD &&
      analytics({
        send: (event) => {
          navigator.sendBeacon('/api/events', JSON.stringify(event))
        },
      }),
  ],
})

Leave out the default plugins

The instance of accounts adds the dialog, funding, and mpp plugins that plugins lacks. accounts/lite exports the same modules, and its Accounts.create adds none of them, so the bundle holds only the plugins that the app names.

tempo.config.ts
// [!code hl:next]
import { Accounts } from 'accounts/lite'
import { dialog } from 'accounts/plugins'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  plugins: [dialog()],
})

Next steps