This example demonstrates how to use the Nylas SDK in a Cloudflare Worker to send email attachments. It provides a simple web interface for uploading files and sending them as email attachments.
- Simple Web UI: Drag & drop or click to upload files
- File Validation: Automatic file size and type validation (10MB max)
- Real-time Feedback: Loading states and success/error messages
- Email Sending: Uses the Nylas SDK to send emails with attachments
- Edge Computing: Runs on Cloudflare's global edge network
- Node.js Compatibility: Uses
nodejs_compatflag for seamless Node.js module support
Before getting started, you'll need:
- Nylas Account: Sign up for free
- Cloudflare Account: Sign up for free
- Node.js: Version 16 or higher
- Nylas Application: Created in your Nylas Dashboard
- Connected Email Account: At least one email account connected to your Nylas application
# Navigate to the edge-environment directory
cd examples/edge-environment
# Install dependencies
npm installCopy the .dev.vars file and update it with your Nylas credentials:
# Update .dev.vars with your actual values
NYLAS_API_KEY=your_nylas_api_key_here
NYLAS_API_URI=https://api.us.nylas.com
NYLAS_GRANT_ID=your_grant_id_here
TEST_EMAIL=test@example.comHow to get these values:
- NYLAS_API_KEY: Found in your Nylas Dashboard under your application settings
- NYLAS_GRANT_ID: The ID of a connected email account (found in Dashboard > Grants)
- NYLAS_API_URI: Use
https://api.us.nylas.comfor US region, or your specific region's API URL
Edit wrangler.toml and update the name and environment variables as needed:
name = "your-worker-name" # Choose a unique name for your worker
[env.development.vars]
NYLAS_API_KEY = "your_api_key"
NYLAS_GRANT_ID = "your_grant_id"
# ... other variablesnpm run devThis will:
- Start the Wrangler development server
- Make your worker available at
http://localhost:8787 - Enable hot-reloading for code changes
- Load environment variables from
.dev.vars
- Open
http://localhost:8787in your browser - Fill in the email form:
- Recipient Email: Enter a valid email address
- Subject: Enter an email subject
- Message: Enter your message content
- Attachment: Upload a file (max 10MB)
- Click "Send Email with Attachment"
- Check the recipient's inbox for the email
- File Size Limit: The worker is configured with a 10MB file size limit
- Supported Files: All file types are supported (PDFs, images, documents, etc.)
- Error Handling: Check the browser console and worker logs for debugging
- Hot Reloading: Code changes will automatically reload the worker
For security, use Wrangler secrets instead of environment variables in production:
# Set your API key as a secret
wrangler secret put NYLAS_API_KEY
# Enter your API key when prompted
# Set your Grant ID as a secret
wrangler secret put NYLAS_GRANT_ID
# Enter your Grant ID when prompted
# Set default recipient email (optional)
wrangler secret put TEST_EMAIL
# Enter default email when promptednpm run deployThis will:
- Build and upload your worker to Cloudflare
- Make it available at
https://your-worker-name.your-subdomain.workers.dev - Use the production environment configuration
Visit your worker's URL and test the file upload functionality.
If you have a custom domain managed by Cloudflare:
- Add a route in
wrangler.toml:
[[routes]]
pattern = "attachments.yourdomain.com/*"
zone_name = "yourdomain.com"- Deploy with the route:
wrangler deployUser Browser → Cloudflare Worker → Nylas API → Email Provider
- File Upload: User uploads a file through the web interface
- Form Processing: Worker receives multipart form data
- File Processing: File is converted to Buffer for efficient binary transfer
- Email Sending: Nylas SDK processes and sends the email with attachment
- Response: User receives confirmation or error message
src/worker.ts: Main worker logic and request handlingwrangler.toml: Cloudflare Worker configuration with Node.js compatibilitypackage.json: Dependencies and scripts.dev.vars: Development environment variables
This worker uses the Nylas SDK with optimizations for Cloudflare Workers:
- SDK Integration: Uses the official Nylas Node.js SDK
- Buffer Attachments: Uses native Buffer objects for efficient binary data handling
- Direct Binary Transfer: No base64 encoding overhead (33% smaller than base64)
- Edge Optimized: Designed specifically for Cloudflare Workers runtime
This worker uses:
compatibility_date = "2024-09-23": Enables automatic Node.js built-in module supportnodejs_compatcompatibility flag: Additional Node.js compatibility features
These settings enable Node.js built-in modules like crypto, path, fs, and stream that are required by the Nylas SDK. The Buffer attachment approach ensures optimal performance and compatibility with the Cloudflare Workers edge environment.
GET /: Serves the HTML upload interfacePOST /send-attachment: Handles file upload and email sendingOPTIONS /*: Handles CORS preflight requests
Update the file size limit in src/worker.ts:
// Check file size (10MB limit)
const maxSize = 10 * 1024 * 1024; // Change this valueFor extremely large files (>25MB), you can use ReadableStream instead of Buffer:
// Alternative: Use ReadableStream for very large files
const stream = file.stream();
const sendRequest: SendMessageRequest = {
// ... other fields
attachments: [{
filename: file.name,
contentType: getContentType(file.name),
content: stream, // Use stream instead of buffer
size: file.size,
}],
};Modify the email HTML template in src/worker.ts:
body: `
<div style="font-family: Arial, sans-serif;">
<h2>Your Custom Email Template</h2>
<p>${message}</p>
<!-- Add your custom styling and content -->
</div>
`,Add file type validation in the worker:
// Validate file type
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!allowedTypes.includes(getContentType(file.name))) {
return new Response(
JSON.stringify({ error: 'File type not allowed' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}Error: "Missing required environment variables"
- Ensure all environment variables are set in
.dev.vars(development) or as secrets (production) - Check variable names match exactly
Error: "Could not resolve [module]" (crypto, path, fs, stream)
- Ensure
compatibility_date = "2024-09-23"or later is set inwrangler.toml - Ensure
compatibility_flags = ["nodejs_compat"]is also set - These settings enable Node.js built-in modules required by the Nylas SDK
- The worker uses Buffer objects for efficient binary attachment handling
Error: "File size exceeds 10MB limit"
- Reduce file size or increase the limit in the worker code
- Note: Cloudflare Workers have memory and CPU time limits
Error: "Invalid file upload"
- Ensure you're uploading a valid file
- Check that the form is submitting properly
Error: "optionParams.form.getHeaders is not a function"
- This was an old SDK compatibility issue, now resolved
- The worker uses Buffer attachments instead of problematic form-data
- This error should not occur with the current implementation
Email not received
- Verify the recipient email address
- Check spam/junk folders
- Verify your Nylas grant has send permissions
- Check Nylas Dashboard for any API errors
Add logging to the worker for debugging:
console.log('File details:', {
name: file.name,
size: file.size,
type: file.type
});View logs with:
wrangler tail- Local Attachment Examples: See
../messages/examples/for Node.js examples - Nylas SDK Documentation: https://developer.nylas.com
- Cloudflare Workers Docs: https://developers.cloudflare.com/workers/
Found an issue or want to improve this example? Please:
- Check existing issues in the Nylas Node.js SDK repository
- Create a new issue or pull request
- Follow the contributing guidelines
This example is part of the Nylas Node.js SDK and is licensed under the MIT License.