Keplars

Firebase Cloud Functions Integration

Send emails using Keplars with Firebase Cloud Functions

Deploy Keplars as a Firebase Cloud Function to send transactional and scheduled emails from your Firebase projects.

Overview

This integration provides a ready-to-use Firebase Cloud Function that connects to Keplars email service. Built with Node.js 18 and TypeScript, it seamlessly integrates with your existing Firebase project.

GitHub Repository: github.com/KeplarsHQ/firebase-cloud-functions-example

Features

  • Template-based emails - Use pre-designed templates with dynamic variables
  • Raw HTML/Text emails - Send custom HTML or plain text without templates
  • Scheduled emails - Schedule emails with timezone support
  • Instant delivery - 0-5 second delivery for critical emails
  • TypeScript - Full type safety with Node.js 18
  • Firebase Auth - Optional integration with Firebase Authentication

Prerequisites

Before starting, you'll need:

Quick Start

1. Clone the Example

git clone https://github.com/KeplarsHQ/firebase-cloud-functions-example.git
cd firebase-cloud-functions-example

2. Create Firebase Project

  1. Go to Firebase Console
  2. Click "Add project" and follow the wizard
  3. Copy your project ID

Update .firebaserc with your project ID:

{
  "projects": {
    "default": "your-firebase-project-id"
  }
}

Or use the CLI:

firebase use --add

4. Configure API Key

Create a .env file in the functions folder:

cd functions
cp .env.example .env

Add your Keplars API key:

KEPLARS_API_KEY=kms_your_actual_api_key_here

5. Install Dependencies

npm install
cd ..

6. Start Local Development

firebase emulators:start

The function will be available at:

http://127.0.0.1:5001/your-project-id/us-central1/keplarsEmail

7. Test the Function

Send a test email:

curl --request POST 'http://127.0.0.1:5001/your-project-id/us-central1/keplarsEmail' \
  --header 'Content-Type: application/json' \
  --data @test-text-email.json

Deployment

Deploy to Firebase Cloud

  1. Set your API key as a secret:
firebase functions:secrets:set KEPLARS_API_KEY
# Paste your key when prompted
  1. Deploy the function:
firebase deploy --only functions

Your function will be live at:

https://us-central1-your-project-id.cloudfunctions.net/keplarsEmail
  1. Get your function URL:
firebase functions:list

Usage Examples

Template-Based Email

{
  "to": ["[email protected]"],
  "template_id": "your_template_id",
  "params": {
    "user_name": "John Doe",
    "verification_code": "123456"
  },
  "delivery_type": "instant"
}

Plain Text Email

{
  "to": ["[email protected]"],
  "subject": "Welcome!",
  "body": "Thanks for signing up. We're excited to have you.",
  "delivery_type": "instant"
}

HTML Email

{
  "to": ["[email protected]"],
  "subject": "Welcome!",
  "html": "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
  "is_html": true,
  "delivery_type": "instant"
}

Scheduled Email

{
  "to": ["[email protected]"],
  "subject": "Weekly Newsletter",
  "html": "<h1>This Week's Updates</h1>",
  "scheduled_at": "2026-01-25T10:00:00",
  "timezone": "America/New_York"
}

Client Integration

JavaScript/TypeScript

const response = await fetch(
  'https://us-central1-your-project-id.cloudfunctions.net/keplarsEmail',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      to: ['[email protected]'],
      template_id: 'your_template_id',
      params: {
        user_name: 'John',
        verification_code: '123456'
      },
      delivery_type: 'instant'
    })
  }
);

const data = await response.json();
console.log('Email sent!', data);

React Example

function WelcomeEmail() {
  const sendWelcome = async (email: string, name: string) => {
    await fetch(
      'https://us-central1-your-project-id.cloudfunctions.net/keplarsEmail',
      {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          to: [email],
          template_id: 'your_welcome_template_id',
          params: {user_name: name}
        })
      }
    );
  };

  return <button onClick={() => sendWelcome('[email protected]', 'Jane')}>
    Send Welcome Email
  </button>;
}

Next.js API Route

// app/api/send-email/route.ts
export async function POST(request: Request) {
  const {email, name} = await request.json();

  const response = await fetch(
    process.env.FIREBASE_FUNCTION_URL + '/keplarsEmail',
    {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        to: [email],
        template_id: process.env.KEPLARS_TEMPLATE_ID,
        params: {user_name: name}
      })
    }
  );

  const data = await response.json();
  return Response.json({success: !data.error, data});
}

Security

Restrict CORS Origins

For production, update CORS in functions/src/index.ts:

res.set("Access-Control-Allow-Origin", "https://yourdomain.com");

Add Firebase Authentication

Integrate with Firebase Auth to require authentication:

import * as admin from "firebase-admin";

// Verify ID token
const token = req.headers.authorization?.split('Bearer ')[1];
const decodedToken = await admin.auth().verifyIdToken(token);

Environment Variables

  • Never commit your .env file
  • Use Firebase secrets for production: firebase functions:secrets:set
  • Use different API keys for development and production
  • Monitor usage on both Firebase and Keplars dashboards

API Reference

Request Fields

Required:

  • to - Array of email addresses
  • For template emails: template_id
  • For raw emails: subject + either body or html

Optional:

  • params - Template variables (template emails only)
  • is_html - Set to true for HTML content
  • delivery_type - Either "instant" or "queue"
  • scheduled_at - ISO 8601 timestamp for scheduled emails
  • timezone - IANA timezone (e.g., "America/New_York")
  • from - Sender email
  • fromName - Sender name

Response Format

Success:

{
  "id": "msg_...",
  "object": "email",
  "status": "queued",
  "from": "[email protected]",
  "to": ["[email protected]"],
  "created_at": "2026-01-22T22:14:04.470Z",
  "metadata": {
    "priority": "instant",
    "estimated_delivery": "0-5 seconds",
    "recipients_count": 1
  }
}

Error:

{
  "success": false,
  "error": "Error message",
  "code": "ERROR_CODE"
}

Troubleshooting

Function not found

Make sure you've deployed the function:

firebase deploy --only functions

API key not configured

Ensure your API key is set:

# Local
echo "KEPLARS_API_KEY=kms_..." >> functions/.env

# Production
firebase functions:secrets:set KEPLARS_API_KEY

Email not arriving

  • Check your spam folder
  • Verify template exists in Keplars dashboard
  • Ensure email provider is connected in Keplars
  • Check Firebase function logs: firebase functions:log

Function not deploying

  • Run npm run build in the functions folder
  • Check for TypeScript errors
  • Ensure you're using Node.js 18+

Resources

Support

Need help? Reach out:

On this page