npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@api-buddy/sendgrid

v3.0.0

Published

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

Readme

@api-buddy/sendgrid

npm version License: 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

# 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
[email protected]

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: '[email protected]',
            defaultReplyTo: '[email protected]',
          }}
        >
          {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: '[email protected]',
      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: '[email protected]',
        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 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

import { sendEmail } from '@api-buddy/sendgrid';

// In an API route or server component
await sendEmail({
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Hello from SendGrid',
  text: 'This is a test email',
  html: '<p>This is a test email</p>',
});

Using Dynamic Templates

await sendEmail({
  to: '[email protected]',
  from: '[email protected]',
  templateId: 'd-1234567890abcdef1234567890abcdef',
  dynamicTemplateData: {
    name: 'John Doe',
    verificationLink: 'https://example.com/verify?token=abc123',
  },
});

Sending to Multiple Recipients

await sendEmail({
  to: ['[email protected]', '[email protected]'],
  from: '[email protected]',
  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