Getting Started with QueueSaaS TypeScript SDK - QueueSaaS Blog
Relay
QueueSaaS Team

Getting Started with QueueSaaS TypeScript SDK

Learn how to integrate QueueSaaS into your TypeScript or JavaScript projects with our official SDK. Send messages, schedule tasks, and build reliable serverless applications.

typescript sdk getting-started tutorial

Getting Started with QueueSaaS TypeScript SDK

The QueueSaaS TypeScript SDK provides a type-safe, developer-friendly interface to our HTTP-based message queue service. Whether you’re building a Next.js application, a Node.js API, or a serverless function, the SDK makes it easy to send messages, schedule tasks, and manage your queues.

Installation

Install the SDK using your preferred package manager:

npm install @anlyonhq/scheduler
# or
pnpm add @anlyonhq/scheduler
# or
yarn add @anlyonhq/scheduler

Quick Start

1. Initialize the Client

import { Client } from '@anlyonhq/scheduler';

const client = new Client({
  apiKey: process.env.ANLYON_API_KEY!,
});

2. Send Your First Message

// Send a message immediately
const result = await client.messages.publish({
  url: 'https://api.example.com/webhook',
  method: 'POST',
  body: { event: 'user.created', userId: '123' },
});

console.log(`Message published: ${result.data.messageId}`);

3. Schedule a Delayed Message

// Send a message 60 seconds from now
const result = await client.messages.publish({
  url: 'https://api.example.com/webhook',
  method: 'POST',
  body: { event: 'reminder', message: 'Don\'t forget!' },
  executeAt: Math.floor(Date.now() / 1000) + 60, // Unix timestamp
});

Using the Fluent Builder API

The SDK provides a fluent builder API for a more intuitive experience:

// Using the fluent builder
await client.messages
  .createMessage()
  .to('https://api.example.com/webhook')
  .body({ event: 'test', data: { value: 42 } })
  .in(60) // 60 seconds from now
  .withRetries(5)
  .send();

Next.js Integration

QueueSaaS provides first-class support for Next.js App Router with automatic webhook signature verification.

The simplest way to handle QueueSaaS webhooks in Next.js:

// app/api/scheduler/route.ts
import { serve } from '@anlyonhq/scheduler/nextjs';

export const { POST } = serve(async (request) => {
  const data = await request.json();

  // Process the verified webhook
  await processJob(data);

  return { success: true };
});

Using verifySignature() Middleware

For more control over your handler:

// app/api/webhook/route.ts
import { verifySignature } from '@anlyonhq/scheduler/nextjs';

export const POST = verifySignature(async (request) => {
  const data = await request.json();

  // Signature is already verified
  await handleWebhook(data);

  return Response.json({ ok: true });
});

Set your signing secret in your environment:

ANLYON_SIGNING_SECRET=whsec_your_signing_secret_here

Advanced Features

CRON Scheduling

Create recurring tasks with CRON expressions:

// Create a daily schedule
await client.schedules.create({
  name: 'Daily Report',
  cronExpression: '0 9 * * *', // 9 AM every day
  timezone: 'America/New_York',
  url: 'https://api.example.com/report',
  method: 'POST',
  body: { type: 'daily_report' },
});

// Using the fluent builder
await client.schedules
  .createSchedule()
  .name('Hourly Ping')
  .hourly()
  .to('https://api.example.com/ping')
  .body({ type: 'ping' })
  .create();

URL Groups (Fan-Out Messaging)

Broadcast messages to multiple endpoints:

// Create a URL group
const group = await client.urlGroups.create({
  name: 'Production Webhooks',
  endpoints: [
    { url: 'https://service1.example.com/webhook' },
    { url: 'https://service2.example.com/webhook' },
  ],
});

// Broadcast to all endpoints
await client.urlGroups.publish(group.data.id, {
  body: { event: 'broadcast', data: { userId: 123 } },
});

Dead Letter Queue Management

Handle failed messages:

// List failed messages
const failed = await client.dlq.list();

// Retry a specific message
await client.dlq.retry('msg_id');

// Retry all failed messages
await client.dlq.retryAll();

// Get DLQ statistics
const stats = await client.dlq.getStats();

Error Handling

The SDK provides typed error classes for different scenarios:

import { 
  AnlyonError,
  AuthenticationError,
  QuotaExceededError,
  ValidationError 
} from '@anlyonhq/scheduler';

try {
  await client.messages.publish({ /* ... */ });
} catch (error) {
  if (error instanceof QuotaExceededError) {
    console.error('Quota exceeded:', error.message);
    // Handle quota exceeded
  } else if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
    // Handle validation error
  } else if (error instanceof AuthenticationError) {
    console.error('Authentication failed');
    // Handle auth error
  }
}

Pagination

The SDK provides helpers for iterating over paginated results:

// List all messages (automatically handles pagination)
for await (const message of client.messages.listAll()) {
  console.log(message.messageId);
}

// Or manually paginate
const result = await client.messages.list({ limit: 50 });
// result.data contains messages
// result.pagination contains pagination info

Best Practices

  1. Store API keys securely: Use environment variables, never commit them to version control
  2. Handle errors gracefully: Always wrap SDK calls in try-catch blocks
  3. Use TypeScript: The SDK is fully typed for better developer experience
  4. Set appropriate retries: Configure retry counts based on your use case
  5. Monitor your queues: Use the analytics API to track message delivery

Next Steps

Happy queuing! 🚀