Streakfox
Guides

Action-Based (Cumulative) Streaks

Trigger custom streak actions such as "like" directly from your code.

Action-Based (Cumulative) Streaks

Cumulative streaks increment every time your code reports that a user performed a specific action — for example like, lesson_completed, or quiz_passed.

This guide shows how to trigger streak events from your code using either the global streak() function or the SDK.


1. Embed the widget

Add the script once per page, ideally inside <head>:

<script
  src="https://cdn.streakfox.com/widget.js"
  data-project="YOUR_PROJECT_ID"
  data-event="like"
  defer
></script>

The data-event attribute should match the Action Key you configured in the Streakfox dashboard.

2. Trigger the event from your code

Once the widget script is loaded, a global streak() function is available:

// Trigger the configured action (uses data-event from script tag)
streak();

// Or explicitly specify the action
streak('like');
streak('lesson_complete');
streak('purchase');

React/Vue/Svelte Example

function LikeButton({ postId }: { postId: string }) {
  const handleLike = async () => {
    // Your app logic
    await api.likePost(postId);

    // Record the streak event
    streak('like');
  };

  return <button onClick={handleLike}>Like</button>;
}

TypeScript Support

Add this declaration to your project (e.g., streak.d.ts):

declare global {
  interface Window {
    streak?: (event?: string) => Promise<void>;
  }
}

export {};

Now you can call it type-safely:

await window.streak?.('like');

For React, Next.js, or any app with a build system, use the official SDK for better TypeScript support and more control.

Installation

npm install @streakdev/web
# or
pnpm add @streakdev/web

Recording Events

import { createClient, ensureUserHash, getVisitorId } from '@streakdev/web';

// Create a client instance (do this once, e.g., in a module)
const streakClient = createClient({
  baseUrl: 'https://api.streakfox.com',
});

// Get or create a stable user identifier
const userHash = ensureUserHash(
  undefined, // known hash (if you have one)
  currentUser?.id ?? getVisitorId() // fallback to user ID or anonymous visitor
);

// Record an event
await streakClient.recordEvent({
  projectId: 'YOUR_PROJECT_ID',
  event: 'like',
  userHash,
});

React Hook Example

import { createClient, ensureUserHash, getVisitorId } from '@streakdev/web';
import { useCallback, useMemo } from 'react';

const PROJECT_ID = process.env.NEXT_PUBLIC_STREAK_PROJECT_ID!;

export function useStreak(userId?: string) {
  const client = useMemo(
    () => createClient({ baseUrl: 'https://api.streakfox.com' }),
    []
  );

  const userHash = useMemo(
    () => ensureUserHash(undefined, userId ?? getVisitorId()),
    [userId]
  );

  const recordEvent = useCallback(
    async (event: string) => {
      await client.recordEvent({
        projectId: PROJECT_ID,
        event,
        userHash,
      });
    },
    [client, userHash]
  );

  return { recordEvent };
}

// Usage in a component
function LikeButton() {
  const { recordEvent } = useStreak(user?.id);

  return (
    <button onClick={() => recordEvent('like')}>
      Like
    </button>
  );
}

Option 3: Server-Side Events (For verified users)

For actions that happen on your backend (purchases, completions, etc.), use the SDK from your server:

import { createClient } from '@streakdev/web';

const streakClient = createClient({
  baseUrl: 'https://api.streakfox.com',
});

// In your API handler
export async function handlePurchase(userId: string, orderId: string) {
  // Your business logic
  await processOrder(orderId);

  // Record the streak event with the user's hashed ID
  await streakClient.recordEvent({
    projectId: process.env.STREAK_PROJECT_ID!,
    event: 'purchase',
    userHash: hashUserId(userId), // Use consistent hashing
  });
}

Note: For server-side events, ensure you're using a consistent user identifier hash so events are attributed to the correct user's streak.


Connecting Anonymous to Authenticated Users

When a user signs in, you may want to merge their anonymous streak with their authenticated account. See the Connecting Users guide for details on the aliasUser API.


Verify It Works

  1. Open your site in the browser, perform the action, and watch the widget update.
  2. Check the Streakfox dashboard → Events tab to see the event within a few seconds.
  3. The user's streak count should increase.

Troubleshooting

SymptomPossible Cause & Fix
streak is not definedThe widget script hasn't loaded yet. Wait for DOMContentLoaded or place your code after the script.
Event sent but streak doesn't updateEnsure the event matches your widget's configured action key in the dashboard.
400 INVALID_WIDGET_KINDThe action key doesn't match any widget. Create a cumulative widget with this event in the dashboard.

Next Steps

On this page