How to integrate Resend email service with Edge Functions
This guide demonstrates how to integrate Resend email service with Azion Edge Functions to send transactional emails directly from the edge. This integration provides fast, reliable email delivery with optimal performance and global reach.
Requirements
Before you begin, ensure you have:
- An Azion account
- A Resend account with API access
- Azion CLI installed and configured
- Node.js version 18 or higher
- pnpm package manager installed
- Basic understanding of JavaScript and Edge Functions
- Resend API key from your Resend dashboard
Getting started
Step 1: Set up your development environment
- Clone the Resend example repository:
git clone https://github.com/egermano/edge-functions-examples.gitcd edge-functions-examples/packages/resend
- Install the project dependencies:
pnpm install
- Review the project structure to understand the implementation:
ls -la
You should see the main files including the Edge Function implementation, configuration files, and email templates.
Step 2: Configure environment variables
- Create a
.env
file based on the example:
cp .env.example .env
- Edit the
.env
file to include your Resend API key:
# Resend API ConfigurationRESEND_API_KEY=your_resend_api_key_here
- Get your Resend API key from your Resend dashboard.
Step 3: Configure Resend integration
-
Set up your sending domain in Resend (if not already done):
- Add your domain in the Resend dashboard
- Configure DNS records for domain verification
- Verify domain ownership
-
Review email templates in your project to customize them for your needs.
Step 4: Build the project
Compile your Edge Function for deployment:
pnpm build
This command builds your Edge Function and prepares it for deployment to Azion’s edge network.
Step 5: Test locally
Before deploying, test your email function locally:
pnpm dev
This starts a local development server where you can test email sending functionality.
Deploying to Azion
Step 1: Authenticate with Azion
- Log in to your Azion account via CLI:
azion login
- Follow the authentication prompts to connect your CLI with your Azion account.
Step 2: Create secrets for API keys
For security, store your Resend API key as a secret:
azion create secret RESEND_API_KEY
When prompted, enter your Resend API key. This ensures your sensitive data is encrypted and secure.
Step 3: Deploy the Edge Function
Deploy your email application to Azion’s edge network:
azion deploy
The deployment process will:
- Upload your Edge Function code
- Configure the edge application
- Set up the necessary routing rules
- Configure environment variables and secrets
- Provide you with a unique domain
Step 4: Access your application
After deployment, you’ll receive a domain like https://xxxxxxx.map.azionedge.net
. Your email application will be available at this URL within a few minutes after DNS propagation.
Understanding the implementation
Email sending process
The Resend Edge Function typically handles:
- Request validation: Checking email parameters and authentication
- Email composition: Building email content with templates
- API integration: Communicating with Resend’s API
- Response handling: Processing API responses and errors
- Logging: Recording email sending activities
API integration example
Here’s how the Resend API integration works:
// Example Edge Function for sending emailsasync function sendEmail(request) { const { to, subject, html, text } = await request.json();
const response = await fetch('https://api.resend.com/emails', { method: 'POST', headers: { 'Authorization': `Bearer ${RESEND_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ from: 'your-email@yourdomain.com', to: to, subject: subject, html: html, text: text }) });
return response.json();}
Key benefits
- Performance: Email processing at the edge reduces latency
- Reliability: Resend’s robust infrastructure ensures delivery
- Scalability: Automatically scales with demand
- Global reach: Edge locations provide worldwide coverage
- Cost efficiency: Optimized email delivery costs
Testing your email application
Step 1: Test email sending functionality
- Navigate to your deployed application
- Use the email form to send test emails
- Verify emails are delivered to recipients
- Check email formatting and content
Step 2: Test error handling
- Invalid email addresses: Test with malformed email addresses
- Rate limiting: Test with rapid successive requests
- Authentication failures: Test with invalid API keys
- Network issues: Test error handling for API failures
Step 3: Performance testing
- Response time: Measure email sending response times
- Concurrent requests: Test multiple simultaneous email sends
- Error rates: Monitor success and failure rates
Common use cases
- Welcome emails: Send onboarding emails to new users
- Password resets: Handle password reset email notifications
- Order confirmations: Send transactional emails for purchases
- Notification emails: Send alerts and updates to users
- Contact forms: Handle form submissions with email notifications
Email templates and customization
Using HTML templates
Create dynamic email templates with placeholders:
<!DOCTYPE html><html><head> <title>Welcome to Our Service</title></head><body> <h1>Welcome, {{name}}!</h1> <p>Thank you for joining {{company}}. We're excited to have you on board.</p> <p>Your account is now active and ready to use.</p></body></html>
Template variables
Replace placeholders with dynamic content:
const emailTemplate = html.replace('{{name}}', userData.name) .replace('{{company}}', 'Your Company');
Troubleshooting
Common issues and solutions
- Email delivery failures: Check API key validity and domain configuration
- Rate limiting: Implement proper request throttling
- Template rendering: Verify template syntax and variable substitution
- Authentication errors: Ensure API key is correctly configured as a secret
Error handling best practices
- Detailed logging: Log all email sending attempts and results
- Retry mechanisms: Implement retry logic for temporary failures
- Graceful degradation: Handle API downtime appropriately
- User feedback: Provide clear status messages to users
Security considerations
API key management
- Use secrets: Always store API keys as Azion secrets
- Rotate regularly: Periodically rotate your API keys
- Monitor usage: Track API key usage and access patterns
- Limit permissions: Use API keys with minimal required permissions
Input validation
- Email validation: Validate email addresses before sending
- Content sanitization: Clean and validate email content
- Rate limiting: Implement rate limiting to prevent abuse
- Authentication: Add proper authentication to your email endpoints
Advanced features
Batch email sending
Implement batch email functionality for newsletter and marketing campaigns:
async function sendBatchEmails(recipients, template) { const batchSize = 100; for (let i = 0; i < recipients.length; i += batchSize) { const batch = recipients.slice(i, i + batchSize); await processBatch(batch, template); }}
Email tracking
Add tracking capabilities to monitor email engagement:
- Open tracking: Track when emails are opened
- Click tracking: Monitor link clicks in emails
- Bounce handling: Handle bounced emails appropriately
- Unsubscribe management: Process unsubscribe requests
Next steps
- Explore advanced email templating techniques
- Implement email analytics and tracking
- Add email scheduling and delayed sending
- Integrate with other Azion products like Edge Storage
- Monitor email delivery performance and optimize accordingly