Quickstarts
Send with Cloudflare Workers
Send email from a Cloudflare Worker with fetch and a secret.
Workers have no Node.js APIs by default, but the usend SDK only needs fetch, so it works. You need a verified domain and an API key.
1. Create the project and secret
npm create cloudflare@latest usend-worker
cd usend-worker
npm install @usend/node
npx wrangler secret put USEND_API_KEYFor local development, put USEND_API_KEY=us_123456789 in .dev.vars.
2. The Worker
import { Usend } from '@usend/node';
interface Env {
USEND_API_KEY: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (request.method !== 'POST') return new Response('POST only', { status: 405 });
const usend = new Usend(env.USEND_API_KEY);
const { email } = (await request.json()) as { email: string };
const { data, error } = await usend.emails.send({
from: 'Acme <[email protected]>',
to: [email],
subject: 'Welcome to Acme',
html: '<p>Thanks for signing up.</p>',
});
if (error) return Response.json({ error }, { status: 502 });
return Response.json({ id: data.id });
},
};3. Run and deploy
npx wrangler dev
curl -X POST localhost:8787 -d '{"email":"[email protected]"}'
npx wrangler deployWithout the SDK
const res = await fetch('https://api.usend.et/emails', {
method: 'POST',
headers: { Authorization: `Bearer ${env.USEND_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ from: 'Acme <[email protected]>', to: ['[email protected]'], subject: 'Hi', text: 'Hi' }),
});Tip
Do not let browsers call the usend API directly with your key. Always go through your Worker. See CORS.
If you want a send to continue after the response, wrap it in ctx.waitUntil(...). Next: Send emails.