npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@refrefhq/better-auth

v0.1.1

Published

Better Auth plugin for RefRef: track signups and referrals from your projects that use Better Auth.

Readme

@refrefhq/better-auth

The RefRef plugin for Better Auth. It sends the signup of each new account to RefRef and connects it to the browser's referral click at the moment of account creation. It needs no client secret, signs nothing, and stores nothing in your database. Add the landing script to the pages where a referral link lands; it keeps the browser's referral handle in the refref_handle cookie.

The setup guide is refref.ai/docs/platform/better-auth.

Install

npm install @refrefhq/better-auth

better-auth 1.7.6 or later is a peer dependency. Node.js ^20.19.0 || >=22.12.0 is required.

Use

import { betterAuth } from "better-auth";
import { refrefAnalytics } from "@refrefhq/better-auth";

export const auth = betterAuth({
  // ...your configuration
  plugins: [
    refrefAnalytics({
      apiUrl: "https://api.refref.ai",
      apiKey: process.env.REFREF_API_KEY!,
      projectId: process.env.REFREF_PROJECT_ID!,
      resolveSignup: async ({ user }) => ({
        participant: { kind: "individual", externalId: user.id },
        actor: { kind: "individual", externalId: user.id },
      }),
    }),
  ],
});

apiUrl is required. Keep the API key on your server. The resolver names the participant of the signup by its kind and the tenant's external ID: the user, or a group such as the user's workspace. The plugin does not assume that the user is the participant. Return the same participant for every call about one user. The actor is optional and is always an individual. The plugin adds the Project, occurredAt (the creation time of the account or the organization, unless the resolver gives one), and identify. A signup needs no sourceEventId: RefRef derives one key for each participant, so a repeated signup converges (API).

Milestones

| milestone | At the creation of the account | Later | | --------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | account-created (default) | One signup with identify: { handle } | Nothing | | email-verified | POST /v1/identify { handle, reference }; no signup | At the first verified state of the email, the signup, with occurredAt = the account creation (below) | | group-created | Nothing | At /organization/create of the organization plugin, the signup of the group with the creator's handle; members never identify |

  • In email-verified mode, an account that is verified when it is created signs up at once, in one call: a social account with a verified email, a magic link, or an email code. A later verification of the same user, for example after an email change, sends the same signup again, and RefRef keeps the first.
  • In group-created mode, the resolver gets organization (id, name, slug) and the creator as user (id). It names the group participant. The mode does not check the creator's email. To count only groups of verified creators, set emailAndPassword.requireEmailVerification, so that an email and password user signs in, and can create an organization, only after the verification.

Accounts that another person created

Anyone can create an account with an email that is not theirs. The owner of the email can later take the account over: Better Auth then removes the access that was created before the proof (a magic link or an email sign-in code), or the owner resets the password.

  • In email-verified mode, the creation identifies the creating browser to a reference, not to the participant. Its key is an HMAC, with the Better Auth secret, of the user ID, the email, and the password hash of the credential account. Only the creator's own verification resolves it: /verify-email or /email-otp/verify-email, before the signup, while the password is the one of the creation, within 30 days. When another proof verifies the email (/magic-link/verify, /sign-in/email-otp, or /email-otp/reset-password), the plugin sends the signup with the handle of the browser that gives the proof, and the creating browser counts for nobody. A password reset before the verification also stops the creating browser from counting. So the creator loses the click when it signs in with a magic link or resets its password before it verifies.
  • In account-created mode, the creation is the signup, and it identifies the creating browser to the participant at once. If the owner of the email takes the account over later, the participant keeps the referral of the browser that created the account. Use email-verified for a Project that pays referrer Rewards.

Which requests identify

  • The plugin uses the user.create.after database hook, so every creation method identifies: email and password, social sign-up, magic link, email code, or another plugin.
  • Only a creation request with a refref_handle cookie that holds a handle ID identifies. A request without it, such as a creation that your backend makes, identifies nothing. A request of a signed-in user, such as an admin who creates an account for another person, identifies nothing.
  • A user of the Better Auth anonymous plugin (isAnonymous) identifies nothing and sends no signup: an anonymous session is not an account creation. A request with an anonymous session still counts as a visitor, so the real account that the person later creates identifies the browser's handle.
  • Sign-in, the creator's verification, account linking, and joining an organization never identify. In email-verified mode, a proof that takes over an account that another person created identifies the browser that gives it (above).

Magic link and email code on another device

A person can ask for a magic link or an email code in one browser and complete it on another device. Then the creation request does not have the starting browser's cookie, so the plugin uses a reference:

  1. When /sign-in/magic-link or /email-otp/send-verification-otp (type sign-in) makes a challenge for an email that has no account, the plugin identifies the browser's handle to reference: { key }. The key is an HMAC-SHA256, with the Better Auth secret, of the stored magic-link token, or of the email code and its identifier. It never leaves your server, and it shows RefRef no token, code, or email.
  2. When /magic-link/verify or /sign-in/email-otp consumes the challenge and creates the account, the plugin resolves the reference to the participant first. Then it sends the signup with the handle of the browser that completes the flow. So the starting browser's click counts on any device, and a completion in the starting browser identifies the same handle again.

The reference expires 24 hours after the first call (the RefRef default); the challenge expires earlier. Limits:

  • A handle is identified once. A resend makes a new challenge, and the handle stays with the first one: the click counts only when the person completes the first link or code. An earlier magic link stays valid until it expires; an earlier code does not.
  • The plugin sees a consumed challenge only through the delete hook of a verification row in the database. With secondaryStorage and without verification.storeInDatabase, the plugin uses no reference; a completion in the starting browser still identifies at creation.
  • With emailOTP({ resendStrategy: "reuse" }), Better Auth gives the code of the first request to every browser that asks for one while it is valid, so the code does not belong to one browser. The plugin then uses no reference for email codes; magic links keep theirs, and a code that completes in the browser that asked for it still identifies that browser at creation.
  • group-created mode uses no reference.

Server-set cookie

Safari keeps a cookie that a script writes for 7 days only. POST <basePath>/refref/handle (auth.api.refreshRefRefHandle) sets refref_handle again from the server, with the value that the request carries: Path=/, Max-Age 90 days, SameSite=Lax, Secure when the Better Auth base URL uses HTTPS, not HttpOnly (the landing script must read it), and Domain. The Domain is the cookieDomain option, or else the registrable domain of the Better Auth base URL (app.example.co.uk gives example.co.uk), which is the domain that the landing script uses by default. When the landing script sets data-cookie-domain, give cookieDomain the same value. The response is { handle }, or { handle: null } when the request has no handle ID; then the endpoint sets no cookie. It never creates or changes a handle. Call it after capture, on the host of the auth server:

await window.RefRefAttribution.capture();
await fetch("/api/auth/refref/handle", { method: "POST" });

Failures and retries

  • Sign-up never fails because of RefRef. The calls of one moment run in order, after Better Auth commits the user. With advanced.backgroundTasks.handler, they run in the background; otherwise the request waits for them.
  • Each call is tried up to three times when it gets no response, a timeout (3 seconds), a 429, or a 5xx status, after 100 ms and 400 ms. Every call is safe to repeat: a handle is identified once, a reference resolves once, and a repeated signup converges.
  • An identification that RefRef refuses with 404 or 409 (a cookie value that is not a handle of the Project, a handle that is already identified, or an expired reference) identifies nothing and is no error. On a signup, RefRef answers with identified: false instead.
  • A signup never waits for a later identification. So when the resolve of a reference fails after its retries, the plugin does not send the signup of that moment: onError gets the identify delivery and then the signup delivery, with the same error. Send them again in that order, so the signup sees the starting browser's click.
  • onError(error, delivery) gets every other failure. The default logs it with the Better Auth logger. error is a RefRefAPIError with status and code of the error body when RefRef answered. Keep delivery to send it again later with RefRefAPIClient.deliver(delivery). When the resolver throws, delivery is undefined. This plugin is not a durable outbox.

RefRefAPIClient also sends a canonical purchase with trackPurchase (type: "purchase", exact integer minor units) and an identification with identify (POST /v1/identify). It validates each body before it sends it.

License

MIT