Integrate Email/SMS Notifications for Orders in Sanity E-commerce

3 replies
Last updated: Feb 2, 2021
I'm building an e-commerce store and I'm wondering how I can integrate text messages or emails notification to clients after they make an order. Any help would be appreciated
AI Update

For sending email and SMS notifications to clients after they make an order in your e-commerce store, webhooks are the stable, production-ready approach that Sanity has offered for years. Webhooks automatically send HTTP requests to your endpoints when content changes occur, making them perfect for triggering order notifications.

How Webhooks Work for Order Notifications

Webhooks are GROQ-powered HTTP callbacks that trigger when documents are created, updated, or deleted in your Content Lake. Here's how to set them up for e-commerce order notifications:

1. Set Up Your Notification Endpoint

First, create an endpoint on your server (or serverless function) that will receive webhook requests and send the actual email/SMS. This could be:

  • A Next.js API route (/api/send-order-notification)
  • A serverless function on Vercel, Netlify, or AWS Lambda
  • An endpoint on your existing backend

2. Create the Webhook in Sanity

You can create webhooks through the Sanity Manage console:

  1. Go to your project settings
  2. Navigate to the API section
  3. Click "Create webhook"
  4. Configure:
    • Name: "Order Notification"
    • URL: Your endpoint URL (e.g., https://yoursite.com/api/send-order-notification)
    • Dataset: Choose your dataset (e.g., production)
    • Trigger on: Create
    • Filter: _type == "order"
    • Projection: {_id, customerEmail, customerPhone, orderTotal, items}

The projection uses GROQ to shape exactly what data gets sent to your endpoint, keeping payloads lean and focused.

3. Implement Your Notification Endpoint

Here's an example Next.js API route that receives the webhook and sends notifications:

// app/api/send-order-notification/route.ts
import { NextRequest, NextResponse } from 'next/server'
import sgMail from '@sendgrid/mail'
import twilio from 'twilio'

sgMail.setApiKey(process.env.SENDGRID_API_KEY!)
const twilioClient = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
)

export async function POST(request: NextRequest) {
  try {
    const order = await request.json()
    
    // Send email
    await sgMail.send({
      to: order.customerEmail,
      from: 'orders@yourstore.com',
      subject: 'Order Confirmation',
      html: `<h1>Thank you for your order!</h1><p>Order total: $${order.orderTotal}</p>`
    })
    
    // Send SMS
    if (order.customerPhone) {
      await twilioClient.messages.create({
        body: `Thank you for your order! Total: $${order.orderTotal}. We'll send updates soon.`,
        from: process.env.TWILIO_PHONE_NUMBER,
        to: order.customerPhone
      })
    }
    
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Notification error:', error)
    return NextResponse.json({ error: 'Failed to send notifications' }, { status: 500 })
  }
}

4. Secure Your Webhook

Add webhook signature verification to ensure requests are actually from Sanity:

import { isValidSignature, SIGNATURE_HEADER_NAME } from '@sanity/webhook'

const secret = process.env.SANITY_WEBHOOK_SECRET!
const signature = request.headers.get(SIGNATURE_HEADER_NAME)!
const body = await request.text()

if (!isValidSignature(body, signature, secret)) {
  return NextResponse.json({ error: 'Invalid signature' }, { status: 401 })
}

You'll find the webhook secret in the Sanity Manage console after creating your webhook.

Email/SMS Service Setup

You'll need accounts with notification providers:

About Sanity Functions

Sanity also offers Functions, a newer serverless compute option that runs directly on Sanity's infrastructure. However, Functions are currently experimental with APIs subject to change. For production e-commerce systems where reliable order notifications are critical, webhooks are the stable, battle-tested choice.

You might consider Functions in the future once they reach general availability, but for now, webhooks give you:

  • Production stability - Used by thousands of Sanity projects
  • Full control - Your own infrastructure and error handling
  • Flexibility - Easy to integrate with any service or custom logic
  • Debugging - Standard server logs and monitoring tools

Testing Your Webhook

Before going live, test your webhook with tools like:

  • webhook.site - Inspect webhook payloads
  • Beeceptor - Mock endpoints for testing
  • Sanity's webhook testing feature in the Manage console

Check out the full webhooks documentation and best practices guide for more details on filters, projections, and advanced configurations!

Show original thread
3 replies
You could integrate a service like Twilio where you hit their SMS API upon completion of a successful order. https://www.twilio.com/sms
Thanks
Spot on. And for email you could implement something like https://postmarkapp.com/

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?