Skip to main content

Anon Frontend SDK

The @anon-dot-com/frontend package provides a lightweight JavaScript library for embedding the Anon Link directly into your web application. This SDK handles link token authentication, link status checking, and provides seamless integration through a secure iframe modal.

Overview

The SDK creates a responsive iframe modal that displays the Anon Link interface within any web application. It provides event-driven communication and handles the complete link lifecycle using a secure token-based authentication flow.

Install the Package

You can install the package using your preferred package manager:
npm install @anon-dot-com/frontend

Quick Start

Basic Integration

The SDK provides two main methods for integrating the Anon Link:
import { init } from '@anon-dot-com/frontend';

// Initialize the Anon Link (finds existing link instance)
await init({
  onEvent: (event) => {
    console.log('Link event:', event);
  }
});

Advanced Configuration

Configure the link with additional options for more control over the link process:
import { start } from '@anon-dot-com/frontend';

// Get link token from your backend
const linkToken = await fetch('/api/anon/link-token', {
  method: 'POST',
  body: JSON.stringify({
    external_id: 'customer_12345',
    job_id: ['550e8400-e29b-41d4-a716-446655440000']
  })
}).then(res => res.json()).then(data => data.link_token);

await start({
  linkToken: linkToken,
  target: '#link-container', // Custom target element
  baseURL: 'https://worker.anon.com', // Optional: Override base URL
  onEvent: (event) => {
    switch (event.event.type) {
      case 'link.opened':
        console.log('Link opened:', event.event.data);
        break;
      case 'link.closed':
        console.log('Link closed:', event.event.data);
        break;
      case 'job_run.completed':
        console.log('Job run completed:', event.event.data);
        break;
      case 'job_run.failed':
        console.log('Job run failed:', event.event.data);
        break;
    }
  }
});

Global Script Usage

If you’re not using a module bundler, include the library as a global script:
<script src="https://cdn.jsdelivr.net/npm/@anon-dot-com/frontend/index.umd.js"></script>
<script>
  // First get link token from your backend
  fetch('/api/anon/link-token', {
    method: 'POST',
    body: JSON.stringify({
      external_id: 'customer_12345',
      job_id: ['550e8400-e29b-41d4-a716-446655440000']
    })
  })
    .then(res => res.json())
    .then(data => {
      // Initialize the Anon Link (finds existing link instance)
      window.Anon.init({
        onEvent: (event) => {
          console.log('Link event:', event);
        }
      });
    });
</script>

API Reference

Methods

Initializes the SDK and finds any existing link instance for the user. This method checks localStorage for previous link options and attempts to continue an existing link session if found.Parameters:
  • options: Configuration object of type AnonInitOptions
Returns:
  • Promise that resolves with link metadata if an existing link is found, or undefined
Creates a new link session and immediately shows the iframe modal. This method requires a link token obtained from your backend.Parameters:
  • options: Configuration object of type AnonLinkOptions
Returns:
  • Promise that resolves when the link session is started

Configuration Options

AnonInitOptions

The AnonInitOptions interface accepts the following properties:
PropertyTypeRequiredDescription
onEvent(event: EventData) => voidNoCallback for link events
targetstringNoCSS selector for target element (defaults to “body”)
baseURLstringNoBase URL for API requests (defaults to “https://worker.anon.com”)

AnonLinkOptions

The AnonLinkOptions interface extends AnonInitOptions and accepts additional properties:
PropertyTypeRequiredDescription
linkTokenstringYesLink token obtained from your backend’s /api/v2/link/token endpoint

Event Structure

The onEvent callback receives events with the following structure:
type AnonEventData = {
  source: 'anon_modal';
  event: {
    type: string;
    data: any;
  };
};
Common event types include link.opened, link.closed, job_run.completed, job_run.failed, workflow_run.completed, and workflow_run.failed.

Authentication Flow

Your backend must generate a link token that the SDK uses to authenticate. Your backend must implement an endpoint that generates link tokens:
// /api/anon/link-token/route.ts
export async function POST(request: Request) {
  const { external_id, job_id } = await request.json();
  
  const response = await fetch('https://worker.anon.com/api/v2/link/token', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.ANON_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      external_id,
      job_id
    })
  });

  const data = await response.json();
  return Response.json(data);
}
Link tokens are short-lived (60 seconds) and single-use for security.
The SDK automatically persists link state in the browser’s localStorage. When you call init(), it checks for any existing link options and attempts to continue where the user left off.
import { init, start } from '@anon-dot-com/frontend';

// On page load, check for existing link
const existingLink = await init({
  onEvent: (event) => console.log('Link event:', event)
});

if (!existingLink) {
  // No existing link found, user can start a new one
  document.getElementById('start-link').addEventListener('click', async () => {
    const linkToken = await fetch('/api/anon/link-token', {
      method: 'POST',
      body: JSON.stringify({
        external_id: 'customer_12345',
        job_id: ['550e8400-e29b-41d4-a716-446655440000']
      })
    })
      .then(res => res.json())
      .then(data => data.link_token);
    
    await start({
      linkToken: linkToken
    });
  });
}

Architecture Flow

The following diagram illustrates the authentication flow:

Backend Requirements

Required Endpoints

Your backend needs to implement the following endpoint:
EndpointMethodPurpose
/api/anon/link-tokenPOSTGenerate a link token for frontend authentication

Security Considerations

  • Store your Anon API key securely in environment variables
  • Implement proper authentication/authorization for the link token endpoint
  • Consider rate limiting the link token endpoint to prevent abuse
  • Link tokens are short-lived (60 seconds) and single-use for security
Never expose your Anon API key in client-side code. The token-based flow eliminates the need for a catch-all proxy while maintaining security.

Event Handling

The SDK provides comprehensive event handling for link lifecycle events:
import { start } from '@anon-dot-com/frontend';

await start({
  linkToken: linkToken,
  onEvent: (event) => {
    // Always verify the event source
    if (event.data?.source !== 'anon_modal') return;

    const linkEvent = event.data.event;
    if (!linkEvent) return;

    switch (linkEvent.type) {
      case 'link.opened':
        console.log('Link opened by user');
        break;
      case 'link.closed':
        console.log('Link closed by user');
        break;
      case 'job_run.created':
        console.log('Job run created:', linkEvent.data);
        break;
      case 'job_run.completed':
        console.log('Job run completed:', linkEvent.data);
        // Poll artifacts API or wait for webhook
        break;
      case 'job_run.failed':
        console.log('Job run failed:', linkEvent.data);
        break;
      case 'workflow_run.started':
        console.log('Workflow run started:', linkEvent.data);
        break;
      case 'workflow_run.completed':
        console.log('Workflow run completed:', linkEvent.data);
        break;
      case 'workflow_run.failed':
        console.log('Workflow run failed:', linkEvent.data);
        break;
      default:
        console.log('Unknown event type:', linkEvent.type);
    }
  }
});

Migration from v1

If you’re migrating from v1 SDK:

Before (v1)

import { init, startModal } from '@anon-dot-com/frontend';

await init({
  onEvent: (event) => console.log('Event:', event)
});

await startModal({
  userId: 'user@example.com',
  linkToken: linkToken
});

After (v2)

import { init, start } from '@anon-dot-com/frontend';

await init({
  onEvent: (event) => console.log('Event:', event)
});

await start({
  linkToken: linkToken // No userId needed - external_id is in link token
});

Breaking Changes

  • startModal() has been renamed to start()
  • userId parameter is no longer needed; external_id is included in the link token
  • Event types have changed: migration_modal.* events are now link.*, job_run.*, and workflow_run.*
  • API endpoint changed from /api/v1/link-token to /api/v2/link/token
  • Link token request now requires external_id and job_id instead of just user context

Next Steps

Embedding Link

Learn more about embedding the Anon Link in your application

Webhooks

Set up webhooks to receive link and job run status updates

Sending Links

Learn about creating and sending links via email or SMS

API Reference

Explore the complete Anon API documentation