@api-buddy/sendgrid v0.4.108
@api-buddy/sendgrid
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
# 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:
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:
// 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:
// 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
'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:
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 objectapiKey
: Your SendGrid API key (optional, defaults toprocess.env.SENDGRID_API_KEY
)defaultFrom
: Default "from" email addressdefaultReplyTo
: Default "reply to" email addressmailSettings
: Default mail settings for all emailstrackingSettings
: Default tracking settings for all emailsasm
: Default ASM (Advanced Suppression Manager) settingsipPoolName
: Default IP pool name
useSendGrid()
A hook to access the SendGrid client and config from the nearest SendGridProvider
.
Returns
client
: The SendGrid client instanceconfig
: The current SendGrid configuration
sendEmail(options: EmailOptions): Promise<SendGridResponse>
Send an email using SendGrid.
Parameters
options
: Email optionsto
: Recipient email address or array of email addressesfrom
: Sender email addresssubject
: Email subjecttext
: Plain text contenthtml
: HTML contenttemplateId
: SendGrid template IDdynamicTemplateData
: Dynamic template dataattachments
: Email attachmentscategories
: Email categories for trackingcustomArgs
: Custom argumentsheaders
: Custom headersmailSettings
: Mail settingstrackingSettings
: Tracking settingsreplyTo
: Reply-to email addresssendAt
: Send at timestamp (Unix timestamp)batchId
: Batch ID for schedulingasm
: ASM (Advanced Suppression Manager) settingsipPoolName
: 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 emailisLoading
: Boolean indicating if an email is being senterror
: Error object if sending failedreset
: Function to reset the hook state
Examples
Sending a Simple Email
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
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
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:
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 - Email delivery service
- @sendgrid/mail - Official SendGrid Node.js library