К основному содержанию
скилл CX Codex

resend · vercel-labs — скилл для Claude Code: эмуляция Resend API локально

Скилл запускает локальный Resend API, который принимает письма, сохраняет их в памяти и отдаёт через REST или UI. Реальные письма не отправляются.

Apache-2.0 246 установок ★ 2 075 обновлён 2026-10-25

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add vercel-labs/emulate --skill resend -a claude-code
Открыть на GitHub

Что делает resend

Скилл поднимает эмулятор Resend на localhost:4000 (или в адаптере Next.js по маршруту /emulate/resend). Все письма, отправленные через POST /emails, остаются в памяти — их можно читать в браузере по адресу /inbox или забирать через GET /emails. Поддерживаются домены, контакты, API-ключи, батч-отправка до 100 писем, идемпотентность через заголовок Idempotency-Key, расписание отправки (scheduled_at) и отмена (POST /emails/<id>/cancel).

Официальный SDK Resend для Node.js читает переменную RESEND_BASE_URL при загрузке модуля: задайте ей адрес эмулятора, и код работает без изменений. Полезно для проверки магических ссылок, кодов подтверждения и сброса пароля: можно извлечь код из HTML тела письма через jq и grep.

Скилл подсказывает агенту команды npx emulate --service resend и curl для отправки и чтения писем. Авторизация — любой токен с префиксом re_; если токена нет, запрос идёт от дефолтного пользователя. Seed-файл YAML позволяет задать начальные домены и контакты.

Какие задачи решает

  • тестировать письма с кодами подтверждения без реальной отправки
  • проверить магические ссылки и сброс пароля в CI
  • отладить транзакционные письма локально
  • извлечь верификационный код из HTML письма в тесте
  • запустить Resend API внутри Next.js по маршруту

Примеры запросов агенту

  • Запусти эмулятор Resend на порту 4000 и покажи команду для отправки письма с кодом подтверждения
  • Отправь письмо через эмулятор и достань последний шестизначный код из HTML
  • Подними Resend API в Next.js по /emulate/resend и настрой RESEND_BASE_URL

Как установить resend

1Через Skills CLI (Vercel)

npx skills add vercel-labs/emulate --skill resend -a claude-code

2Вручную: положить файлы

~/.claude/skills/resend/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/resend/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о resend

Как установить resend в Claude Code?

Выполни npx skills add vercel-labs/emulate --skill resend -a claude-code, затем открой ~/.claude/skills/resend/SKILL.md.

Что делает скилл resend?

Скилл запускает локальный эмулятор Resend API, который принимает и сохраняет письма в памяти вместо реальной отправки. Отправленные письма можно читать через браузер или REST API, извлекать коды подтверждения и проверять магические ссылки в тестах.

Как подключить SDK Resend к эмулятору?

Задай переменную окружения RESEND_BASE_URL=http://localhost:4000 перед запуском приложения. Официальный SDK Resend для Node.js читает её при загрузке модуля, и код работает без изменений.

Исходный текст

SKILL.md · Apache-2.0
---
name: resend
description: Emulated Resend email API for local development and testing. Use when the user needs to send emails locally, test transactional email flows, implement magic link or verification code auth, inspect sent emails, manage domains/contacts/API keys, or work with the Resend API without sending real emails. Triggers include "Resend API", "emulate Resend", "send email locally", "test email", "magic link", "verification email", "email inbox", "RESEND_BASE_URL", or any task requiring a local email API.
allowed-tools: Bash(npx emulate:*), Bash(curl:*)
---

# Resend Email API Emulator

Fully stateful Resend API emulation. Emails, domains, API keys, audiences, and contacts persist in memory. Sent emails are captured and viewable through the inbox UI or the REST API.

No real emails are sent. Accepted calls to `POST /emails` store the message locally so you can inspect it programmatically or in the browser. Validated sends also record attempts, including recipient rejections.

## Start

Local listeners bind to `127.0.0.1` by default. For access from containers or other machines, pass `--host 0.0.0.0` to the CLI or `hostname: '0.0.0.0'` to `createEmulator`. Configure `--base-url` or `baseUrl` for advertised URLs reachable by those clients.

```bash
# Resend only
npx emulate --service resend

# Default port (when run alone)
# http://localhost:4000
```

Or programmatically:

```typescript
import { createEmulator } from 'emulate'

const resend = await createEmulator({ service: 'resend', port: 4000 })
// resend.url === 'http://localhost:4000'
```

## Auth

Pass tokens as `Authorization: Bearer <token>`. Any `re_` prefixed token is accepted.

```bash
curl http://localhost:4000/emails \
  -H "Authorization: Bearer re_test_key"
```

When no token is provided, requests fall back to the default user.

## Pointing Your App at the Emulator

### Environment Variable (Resend SDK)

The official Resend Node.js SDK reads `RESEND_BASE_URL` at module load time. Set it to the emulator URL and the SDK works without any code changes:

```bash
RESEND_BASE_URL=http://localhost:4000
```

```typescript
import { Resend } from 'resend'

// No baseUrl argument needed; the SDK reads RESEND_BASE_URL automatically.
const resend = new Resend('re_test_key')

await resend.emails.send({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Hello',
  html: '<p>It works!</p>',
})
```

### Embedded in Next.js (adapter-next)

When using `@emulators/adapter-next`, the emulator runs inside your Next.js app at `/emulate/resend`. Set `RESEND_BASE_URL` via `next.config.ts`:

```typescript
// next.config.ts
import { withEmulate } from '@emulators/adapter-next'

export default withEmulate({
  env: {
    RESEND_BASE_URL: `http://localhost:${process.env.PORT ?? '3000'}/emulate/resend`,
  },
})
```

```typescript
// app/emulate/[...path]/route.ts
import { createEmulateHandler } from '@emulators/adapter-next'
import * as resend from '@emulators/resend'

export const { GET, POST, PUT, PATCH, DELETE } = createEmulateHandler({
  services: {
    resend: {
      emulator: resend,
      seed: {
        domains: [{ name: 'example.com' }],
      },
    },
  },
})
```

### Direct fetch

If you cannot use the SDK or env var, call the emulator directly:

```typescript
await fetch('http://localhost:4000/emails', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer re_test_key',
  },
  body: JSON.stringify({
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Hello',
    html: '<p>It works!</p>',
  }),
})
```

## Seed Config

```yaml
resend:
  domains:
    - name: example.com
      region: us-east-1
  contacts:
    - email: [email protected]
      first_name: Test
      last_name: User
      audience: Default
```

## Retrieving Sent Emails

This is the key differentiator of the emulator: every email sent via `POST /emails` is stored and queryable.

### Inbox UI

Browse sent emails in the browser:

```
http://localhost:4000/inbox
```

### REST API

```bash
# List all sent emails
curl http://localhost:4000/emails \
  -H "Authorization: Bearer re_test_key"

# Get a single email by ID
curl http://localhost:4000/emails/<id> \
  -H "Authorization: Bearer re_test_key"
```

### Extracting Data from Emails (tests, agents)

Useful for completing magic link, verification code, or password reset flows programmatically:

```bash
# Get the latest email ID
EMAIL_ID=$(curl -s http://localhost:4000/emails \
  -H "Authorization: Bearer re_test_key" | jq -r '.data[0].id')

# Extract a 6-digit code from the HTML body
CODE=$(curl -s http://localhost:4000/emails/$EMAIL_ID \
  -H "Authorization: Bearer re_test_key" | jq -r '.html' | grep -oE '[0-9]{6}')

echo "Verification code: $CODE"
```

## API Endpoints

### Emails

```bash
# Send an email
curl -X POST http://localhost:4000/emails \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"from": "[email protected]", "to": "[email protected]", "subject": "Hello", "html": "<p>Hi</p>"}'

# Send batch (up to 100)
curl -X POST http://localhost:4000/emails/batch \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '[{"from": "[email protected]", "to": "[email protected]", "subject": "One", "html": "<p>1</p>"}]'

# List all emails
curl http://localhost:4000/emails \
  -H "Authorization: Bearer $TOKEN"

# Get email by ID
curl http://localhost:4000/emails/<id> \
  -H "Authorization: Bearer $TOKEN"

# Cancel a scheduled email
curl -X POST http://localhost:4000/emails/<id>/cancel \
  -H "Authorization: Bearer $TOKEN"
```

Supported fields: `from`, `to`, `subject`, `html`, `text`, `cc`, `bcc`, `reply_to`, `headers`, `tags`, `scheduled_at`.

### Idempotent Sends

`POST /emails` and `POST /emails/batch` accept the case-insensitive `Idempotency-Key` header. Keys must be 1 to 256 characters and remain active for 24 hours. A retry with the same key and validated payload returns the original response, email IDs, and status without creating emails or dispatching duplicate `email.sent` and `email.delivered` webhooks. Reusing a key with a different payload or endpoint returns `409 invalid_idempotent_request`; invalid key lengths return `400 invalid_idempotency_key`. Omitting the header preserves normal behavior.

```bash
curl -X POST http://localhost:4000/emails \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: signup-email-123" \
  -d '{"from": "[email protected]", "to": "[email protected]", "subject": "Hello"}'
```

### Recipient restrictions and send attempts

Set `resend.allowlist` in seed config to test recipient rejection:

```yaml
resend:
  allowlist:
    - [email protected]
    - [email protected]
```

Omitting `allowlist` accepts every recipient; `allowlist: []` rejects every recipient. Every address in `to`, `cc`, and `bcc` must be listed. Matching ignores surrounding whitespace and letter case; entries are individual addresses, with no wildcard or domain matching. This is a local testing control, independent of Resend's domain verification and account restrictions.

A rejected send returns `403 validation_error` naming the rejected addresses and configured allowlist. No email ID, email record, idempotency record, or webhook is created. A batch is rejected as a whole if any recipient is disallowed. Retrying a rejected request, even with the same idempotency key, creates a new attempt. Replaying an accepted idempotent request returns its original response even if the allowlist has since changed.

Validated sends append one record per email to the `resend.send_attempts` store collection, including emails in a rejected batch. Each record contains `from`, `to`, `cc`, `bcc`, `subject`, `idempotency_key` (or `null`), and the store's `id`, `created_at`, and `updated_at`. Message bodies are not copied into attempts. Malformed requests, invalid or conflicting idempotency keys, and idempotency replays do not append attempts.

Read attempts with `getResendStore(store).sendAttempts.all()` from `@emulators/resend`, or inspect the persisted state. Shared adapter snapshots use the key `resend:resend.send_attempts`. Attempts and recipient restrictions survive saved-state restoration, including rejected sends. There is no additional Resend API endpoint for attempts. A rejected send has an attempt without an email; a send that never happened has neither.

### Domains

```bash
# Create domain
curl -X POST http://localhost:4000/domains \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "example.com", "region": "us-east-1"}'

# List domains
curl http://localhost:4000/domains \
  -H "Authorization: Bearer $TOKEN"

# Get domain
curl http://localhost:4000/domains/<id> \
  -H "Authorization: Bearer $TOKEN"

# Verify domain (instantly marks all records as verified)
curl -X POST http://localhost:4000/domains/<id>/verify \
  -H "Authorization: Bearer $TOKEN"

# Delete domain
curl -X DELETE http://localhost:4000/domains/<id> \
  -H "Authorization: Bearer $TOKEN"
```

### API Keys

```bash
# Create API key
curl -X POST http://localhost:4000/api-keys \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Production"}'

# List API keys
curl http://localhost:4000/api-keys \
  -H "Authorization: Bearer $TOKEN"

# Delete API key
curl -X DELETE http://localhost:4000/api-keys/<id> \
  -H "Authorization: Bearer $TOKEN"
```

### Audiences

```bash
# Create audience
curl -X POST http://localhost:4000/audiences \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Newsletter"}'

# List audiences
curl http://localhost:4000/audiences \
  -H "Authorization: Bearer $TOKEN"

# Delete audience
curl -X DELETE http://localhost:4000/audiences/<id> \
  -H "Authorization: Bearer $TOKEN"
```

### Contacts

```bash
# Create contact in an audience
curl -X POST http://localhost:4000/audiences/<audience_id>/contacts \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "first_name": "Jane", "last_name": "Doe"}'

# List contacts in an audience
curl http://localhost:4000/audiences/<audience_id>/contacts \
  -H "Authorization: Bearer $TOKEN"

# Delete contact
curl -X DELETE http://localhost:4000/audiences/<audience_id>/contacts/<id> \
  -H "Authorization: Bearer $TOKEN"
```

## Webhooks

The emulator dispatches webhook events when state changes:

- `email.sent` and `email.delivered` on `POST /emails`
- `domain.created` and `domain.deleted` on domain operations
- `contact.created` and `contact.deleted` on contact operations

## Common Patterns

### Magic Link / Verification Code Flow

```bash
TOKEN="re_test_key"
BASE="http://localhost:4000"

# 1. Send verification email
curl -X POST $BASE/emails \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"from": "[email protected]", "to": "[email protected]", "subject": "Your code", "html": "<p>Code: <strong>482910</strong></p>"}'

# 2. Retrieve the email
EMAIL_ID=$(curl -s $BASE/emails -H "Authorization: Bearer $TOKEN" | jq -r '.data[0].id')

# 3. Read the HTML body
curl -s $BASE/emails/$EMAIL_ID -H "Authorization: Bearer $TOKEN" | jq -r '.html'
```

### Send and Verify in a Test

```typescript
import { createEmulator } from 'emulate'
import { Resend } from 'resend'

const emu = await createEmulator({ service: 'resend', port: 4000 })

process.env.RESEND_BASE_URL = emu.url
const resend = new Resend('re_test_key')

// Send
await resend.emails.send({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Verify',
  html: '<p>Code: <strong>123456</strong></p>',
})

// Retrieve
const res = await fetch(`${emu.url}/emails`, {
  headers: { Authorization: 'Bearer re_test_key' },
})
const { data: emails } = await res.json()
console.log(emails[0].html) // contains "123456"
```

## Custom emulators alongside built-ins

Use `npx emulate init --custom inventory` to scaffold a third-party API emulator and test. Register it in `emulate.config.ts` with `defineConfig` from `emulate`, alongside built-in entries such as `{ emulator: "resend" }`. Run `npx emulate start --watch` to reload imports and inspect custom state at the printed `/_emulate` URL. Successful reloads reset the run to seed. Existing flat seed configs still work; `--config` selects an explicit file. For authoring and testing third-party API emulators, see https://emulate.dev/docs/custom-emulators.

© vercel-labs · Apache-2.0 · vercel-labs/emulate

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →

Сначала — resend от других авторов.

resend resend Скилл resend для Claude Code помогает работать с API Resend: отправлять письма, настраивать вебхуки и управлять шаблонами. Подключается к задачам с Resend и его SDK. CX Codex +1 24 800установок resend oakoss Помогает агенту настроить отправку писем через Resend API, шаблоны React Email, верификацию доменов и вебхуки Svix. CX Codex +1 127установок resend-cli resend Скилл resend-cli для Claude Code учит агента работать с Resend через CLI: отправлять письма и управлять доменами, контактами, рассылками и вебхуками. Эти задачи выполняются из скриптов и CI. CX Codex +1 14 200установок resend-integration-skills gocallum Скилл resend-integration-skills для Claude Code настраивает отправку транзакционных и маркетинговых писем через Resend по MCP из чата с агентом. CX Codex +1 413установок pp-resend Giuliano Giacaglia Скилл pp-resend управляет аккаунтом Resend через терминал: собирает историю отправок адресату, строит цепочки событий письма и проверяет здоровье доменов. CX Codex +1 256установок email официальный Vercel Labs Настраивает отправку писем через Resend и шаблоны React Email в проектах на Vercel. Помогает связать API и подготовить вёрстку. CX Codex GP ChatGPT +1 6установок resend-webhooks hookdeck Скилл resend-webhooks помогает подключить вебхуки Resend, проверить подпись Svix и обработать события почты. Нужен при настройке Express или FastAPI. CX Codex +1 266установок resend-design-skills resend Скилл resend-design-skills направляет ассистента к правилам визуального стиля и айдентики Resend. Пригодится при оформлении презентаций, соцсетей и промо-страниц в стилистике бренда. CX Codex +1 1 200установок

Из того же набора12

Весь набор →
emulate Скилл emulate для Claude Code запускает локальные эмуляторы API для тестов, CI и работы без сети. Он реагирует на просьбы запустить сервисы или настроить seed-данные. CX Codex +1 568установок google Эмулирует Google OAuth 2.0, OIDC, Gmail, Calendar и Drive для локальной разработки. CX Codex +1 382установок stripe Эмулятор Stripe API для локальной разработки и тестирования платежей. Обрабатывает платежи без обращения к реальным серверам Stripe, позволяет тестировать checkout, работать с webhook и SDK. CX Codex +1 294установок aws Скилл aws для Claude Code поднимает локальную эмуляцию сервисов AWS для отладки приложений без обращения к реальному облаку. CX Codex +1 241установок github Запускает локальную эмуляцию GitHub REST API с сохранением состояния. Помогает тестировать вебхуки, OAuth-авторизацию и GitHub Apps без реальных запросов к api.github.com. CX Codex +1 228установок apple Локальный эмулятор Apple OIDC для разработки и тестирования авторизации через Apple. Поднимает сервер с discovery-документом, выдачей токенов и JWKS. CX Codex +1 224установок vercel Эмулирует REST API платформы Vercel на локальной машине для тестов интеграций, OAuth и деплоев. CX Codex +1 220установок slack Локально эмулирует Slack Web API для разработки и тестирования интеграций без обращения к реальному Slack. CX Codex +1 212установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой