UNPKG

@api-buddy/sendgrid

Version:

API Buddy integration for SendGrid - Email delivery service for transactional and marketing emails

303 lines (231 loc) 8 kB
# @api-buddy/sendgrid [![npm version](https://img.shields.io/npm/v/@api-buddy/sendgrid.svg)](https://www.npmjs.com/package/@api-buddy/sendgrid) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) A comprehensive SendGrid integration for Next.js applications, providing a simple and type-safe way to send transactional and marketing emails. ## Features - 🚀 **Easy Setup**: Get started quickly with a few simple steps - 🔒 **Type-Safe**: Full TypeScript support for all email options and responses -**Performance Optimized**: Efficient email sending with proper error handling - 🎣 **React Hooks**: Custom hooks for easy email sending from React components - 🛠 **CLI Tool**: Quick project setup with the included CLI - 📧 **Templates Support**: Built-in support for SendGrid's dynamic templates - 📊 **Analytics**: Track email opens, clicks, and other events ## Installation ```bash # Using npm npm install @api-buddy/sendgrid @sendgrid/mail # Using yarn yarn add @api-buddy/sendgrid @sendgrid/mail # Using pnpm pnpm add @api-buddy/sendgrid @sendgrid/mail ``` ## Quick Start ### 1. Set Up Environment Variables Create a `.env.local` file in your project root and add your SendGrid API key: ```env SENDGRID_API_KEY=your_sendgrid_api_key_here SENDGRID_FROM_EMAIL=your-email@example.com ``` ### 2. Initialize SendGrid in Your Next.js App Wrap your application with the `SendGridProvider` in your root layout: ```tsx // app/layout.tsx 'use client'; import { SendGridProvider } from '@api-buddy/sendgrid'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> <SendGridProvider config={{ // Optional: Configure default settings here defaultFrom: 'noreply@yourdomain.com', defaultReplyTo: 'support@yourdomain.com', }} > {children} </SendGridProvider> </body> </html> ); } ``` ### 3. Send Your First Email Create an API route to handle email sending: ```typescript // app/api/email/route.ts import { NextResponse } from 'next/server'; import { sendEmail } from '@api-buddy/sendgrid'; export async function POST(request: Request) { try { const { to, subject, text, html } = await request.json(); const result = await sendEmail({ to, from: 'noreply@yourdomain.com', subject, text, html, }); return NextResponse.json({ success: true, data: result }); } catch (error) { console.error('Error sending email:', error); return NextResponse.json( { success: false, error: 'Failed to send email' }, { status: 500 } ); } } ``` ### 4. Use the useEmail Hook in Your Components ```tsx 'use client'; import { useEmail } from '../hooks/useEmail'; export function ContactForm() { const { sendEmail, isLoading, error } = useEmail(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { await sendEmail({ to: 'contact@yourdomain.com', subject: 'New Contact Form Submission', text: 'Hello from the contact form!', html: '<p>Hello from the contact form!</p>', }); alert('Message sent successfully!'); } catch (err) { console.error('Failed to send message:', err); alert('Failed to send message. Please try again.'); } }; return ( <form onSubmit={handleSubmit}> {/* Your form fields */} <button type="submit" disabled={isLoading}> {isLoading ? 'Sending...' : 'Send Message'} </button> {error && <div className="error">{error.message}</div>} </form> ); } ``` ## CLI Setup For a quick setup, use the included CLI: ```bash npx @api-buddy/sendgrid ``` This will: 1. Install required dependencies 2. Create an API route for sending emails 3. Generate a custom `useEmail` hook 4. Set up an example contact form component 5. Update your environment variables ## API Reference ### `SendGridProvider` A context provider that makes the SendGrid client available throughout your application. #### Props - `config`: Configuration object - `apiKey`: Your SendGrid API key (optional, defaults to `process.env.SENDGRID_API_KEY`) - `defaultFrom`: Default "from" email address - `defaultReplyTo`: Default "reply to" email address - `mailSettings`: Default mail settings for all emails - `trackingSettings`: Default tracking settings for all emails - `asm`: Default ASM (Advanced Suppression Manager) settings - `ipPoolName`: Default IP pool name ### `useSendGrid()` A hook to access the SendGrid client and config from the nearest `SendGridProvider`. #### Returns - `client`: The SendGrid client instance - `config`: The current SendGrid configuration ### `sendEmail(options: EmailOptions): Promise<SendGridResponse>` Send an email using SendGrid. #### Parameters - `options`: Email options - `to`: Recipient email address or array of email addresses - `from`: Sender email address - `subject`: Email subject - `text`: Plain text content - `html`: HTML content - `templateId`: SendGrid template ID - `dynamicTemplateData`: Dynamic template data - `attachments`: Email attachments - `categories`: Email categories for tracking - `customArgs`: Custom arguments - `headers`: Custom headers - `mailSettings`: Mail settings - `trackingSettings`: Tracking settings - `replyTo`: Reply-to email address - `sendAt`: Send at timestamp (Unix timestamp) - `batchId`: Batch ID for scheduling - `asm`: ASM (Advanced Suppression Manager) settings - `ipPoolName`: IP pool name #### Returns A promise that resolves to the SendGrid API response. ### `useEmail()` A hook for sending emails from React components. #### Returns - `sendEmail`: Function to send an email - `isLoading`: Boolean indicating if an email is being sent - `error`: Error object if sending failed - `reset`: Function to reset the hook state ## Examples ### Sending a Simple Email ```typescript import { sendEmail } from '@api-buddy/sendgrid'; // In an API route or server component await sendEmail({ to: 'recipient@example.com', from: 'sender@example.com', subject: 'Hello from SendGrid', text: 'This is a test email', html: '<p>This is a test email</p>', }); ``` ### Using Dynamic Templates ```typescript await sendEmail({ to: 'recipient@example.com', from: 'sender@example.com', templateId: 'd-1234567890abcdef1234567890abcdef', dynamicTemplateData: { name: 'John Doe', verificationLink: 'https://example.com/verify?token=abc123', }, }); ``` ### Sending to Multiple Recipients ```typescript await sendEmail({ to: ['user1@example.com', 'user2@example.com'], from: 'sender@example.com', subject: 'Hello everyone!', text: 'This email is sent to multiple recipients', }); ``` ## Error Handling All email sending methods throw a `SendGridApiError` when something goes wrong. You can catch and handle these errors: ```typescript try { await sendEmail({ // ... }); } catch (error) { if (error.isRateLimit) { console.error('Rate limit exceeded:', error.message); } else if (error.isAuthError) { console.error('Authentication error:', error.message); } else { console.error('Error sending email:', error.message); } } ``` ## Contributing Contributions are welcome! Please open an issue or submit a pull request. ## License MIT ## Acknowledgments - [SendGrid](https://sendgrid.com/) - Email delivery service - [@sendgrid/mail](https://www.npmjs.com/package/@sendgrid/mail) - Official SendGrid Node.js library