Skip to content

About

Gamification for any website. XP, levels, achievements, daily streaks and confetti, from one script tag or one import.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

DopamineJS

Gamification for any website. XP, levels, achievements, daily streaks and confetti, from one script tag or one import.

Live demo: https://baryodev.github.io/dopaminejs/

Course sites, blogs, onboarding flows and community sites all end up building the same thing: points that add up, a level that goes up, a streak that must not break, and something on screen when it happens. Teams write it again each time, usually without the timezone handling that makes streaks correct.

DopamineJS is that piece. Progress is the core, and the visual and audio feedback are parts you can keep, swap or leave out.

What it is for

  • Course and training sites: XP per lesson, achievement unlocks, a daily streak for coming back
  • Blogs and docs: XP when a reader finishes a post, an achievement for finishing a series
  • Product onboarding: setup progress that feels like something rather than a checklist
  • Community and habit sites: streaks kept in the user's own timezone, milestone celebrations
  • Web apps: including the internal tools nobody opens voluntarily
  • Games: the game helpers are in dopaminejs/games

Your code decides when something happened (a lesson done, a post read to the end) and calls addXP or record. DopamineJS does not watch the page for you.

Quick start

npm install dopaminejs
import { RewardSystem, DataService } from 'dopaminejs';

const rewards = new RewardSystem(new DataService());
await rewards.init();

rewards.on('level_up', ({ newLevel }) => showLevelUpToast(newLevel));
rewards.on('achievement_unlocked', (achievement) => showBadge(achievement));

// Somewhere in your app, when the user does the thing you want repeated
await rewards.addXP(250);

const { progress, needed } = rewards.getXPForNextLevel();
// progress: 0.75, needed: 50

That is the whole integration. Persistence is localStorage by default and swappable, streaks are computed in the user's local calendar rather than UTC, and nothing renders until you ask it to.

Want the visuals and sound too. createDopamine builds the parts, wires them to the progress events and installs plugins:

import { createDopamine } from 'dopaminejs';
import 'dopaminejs/style.css';

const dopamine = createDopamine({ plugins: [] });
await dopamine.ready;

await dopamine.progress.addXP(250);   // the bar moves, the sound plays

Each part (ui, particles, sound, haptics) is a value, a factory, or false for none. RewardUI takes a second argument to change its copy and icons:

import { RewardUI } from 'dopaminejs';

new RewardUI(parts, {
    text: { levelUp: 'Level up', achievementUnlocked: 'Unlocked' },
    icons: { streak: '*' },   // a string or a DOM Node (a Node is moved, not copied)
    safeIcons: true,          // the default: string icons become allowlisted SVG or text
    injectCss: false          // true adds the stylesheet from code
});

Importing dopaminejs has no side effects. Import dopaminejs/style.css yourself, or pass injectCss: true.

No build step

The script tag build ships from 3.4.0. It is not on the CDNs for 3.3.0 or earlier.

From 3.4.0, a page with no bundler can load one script. It sets window.Dopamine with the same named exports as the package. Always load an exact version. This is 3.8.0:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dopaminejs@3.8.0/dist/style.css">
<script src="https://cdn.jsdelivr.net/npm/dopaminejs@3.8.0/dist/dopamine.global.js"
        integrity="sha384-dUaLNFGKaZQYdTli6Urq52KXfZpLQOcCfzYrUPvq2v34ysltHJS4MGlCoNeFQBqA"
        crossorigin="anonymous"></script>
<script>
  const rewards = new Dopamine.RewardSystem(new Dopamine.DataService());
  rewards.init().then(() => rewards.addXP(250));
</script>

The integrity value makes the browser refuse a changed file. It belongs to 3.8.0 only; the publish job prints the value for each release. unpkg.com serves the same file.

Celebrate a moment

One call shows a toast, fires confetti and plays a sound. It works with no createDopamine() and no XP bar:

import { celebrate } from 'dopaminejs/celebrate';

celebrate('complete', { title: 'Lesson 3 done', target: button });

Already have a host? Pass its parts and the toast, confetti and sound go through them:

celebrate('complete', { title: 'Lesson 3 done', parts: dopamine.parts });

The presets are complete, milestone, streak and certificate. An unknown preset does nothing. Options are all optional:

  • title, body and icon replace the preset text and icon. Text is set as text. On the standalone route a string icon is text too, and a Node is appended. Through parts a string icon follows safeIcons.
  • target is an element. The confetti starts at its centre. Without one, or if it has no size, it starts at the middle of the viewport.
  • sound is a sound key, or false for none. The default is the preset sound.
  • parts is the host's parts. A part the host does not have (parts: {}, or a host built with ui: false) is skipped, with no standalone fallback. Without parts, celebrate makes its own toast on the first call, a canvas when confetti runs (not under reduced motion) and a sound manager when a sound plays (not with sound: false).

With reduced motion on, there is no confetti. The toast and sound still happen. The setting is read on each call. The standalone toast lasts 3 seconds, and a new call replaces it. Call destroyCelebrations() to remove the toast, its screen reader region, the canvas and the sound manager. celebrate never throws, and errors go to console.error. dopamine.global.js does not include it. dopamine.all.global.js does.

Completion certificate

A modal card the visitor can download as a PNG or print. This one opens when a video ends:

import { showCertificate } from 'dopaminejs/certificate';

const logo = new Image();
logo.src = '/img/acme.png';

video.addEventListener('ended', () => {
    showCertificate({
        title: 'Intro to Gardening',
        recipient: 'Ana Reyes',
        date: 'Nov 25, 2026',
        issuer: 'Acme Academy',
        logo
    });
});

celebrate can open it after the confetti. The certificate code loads on demand, so a page that never shows one does not download it:

import { celebrate } from 'dopaminejs/celebrate';

celebrate('certificate', { certificate: { title: 'Intro to Gardening', recipient: 'Ana Reyes' } });
  • title, recipient, date and issuer are set as text, so a name from a CMS cannot inject HTML. Long text wraps, and past a few lines it ends with an ellipsis, in the card and in the PNG.
  • logo is a string or an image. A string follows safeIcons as an achievement icon does: text or allowlisted SVG by default, HTML only with showCertificate(fields, { safeIcons: false }). An HTMLImageElement is moved in, never parsed, and goes back to its place in the page, with its own style, when the certificate closes.
  • Download draws the card on a canvas and saves certificate.png. If the logo is from another origin the canvas cannot be exported, so the PNG is saved without the logo and console.warn says so once. A logo that has not loaded is dropped from the PNG the same way.
  • The PNG takes a plain colour from --dopamine-toast-bg (anything the canvas accepts as a colour) and draws a gradient as its default purple background.
  • fields must be an object; anything else logs a warning and opens nothing.
  • Print calls window.print() with a print style that shows only the certificate.
  • It is a dialog (role="dialog", aria-modal, labelled by the title) with focus kept inside. Escape, Close or a click outside closes it and focus goes back to where it was. One certificate is open at a time. destroyCertificate() closes it and removes its DOM, print style and listeners. destroyCelebrations() does not.
  • Colours come from the --dopamine-toast-* variables (bg, text, muted, accent, radius, shadow). The PNG reads them too; a gradient bg is drawn as the default purple gradient.
  • Not in dopamine.global.js. dopamine.all.global.js has it.

Rewards from HTML attributes

dopaminejs/auto reads data-dopamine-* attributes and awards XP, unlocks achievements, celebrates and shows a certificate when something happens on the page. A writer who can edit HTML can wire a reward with no JavaScript of their own.

<video src="lesson.mp4" controls
       data-dopamine-on="ended" data-dopamine-xp="50" data-dopamine-celebrate="complete"></video>

<button data-dopamine-on="click" data-dopamine-xp="5">Mark as done</button>

<article data-dopamine-on="read" data-dopamine-achievement="first_game"
         data-dopamine-certificate-title="Intro to Gardening"
         data-dopamine-certificate-recipient="Ana Reyes">...</article>

With a bundler, build a host and pass it in:

import { createDopamine } from 'dopaminejs';
import { auto } from 'dopaminejs/auto';

const host = createDopamine();
auto({ host });

With no build step, load dopamine.all.global.js and add data-dopamine-auto to the script tag. It holds the main entry, celebrate, the certificate and auto, and window.Dopamine has all of them. This is 3.8.0:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dopaminejs@3.8.0/dist/style.css">
<script src="https://cdn.jsdelivr.net/npm/dopaminejs@3.8.0/dist/dopamine.all.global.js"
        integrity="sha384-MAjfDgRBUHoYdY5AFqXdS0IVb3+tb5CvBl8cnhAF/iYaTxOsgot8vY7C0Ch1gj8D"
        crossorigin="anonymous" data-dopamine-auto></script>

The integrity value belongs to 3.8.0 only. The tag can go in <head> with no defer: it waits for the body. Include it once, because each copy builds its own host. Without data-dopamine-auto, loading the file changes nothing. For achievements your page defines or other options, skip the attribute and call Dopamine.auto({ host }) with your own Dopamine.createDopamine({ ... }).

auto({ host, root?, maxXP? }):

  • host is a createDopamine() result. Without it, auto throws a TypeError. destroyAuto() never disposes it.
  • root is a Document or Element, default document. Every listener and observer attaches to it.
  • maxXP is the largest XP an attribute may award, default 1000.

Attributes:

  • data-dopamine-on is one of click, submit, ended, read or visible. read fires when the end of the element scrolls into view, using a one pixel invisible <span data-dopamine-sentinel> added as its last child and moved back to the end when the children change. So read needs an element that holds children, the old last child no longer matches :last-child, and in a flex or grid container the sentinel is an item. visible fires when the element does.
  • data-dopamine-xp is a whole number written in digits, such as 25. Anything else (-5, 5.5, 1e3, 0x10) or a number over maxXP is ignored with one console.warn. 0 does nothing.
  • data-dopamine-achievement is an achievement id the host has. An unknown id is ignored with a warning.
  • data-dopamine-celebrate is a celebrate preset: complete, milestone, streak or certificate. Any other value is ignored with a warning, and certificate attributes on the same element still open the certificate.
  • data-dopamine-certificate-title, -recipient, -date, -issuer and -logo open a certificate, after the celebration if there is one.
  • data-dopamine-repeat lets the element fire every time.

The XP, achievement and celebrate values are trimmed; data-dopamine-on and the certificate fields are used as written. Each element warns at most once, for the first bad value it has. Put click on the control itself, not on a <label>: a click on a label also clicks its control, so a label with data-dopamine-repeat awards twice. Click and submit are heard in the capture phase at the root, so a handler on the element or inside it that stops the event does not stop the reward. A capture listener on window that stops it still does. Elements inside a shadow root are not seen.

Each element fires once per page load, even if destroyAuto() and auto() run in between. With data-dopamine-repeat it fires on each click, and each time it enters the viewport again. Elements added to or removed from the page later are picked up. A changed attribute is not watched. Where there is no IntersectionObserver, read and visible are skipped with one warning and the other triggers still work. destroyAuto() removes the listeners, observers and sentinels.

Why streaks are the hard part

A daily streak is a calendar question, not a clock question. "Did they come back yesterday" depends on the user's timezone, and a naive Date comparison breaks for anyone not on UTC, silently, for a subset of users you will never hear from.

DopamineJS resolves streak boundaries in local time and the test suite is pinned to a non-UTC zone so a regression fails CI instead of passing quietly on a UTC runner.

πŸ“¦ Packages

Core Package (MPL-2.0)

npm install dopaminejs

The core with:

  • TypeScript declarations included, no @types package needed
  • createDopamine with swappable parts and a plugin contract
  • Default parts (DOM overlay, Canvas particles, Web Audio)
  • Reward system (XP, levels, achievements, streaks)

License: MPL-2.0 (copyleft for core improvements)


Plugin Packages (MIT)

Install only what you use. Each plugin is its own package.

Package Provides
dopaminejs-plugin-webgl-particles webglParticles() - a GPU particle part
dopaminejs-plugin-howler-audio howlerSound() - a sound part on Howler.js
dopaminejs-plugin-sound-packs soundPack(name) - retro, modern, cute, scifi
dopaminejs-plugin-ecosystem webhooks() - signed event webhooks with a queue
dopaminejs-plugin-debug-overlay debugOverlay() - live snapshot and event log
npm install dopaminejs-plugin-webgl-particles

Coming from 2.x? See docs/MIGRATION-3.0.md.

License: MIT (use freely, even commercially)


Themes Package (MIT)

npm install dopaminejs-themes

UI themes:

  • Modern, Dark Cyberpunk, Neon, Retro, Cute
  • Each theme sets --dopamine-* CSS variables on the document root
  • The core stylesheet does not read those variables yet. Use them in your own CSS.

License: MIT (use freely, even commercially)


React Package (MIT)

npm install dopaminejs dopaminejs-react

RewardsProvider and the useRewards() hook. Needs react 18 or newer and dopaminejs 2.3.0 or newer. See packages/dopaminejs-react/README.md.


Vue Package (MIT)

Not on npm yet. provideRewards() and the useRewards() composable for Vue 3.3 or newer, with dopaminejs 2.3.0 or newer. See packages/dopaminejs-vue/README.md.


React Native, Expo and other non-browser runtimes

dopaminejs/core exports only the progression API: RewardSystem, DataService, EventEmitter, DopamineError, merge, validate, createMemoryStorage and resolveStorage. It has no UI, particles or sound, and nothing in it touches window, document or localStorage at import time. Only the default-storage fallback (resolveStorage) probes localStorage, so pass storage outside a browser. CI imports the built output in plain Node with those globals unset and runs init and record (scripts/check-core-import.js).

The entry resolves only through the exports field of package.json. Metro honours it by default from React Native 0.79 and Expo SDK 53. Older versions need config.resolver.unstable_enablePackageExports = true in metro.config.js.

DataService awaits every storage call, so AsyncStorage works as is:

import AsyncStorage from '@react-native-async-storage/async-storage';
import { RewardSystem, DataService } from 'dopaminejs/core';

const rewards = new RewardSystem(new DataService({ storage: AsyncStorage }));
rewards.on('level_up', ({ newLevel }) => console.log(`Level ${newLevel}`));
await rewards.init();

await rewards.record('quiz', { score: 80, won: true });

Any object with promise-returning getItem, setItem and removeItem works the same way.

If the saved player cannot be read (getItem throws or rejects), init() still resolves with a new player in memory, fires load_failed with reason: 'read', and saves nothing for the rest of the session (until init() reads it or reset() is called), so the real player is never overwritten. Storage is read again before a blocked save, at most once every loadRetryMs (default 30000, an option on createDopamine and RewardSystem). When that read works and returns a player, the progress made this session is merged into it and saved, loadFailed goes back to false and load_recovered fires with { key: 'player' }. If the read fails again, or the value is not a player, nothing is saved and the session keeps its progress. An import while saves are blocked is treated as already stored progress. If the device id is only found at the retry and the session already holds entries under it, saves stay blocked; reset({ overwrite: false }) ends that and keeps the stored player (it drops this session's progress), while reset() with no option replaces the stored player with no backup, and an init() that fails again stays blocked. Calling init() again also retries; one that fails again keeps the progress made in memory. Two tabs that both recover each merge their own session once; nothing links the two. Rules are in spec/README.md. If the saved value is not valid JSON, it is kept under the player_corrupt key as a JSON string (JSON.parse it once to get the original), load_failed fires with reason: 'corrupt', and a new player starts. If that backup cannot be written, backedUp is false and nothing is saved this session. A data service that overrides load must pass the third argument ({ strict: true }) on, or a failed read looks like an empty one. rewards.loadFailed is true after a failed read, and the React and Vue packages expose it as loadFailed. Show the visitor that progress is not being kept when it is. A failed write fires save_failed.

merge(a, b) joins two saves of the same player into one, in any order, so a server can merge saves without a browser. rewards.export() gives the saved document and rewards.import(doc) merges one in. await rewards.reset() replaces the player with an empty one (for a new account on a shared device), keeps the device id, saves, and resolves the new snapshot. It emits player_reset after the save, and it writes even after a failed load, so the stored player is replaced and loadFailed goes back to false. It does not back up the save it replaces. Call it after init() has resolved, not while init() is pending. A record() already in flight when it runs lands in the new player. Called from inside a hook, the write happens when the outer record or unlock finishes.

Without a storage option, DataService falls back to localStorage if present, then to memory, so state is lost when the app closes. RewardUI, ParticleSystem and SoundManager are web only and stay on the root dopaminejs entry.


Plugins

A subscriber plugin is { name, version, api: 3, install(ctx) } and install returns a disposer. Parts and middleware are the other two shapes. See docs/PLUGIN_GUIDE.md.


πŸ—οΈ Development

This is a monorepo using npm workspaces:

# Install all dependencies
npm install

# Build all packages
npm run build

# Test all packages
npm run test

# Work on specific package
cd packages/dopaminejs
npm run dev

🚒 Releasing

Publishing is automated. There is no manual npm publish step and no npm token in this repository; GitHub Actions authenticates via npm Trusted Publishing (OIDC), which also attaches a provenance attestation to every release.

  1. Bump the version of each package you want to publish.
  2. Update CHANGELOG.md.
  3. Tag with the core package's version and push:
git tag v2.1.0
git push origin v2.1.0

The Publish workflow (.github/workflows/publish.yml, the filename npm's Trusted Publisher config is pinned to) verifies manifests, runs the tests, builds every package, checks the tag matches dopaminejs's version, then publishes only those packages whose version is not already on npm. Re-running after a partial failure is safe: already-published packages are skipped.

To preview without publishing, run the workflow manually from the Actions tab with dry run left checked.

If a publish fails with ENEEDAUTH, run the workflow manually with dry run checked. That runs a per-package OIDC diagnostic and prints the registry's actual response, which npm publish hides:

  • HTTP 201 - trusted publishing is configured correctly for that package
  • HTTP 404 "package not found" - no Trusted Publisher record exists for that package name, even though the package itself is on npm. Configure it at npmjs.com/package/<name>/access.

The filename publish.yml is load-bearing. npm matches the OIDC request against the exact workflow filename registered on each package's Trusted Publisher config, so renaming this file breaks publishing until all eight packages are reconfigured on npmjs.com.


πŸ“ Licensing

Why Different Licenses?

  • Core (MPL-2.0): Ensures improvements to the core are shared back
  • Plugins/Themes (MIT): Maximum freedom for extensions and customization

Can I use this commercially?

Yes! Both MPL-2.0 and MIT allow commercial use:

  • MPL-2.0: You can use the core in commercial projects. If you modify the core files, share those modifications.
  • MIT: Plugins and themes have zero restrictions.

πŸ”— Links


πŸ“„ License

  • dopaminejs: MPL-2.0
  • dopaminejs-themes: MIT
  • dopaminejs-plugin-*: MIT

See individual package LICENSE files for details.

About

Gamification for any website. XP, levels, achievements, daily streaks and confetti, from one script tag or one import.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages