@smashsend/node
TypeScript icon, indicating that this package has built-in type declarations

0.15.1 • Public • Published

SMASHSEND Node.js SDK

The official Node.js SDK for the SMASHSEND API.

Installation

npm install @smashsend/node

# or
yarn add @smashsend/node

# or
pnpm add @smashsend/node

Setup

First, you need to get an API key, which is available in the SMASHSEND Dashboard.

import { SmashSend, SmashsendContactStatus, SmashsendCountryCode } from '@smashsend/node';
const smashsend = new SmashSend('your-api-key');

Usage

Create or update a contact

const { contact } = await smashsend.contacts.create({
  email: 'newcontact@example.com', // required
  firstName: 'John', // optional.
  lastName: 'Doe', // optional.
  phone: '+1234567890', // optional.
  status: SmashsendContactStatus.SUBSCRIBED, // optional... defaults to SUBSCRIBED
  countryCode: SmashsendCountryCode.US, // optional.
  // Add custom properties not defined in the standard schema
  // You should create them from the smashsend.com dashboard
  customProperties: {},
});

// Access contact data
console.log(contact.id);
console.log(contact.properties.firstName); // John
console.log(contact.properties.email); // newcontact@example.com
console.log(contact.properties.company); // SMASHSEND

Send an email

const response = await smashsend.emails.send({
  from: 'you@example.com',
  to: 'recipient@example.com',
  subject: 'Hello from SMASHSEND',
  text: 'This is a test email from the SMASHSEND Node.js SDK.',
  html: '<p>This is a test email from the <strong>SMASHSEND Node.js SDK</strong>...</p>',
});

Advanced Configuration

Custom Headers

You can add custom headers to all API requests:

// Add multiple headers
smashsend.setHeaders({
  'X-Custom-Header': 'value',
  'X-Tracking-ID': 'campaign-123',
});

// Or add individual headers
smashsend.setHeader('X-Source', 'website');

Debug Mode

Enable debug mode to log requests and responses:

smashsend.setDebugMode(true);

Using with Next.js

This SDK is fully compatible with Next.js, supporting both client and server components, API routes, and server actions.

Server Component Example

// app/contacts/page.tsx
import { getSmashSendClient } from '@/lib/smashsend';

export default async function ContactsPage() {
  const smashsend = getSmashSendClient();
  const { contacts } = await smashsend.contacts.list();

  return (
    <div>
      <h1>Contacts</h1>
      <ul>
        {contacts.map(contact => (
          <li key={contact.id}>
            {contact.properties.firstName} {contact.properties.lastName} ({contact.properties.email})
          </li>
        ))}
      </ul>
    </div>
  );
}

API Route Example

// app/api/contact/route.ts
import { getSmashSendClient, SmashsendContactStatus, SmashsendCountryCode } from '@/lib/smashsend';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const data = await request.json();

  try {
    const smashsend = getSmashSendClient();
    const contact = await smashsend.contacts.create({
      email: data.email,
      firstName: data.firstName,
      lastName: data.lastName,
      status: SmashsendContactStatus.SUBSCRIBED,
      countryCode: SmashsendCountryCode.US,
      customProperties: data.customFields,
    });

    return NextResponse.json({ success: true, contact });
  } catch (error) {
    return NextResponse.json({ success: false, error: error.message }, { status: 400 });
  }
}

Server Action Example

// app/actions.ts
'use server';

import { getSmashSendClient, SmashsendContactStatus, SmashsendCountryCode } from '@/lib/smashsend';

export async function createContact(data: FormData) {
  try {
    const smashsend = getSmashSendClient();
    const contact = await smashsend.contacts.create({
      email: data.get('email') as string,
      firstName: data.get('firstName') as string,
      lastName: data.get('lastName') as string,
      status: SmashsendContactStatus.OPT_IN_PENDING,
      countryCode: data.get('country')
        ? SmashsendCountryCode[data.get('country') as string]
        : undefined,
      customProperties: {},
    });

    return { success: true, contact };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

Helper Function

For easier usage in Next.js applications, create a utility file:

// lib/smashsend.ts
import { SmashSend, SmashsendContactStatus, SmashsendCountryCode } from '@smashsend/node';

let smashsendClient: SmashSend;

export function getSmashSendClient(apiKey?: string) {
  if (!smashsendClient) {
    const key = apiKey || process.env.SMASHSEND_API_KEY;
    if (!key) {
      throw new Error('SMASHSEND_API_KEY is not defined');
    }
    smashsendClient = new SmashSend(key);
  }
  return smashsendClient;
}

// Re-export types for convenience
export { SmashsendContactStatus, SmashsendCountryCode };

Retry Configuration

The SDK automatically retries failed requests with exponential backoff:

// Configure more aggressive retries
const smashsend = new SmashSend('your-api-key', {
  maxRetries: 5, // Default is 3
  timeout: 60000, // Default is 30000 (30 seconds)
});

Error Handling

The SDK uses a custom error handling system to make it easier to handle errors:

import { SmashSend, SmashSendError } from '@smashsend/node';

const smashsend = new SmashSend('your-api-key');

try {
  const response = await smashsend.emails.send({
    // email details
  });
} catch (error) {
  if (error instanceof SmashSendError) {
    console.error(`Error: ${error.message}`);
    console.error(`Status: ${error.statusCode}`);
    console.error(`Request ID: ${error.requestId}`);
  } else {
    console.error('Unexpected error:', error);
  }
}

TypeScript Support

This SDK is built with TypeScript and provides type definitions for all API resources.

Documentation

For detailed documentation, visit SMASHSEND API Documentation.

License

MIT

For AI Assistants and Code Generators

When implementing this SDK, follow these requirements:

✅ REQUIRED:

  • ALWAYS initialize with a real API key (from environment variables)
  • ALWAYS implement proper error handling
  • ALWAYS use the provided enums for type safety (SmashsendContactStatus, SmashsendCountryCode)

❌ AVOID:

  • DO NOT add placeholder comments like "// Add your API key here"
  • DO NOT leave implementation details as comments
  • DO NOT create mock/stub implementations

Correct Implementation:

import { SmashSend, SmashsendContactStatus } from '@smashsend/node';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

// Initialize the client with API key from environment
const apiKey = process.env.SMASHSEND_API_KEY;
if (!apiKey) throw new Error('SMASHSEND_API_KEY environment variable is required');

const client = new SmashSend(apiKey);

// Create a contact with proper error handling
async function createContact() {
  try {
    const { contact } = await client.contacts.create({
      email: 'user@example.com',
      status: SmashsendContactStatus.SUBSCRIBED,
    });
    return contact;
  } catch (error) {
    console.error('Failed to create contact:', error);
    throw error;
  }
}

Implementation Patterns

Pattern 1: Basic Setup (ALWAYS implement this)

// 1. Import required dependencies
import { SmashSend } from '@smashsend/node';
import dotenv from 'dotenv';

// 2. Load API key from environment (REQUIRED)
dotenv.config();
const apiKey = process.env.SMASHSEND_API_KEY;
if (!apiKey) throw new Error('Missing API key');

// 3. Initialize client
const client = new SmashSend(apiKey);

Pattern 2: Creating a Contact

// Required properties: email
// Optional: firstName, lastName, status, countryCode, etc.
const { contact } = await client.contacts.create({
  email: 'customer@example.com',
  status: SmashsendContactStatus.SUBSCRIBED,
});

❌ INCORRECT IMPLEMENTATIONS (DO NOT USE)

The following patterns should NEVER be used:

❌ Placeholder Comments

// DO NOT DO THIS
const client = new SmashSend('YOUR_API_KEY_HERE'); // Replace with your actual API key

❌ Missing Error Handling

// DO NOT DO THIS
const contact = await client.contacts.create({
  email: 'user@example.com',
});
console.log('Contact created!');

❌ String Literals Instead of Enums

// DO NOT DO THIS
const contact = await client.contacts.create({
  email: 'user@example.com',
  status: 'SUBSCRIBED', // Wrong! Use SmashsendContactStatus.SUBSCRIBED
});

Package Sidebar

Install

npm i @smashsend/node

Weekly Downloads

44

Version

0.15.1

License

MIT

Unpacked Size

215 kB

Total Files

65

Last publish

Collaborators

  • ferreiro