Laneful Node.js/TypeScript SDK
Send emails with JavaScript/TypeScript using the official Laneful Node.js SDK. Modern API, full features, and type safety.
Templates, attachments, tracking
First-class TypeScript support
Async/await, axios-based client
On this page
Prerequisites
Before you begin, make sure you have:
- • Node.js 16 or higher
- • npm or yarn
- • A Laneful account with API key
- • Verified domain for sending emails
Installation
npm
npm install laneful
This page describes version 2.3.0. The package loads from CommonJS (require) and from native ES modules (import). In 2.2.0 and earlier the ES module build doesn't load in Node.js, so use CommonJS or a bundler there.
Quick Start
Send your first email in minutes:
Send Simple Email (TypeScript)
import { LanefulClient, Email } from 'laneful';
// Initialize the client
const client = new LanefulClient(
'https://your-endpoint.z1.send.laneful.net',
'your-api-key'
);
// Create an email
const email: Email = {
from: { email: 'noreply@yourdomain.com', name: 'Your App Name' },
to: [{ email: 'user@example.com', name: 'User Name' }],
subject: 'Welcome to Our Service',
textContent: 'Welcome to our service!'
};
// Send the email
async function main() {
try {
const response = await client.sendEmail(email);
console.log('Email sent successfully!', response);
} catch (error) {
console.error('Failed to send email:', error);
}
}
main();Replace https://your-endpoint.z1.send.laneful.net with your organization's HTTP API endpoint, shown in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email), and your-api-key with a key you create there. The API accepts HTTPS only.
Examples
Common use cases and patterns. Each snippet runs inside an async function and uses the client from Quick Start:
Template Email
await client.sendEmail({
from: { email: 'noreply@yourdomain.com', name: 'Your App' },
to: [{ email: 'user@example.com', name: 'John Smith' }],
subject: 'Welcome to Our Service',
templateId: '1234',
templateData: {
user_name: 'John Smith',
company_name: 'Acme Corp',
activation_link: 'https://app.example.com/activate/abc123',
support_email: 'support@yourdomain.com'
}
});Email with Attachment
await client.sendEmail({
from: { email: 'sender@yourdomain.com' },
to: [{ email: 'recipient@example.com' }],
subject: 'Document',
textContent: 'Please find attached.',
attachments: [{
contentType: 'application/pdf',
fileName: 'document.pdf',
content: 'base64-encoded-content'
}]
});Email with Tracking Settings
await client.sendEmail({
from: { email: 'newsletter@yourdomain.com' },
to: [{ email: 'subscriber@example.com' }],
subject: 'Monthly Newsletter',
htmlContent: '<h1>Our Monthly Update</h1><p>Latest news and updates...</p>',
tag: 'newsletter',
tracking: {
opens: true,
clicks: true,
unsubscribes: true,
unsubscribeGroupId: 123
},
webhookData: {
campaign_id: 'camp_123'
}
});Scheduled Email
await client.sendEmail({
from: { email: 'sender@yourdomain.com' },
to: [{ email: 'recipient@example.com' }],
subject: 'Scheduled',
textContent: 'This will be sent later.',
sendTime: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now
});Batch Email Sending
const response = await client.sendEmails([
{
from: { email: 'sender@yourdomain.com' },
to: [{ email: 'user1@example.com' }],
subject: 'Email 1',
textContent: 'First email content.'
},
{
from: { email: 'sender@yourdomain.com' },
to: [{ email: 'user2@example.com' }],
subject: 'Email 2',
textContent: 'Second email content.'
}
]);All emails go in one request and share one response and one idempotency key.
Message IDs and Webhook Data
const response = await client.sendEmail(
{
from: { email: 'orders@yourdomain.com' },
to: [{ email: 'customer@example.com' }],
subject: 'Your order has shipped',
textContent: 'Your order is on its way.',
webhookData: { order_id: '1042' } // returned as metadata on every webhook event
},
{ returnMessageIds: true } // MailSettings
);
// One ID per email, equal to message_id on that email's webhook events
console.log(response.messageIds);API Reference
LanefulClient
Initialization
- •
new LanefulClient(baseUrl: string, authToken: string, options?: LanefulClientOptions)
Methods
- •
sendEmail(email: Email, settings?: MailSettings): Promise<SendEmailResponse>- Send single email - •
sendEmails(emails: Email[], settings?: MailSettings): Promise<SendEmailResponse>- Send multiple emails in one request
Core Interfaces
interface Email {
from: Address;
subject: string; // Required, also with templateId
to?: Address[];
cc?: Address[];
bcc?: Address[];
textContent?: string;
htmlContent?: string;
templateId?: string;
templateData?: Record<string, unknown>;
attachments?: Attachment[];
headers?: Record<string, string>; // Custom email headers
replyTo?: Address;
sendTime?: number; // Unix timestamp in seconds, at most 72 hours ahead
webhookData?: Record<string, string>; // Returned as metadata on every webhook event
tag?: string;
tracking?: TrackingSettings;
fromHeader?: Address; // Visible From header, if it should differ from from
}
interface Address {
email: string;
name?: string;
}
interface Attachment {
contentType: string;
fileName?: string;
content?: string; // Base64 encoded
inlineId?: string; // Content ID for inline images
}
interface TrackingSettings {
opens?: boolean; // Track email opens (default: true)
clicks?: boolean; // Track link clicks (default: true)
unsubscribes?: boolean; // Track unsubscribes (default: true)
unsubscribeGroupId?: number; // Optional unsubscribe group ID
unsubscribeGroupName?: string; // Ignored if unsubscribeGroupId is set
}
interface MailSettings {
idempotencyKey?: string; // 1 to 36 bytes; generated when omitted, see Retries
sandboxMode?: boolean; // Accept the request without sending anything
returnMessageIds?: boolean; // Return one message ID per email
}
interface SendEmailResponse {
status: string; // e.g. 'accepted'
messageIds?: string[]; // Only with returnMessageIds: true
messageId?: string; // First message ID
}
interface LanefulClientOptions {
timeout?: number; // Per attempt, in milliseconds (default: 30000)
retry?: RetryOptions; // See Retries
rateLimit?: RateLimitOptions; // Client-side limit, see below
logger?: Logger; // { debug, info, warn, error }
userAgent?: string;
verifySsl?: boolean; // Accepted but has no effect
}
interface RetryOptions {
maxRetries?: number; // default: 3; 0 turns retries off
baseDelay?: number; // milliseconds, default: 1000
maxDelay?: number; // milliseconds, default: 10000
backoffMultiplier?: number; // default: 2
jitter?: number; // default: 0.1
}
interface RateLimitOptions {
maxRequests: number;
windowMs: number;
}- •
headers: custom email headers. From, To, Cc, Bcc, Reply-To and Subject come from the email fields and Laneful generates the Message-ID as<message_id@laneful-host>, so those headers are ignored here. See Sending Email. - •
webhookData: your own data, up to 20 keys (keys up to 50 bytes and string values up to 100 bytes in UTF-8). Laneful returns it unchanged asmetadataon every webhook event for the email. - •
messageIds: setreturnMessageIdsto true to get one ID per email; each matches themessage_idon that email's webhook events. This requires every email in the request to have exactly one recipient. See Mail Settings. - •
rateLimit: caps the client atmaxRequestscalls perwindowMswindow; calls over the limit fail fast withLanefulErrorinstead of waiting.
Organization API Methods
- • Unsubscribe groups:
listUnsubscribeGroups(workspaceId, ...),createUnsubscribeGroup(workspaceId, ...),updateUnsubscribeGroup(workspaceId, unsubscribeGroupId, ...) - • Domains:
listDomains(workspaceId, ...),getDomain(workspaceId, domain),createDomain(workspaceId, ...),updateDomain(workspaceId, domain, ...),verifyDomain(workspaceId, domain),deleteDomain(workspaceId, domain) - • Analytics:
listDomainSpamRatioRadar,listGooglePostmasterSpamReports,listSndsReports
const org = new LanefulClient('https://api.laneful.net', 'your-organization-api-key');
const groups = await org.listUnsubscribeGroups(42, { limit: 50 });
await org.verifyDomain(42, 'yourdomain.com');These methods call the Organization API, so create a separate client with base URL https://api.laneful.net and an Organization API key (see Organization API). Domain and unsubscribe group methods are scoped to a workspace and take workspaceId: number as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).
Error Handling
Comprehensive error handling with specific error types:
import {
Email,
LanefulAPIError,
LanefulAuthError,
LanefulClient,
LanefulError,
LanefulValidationError
} from 'laneful';
async function send(client: LanefulClient, email: Email) {
try {
await client.sendEmail(email);
} catch (error) {
if (error instanceof LanefulValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof LanefulAuthError) {
console.error('Authentication failed');
} else if (error instanceof LanefulAPIError) {
console.error('API error:', error.statusCode, error.responseData);
} else if (error instanceof LanefulError) {
console.error('Request failed:', error.message); // e.g. timeout or connection failure
} else {
console.error('Unexpected error:', error);
}
}
}Error Types
- •
LanefulValidationError- Invalid input caught before sending (empty email list,webhookDataover its limits,idempotencyKeyoutside 1 to 36 bytes) - •
LanefulAuthError- API returned 401 (invalid API key) - •
LanefulAPIError- Any other API error status, withstatusCodeandresponseDatafor details - •
LanefulError- Base class; thrown directly for timeouts, connection failures and the client-side rate limit
Best Practices
- • Wrap API calls in try/catch
- • Handle specific error classes first
- • Log errors with context
- • Before resending after a timeout or connection failure, read Retries: reuse the same
idempotencyKey. After an HTTP 500, check your webhook events first
Retries and Duplicate Sends
- • The client automatically retries a request that times out (
timeout, 30 seconds by default) or whose connection fails (connection refused or DNS lookup failure), up to 3 times by default (retry.maxRetries), after about 1, 2 and 4 seconds. This covers every request, sends included. - • HTTP error responses, including 5xx and 429, reach your code right away, without a retry.
- • Every
sendEmailandsendEmailscall carries an idempotency key (mail_settings.idempotency_key, see Sending Email), and the automatic retries reuse it, so Laneful doesn't send a timed-out send again if it had already accepted it (detection is best effort). The client generates a random key per call unless you pass one. - • Pass your own
idempotencyKey(1 to 36 bytes) to also cover your own resends after a timeout, a connection failure or a crash. A repeated key within one hour returns statusacceptedwith no message IDs and sends nothing, even if the emails differ, so use a new key for every distinct send. Sandbox mode requests aren't deduplicated. - • A request that fails with HTTP 500 doesn't keep its key, so a resend with it is processed as a new request. Before resending after a 500, check your webhook events (a
requestevent means Laneful accepted the email). - • Versions before 2.3.0 send no key, so a retried send can deliver the same email twice.
await client.sendEmail(email, { idempotencyKey: `order-${order.id}-receipt` });To decide yourself whether to resend, turn retries off:
const client = new LanefulClient(
'https://your-endpoint.z1.send.laneful.net',
'your-api-key',
{ retry: { maxRetries: 0 } }
);Webhook Handling
Verify webhook signatures and route each event type to its own handler:
Signature Verification & Processing
import express from 'express';
import { WebhookHandler, WebhookEventType } from 'laneful';
const secret = process.env.LANEFUL_WEBHOOK_SECRET;
if (!secret) {
throw new Error('LANEFUL_WEBHOOK_SECRET is not set');
}
const webhookHandler = new WebhookHandler(secret);
// Register event handlers
webhookHandler.on(WebhookEventType.DELIVERY)((event) => {
console.log(`Email delivered: ${event.message_id}`);
console.log(`Recipient: ${event.email}`);
});
webhookHandler.on(WebhookEventType.OPEN)((event) => {
console.log(`Email opened: ${event.message_id}`);
// Narrow the type to access open-specific fields
if (event.event === WebhookEventType.OPEN) {
console.log(`Client IP: ${event.client_ip}`);
console.log(`Device: ${event.client_device}`);
}
});
webhookHandler.on(WebhookEventType.CLICK)((event) => {
// Narrow the type to access click-specific fields
if (event.event === WebhookEventType.CLICK) {
console.log(`Link clicked: ${event.url}`);
console.log(`Referer: ${event.referer}`);
console.log(`Client OS: ${event.client_os}`);
}
});
const app = express();
// Verify the raw body, then process it (single events and batch mode).
// A batch can reach about 1 MB, above express.raw's 100 KB default limit.
app.post('/webhook', express.raw({ type: 'application/json', limit: '2mb' }), async (req, res) => {
const signature = req.get('x-webhook-signature') ?? '';
try {
if (!webhookHandler.verifySignature(req.body, signature)) {
res.status(401).send('Invalid signature');
return;
}
await webhookHandler.processWebhook(req.body.toString('utf8'));
res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing failed:', error);
res.status(500).send('Error'); // Laneful retries the request
}
});
app.listen(3000);- • Laneful signs every webhook:
X-Webhook-Signatureis the HMAC-SHA256 of the raw request body, keyed with your webhook secret, as 64 lowercase hex characters with no prefix. Verify the exact bytes you received (express.raw), not re-serialized JSON such asJSON.stringify(req.body), which can differ from the signed bytes. - • Always pass your webhook secret: a
WebhookHandlercreated without one rejects every signature. Versions before 2.3.0 instead returned true for any payload and threw when the signature wasundefined, which is why the sample passes''when the header is missing. - • Answer 2xx only after
processWebhookresolves: it's async, runs the handlers of a batch concurrently and rejects if any of them throws. Laneful keeps retrying for up to 24 hours until your endpoint answers 2xx within 30 seconds, so a handler can see the same event more than once. - • Each event type has one handler; registering another replaces it. Events without a handler, including unknown types, are ignored.
processWebhookexpects the Laneful webhook format (the default).
Event Types
Available Events: request, delivery, open, click, drop, spam_complaint, unsubscribe, bounce
Each temporary delivery failure arrives as a bounce with is_hard: false; there is no separate deferral event.
Event-Specific Fields
Every event passed to a handler has id, email, event, lane_id, message_id, metadata (the webhookData sent with the email), tag and timestamp (Unix seconds), plus these fields:
request
mx_host
delivery
mx_host, relay (true on relay lanes)
open
referer, client_name, client_os, client_ip, client_device, is_machine
click
url, referer, client_name, client_os, client_ip, client_device, is_machine
drop
reason, mx_host
spam_complaint
feedback_type (number; 1 = abuse), feedback_type_text, received_unix_timestamp (number), mx_host
unsubscribe
unsubscribe_group_id (number; 0 = global unsubscribe), mx_host
bounce
code, extended_code, text (strings), is_hard, deliverability_issue (booleans; the SDK's BounceEvent type declares deliverability_issue as a string), classification, mx_host
Use id to discard events you have already processed: it's unique per event and stays the same when Laneful delivers the event again. Handlers receive every field in the payload, including ones the SDK doesn't type yet. Before 2.3.0 the SDK dropped untyped fields, including id on every event except request. See Webhooks for every field.
Batch Mode Support
In batch mode, Laneful sends multiple events in one request as a JSON array; processWebhook handles both shapes:
// Single event
{
"event": "delivery",
"email": "user@example.com",
// ... other fields
}
// Batch mode (array of events)
[
{
"event": "delivery",
"email": "user@example.com",
// ... other fields
},
{
"event": "open",
"email": "user@example.com",
// ... other fields
}
]Ready to Get Started?
Start sending emails with JavaScript/TypeScript in minutes. Check out the examples and integrate with your application.