SDK
Node.js SDK
The official Node.js SDK for Unosend. Works with Node.js 18+ and supports TypeScript out of the box.
Installation
npm
npm install @unosend/nodeOr with yarn:
yarn
yarn add @unosend/nodeRequirements
- Node.js 18 or higher
- TypeScript 4.7+ (optional)
Environment Variables
Never hardcode your API key. Use environment variables instead:
.env
UNOSEND_API_KEY=un_your_api_keyindex.ts
import { Unosend } from '@unosend/node';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);Basic Usage
index.ts
import { Unosend } from '@unosend/node';
// Initialize with your API key
const unosend = new Unosend('un_your_api_key');
// Send an email
async function sendWelcomeEmail(email: string, name: string) {
const { data, error } = await unosend.emails.send({
from: 'hello@yourdomain.com',
to: email, // Can be string or string[]
subject: `Welcome, ${name}!`,
html: `<h1>Hello ${name}</h1><p>Welcome to our platform!</p>`
});
if (error) {
console.error('Failed to send:', error.message);
return null;
}
console.log('Email sent:', data.id);
return data;
}Response Format
All SDK methods return a response object with data and error properties:
response.json
// Successful response
{
"data": {
"id": "em_xxxxxxxxxxxxxxxxxxxxxxxx",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Welcome!",
"status": "queued",
"createdAt": "2024-01-15T10:30:00Z"
},
"error": null
}
// Error response
{
"data": null,
"error": {
"message": "Invalid API key",
"code": 401,
"statusCode": 401
}
}Sending with Attachments
attachments.ts
import { Unosend } from '@unosend/node';
import { readFileSync } from 'fs';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
// Send email with file attachment
const { data, error } = await unosend.emails.send({
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Your Invoice',
html: '<p>Please find your invoice attached.</p>',
attachments: [
{
filename: 'invoice.pdf',
content: readFileSync('./invoice.pdf').toString('base64'),
contentType: 'application/pdf'
}
]
});Working with Domains
domains.ts
import { Unosend } from '@unosend/node';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
// Add a domain
const { data: domain } = await unosend.domains.create('yourdomain.com');
console.log('Domain added:', domain.id);
console.log('DNS Records to add:', domain.records);
// List all domains
const { data: domains } = await unosend.domains.list();
console.log('Your domains:', domains);
// Verify domain DNS
const { data: verified } = await unosend.domains.verify(domain.id);
console.log('Domain status:', verified.status);
// Delete a domain
await unosend.domains.delete(domain.id);Working with Audiences & Contacts
audiences.ts
import { Unosend } from '@unosend/node';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
// Create an audience
const { data: audience } = await unosend.audiences.create('Newsletter Subscribers');
console.log('Audience created:', audience.id);
// Add a contact to the audience
const { data: contact } = await unosend.contacts.create(audience.id, {
email: 'subscriber@example.com',
firstName: 'John',
lastName: 'Doe'
});
console.log('Contact added:', contact.id);
// List all contacts in an audience
const { data: contacts } = await unosend.contacts.list(audience.id);
console.log('Subscribers:', contacts.length);
// List all audiences
const { data: audiences } = await unosend.audiences.list();
console.log('Your audiences:', audiences);Configuration Options
config.ts
import { Unosend } from '@unosend/node';
// Default configuration
const unosend = new Unosend('un_your_api_key');
// Custom base URL (for self-hosted instances)
const customClient = new Unosend('un_your_api_key', {
baseUrl: 'https://your-instance.com/api/v1'
});Framework Examples
Next.js App Router
app/api/send/route.ts
import { NextResponse } from 'next/server';
import { Unosend } from '@unosend/node';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
export async function POST(request: Request) {
const { to, subject, html } = await request.json();
const { data, error } = await unosend.emails.send({
from: 'hello@yourdomain.com',
to: [to],
subject,
html
});
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
return NextResponse.json({ id: data.id });
}Express.js
routes/email.ts
import express from 'express';
import { Unosend } from '@unosend/node';
const router = express.Router();
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
router.post('/send', async (req, res) => {
const { to, subject, html } = req.body;
const { data, error } = await unosend.emails.send({
from: 'hello@yourdomain.com',
to: [to],
subject,
html
});
if (error) {
return res.status(400).json({ error: error.message });
}
res.json({ id: data.id });
});
export default router;Error Handling
error-handling.ts
import { Unosend } from '@unosend/node';
const unosend = new Unosend(process.env.UNOSEND_API_KEY!);
async function sendEmail() {
const { data, error } = await unosend.emails.send({
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello',
html: '<p>Hello World</p>'
});
if (error) {
// Handle based on status code
switch (error.statusCode) {
case 429:
console.log('Rate limited, please retry later');
break;
case 401:
console.log('Check your API key');
break;
case 400:
console.log('Validation error:', error.message);
break;
default:
console.log('Error:', error.message);
}
return;
}
console.log('Email sent:', data.id);
}TypeScript Support
The SDK includes full TypeScript definitions:
types.ts
import type {
SendEmailOptions,
Email,
Domain,
Audience,
Contact,
Webhook
} from '@unosend/node';
// All methods are fully typed
const sendOptions: SendEmailOptions = {
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello',
html: '<p>Hello World</p>'
};Available Methods
| Method | Description |
|---|---|
emails.send() | Send an email |
emails.get(id) | Get email details by ID |
emails.list() | List all emails |
domains.create(name) | Add a domain |
domains.verify(id) | Verify domain DNS |
domains.list() | List all domains |
audiences.create(name) | Create an audience |
audiences.list() | List all audiences |
contacts.create(audienceId, data) | Add a contact to audience |
contacts.list(audienceId) | List contacts in audience |