Examples
Real-world code examples and use cases
Examples
Real-world examples of integrating NotiGrid into your applications.
Welcome Email on Signup
Send a welcome email when users sign up for your app.
Node.js / Express
const express = require('express');
const app = express();
app.post('/api/signup', async (req, res) => {
const { email, name } = req.body;
// Create user in database
const user = await db.users.create({ email, name });
// Send welcome email via NotiGrid
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'welcome-email',
channel: 'email',
to: email,
variables: {
name,
loginUrl: 'https://yourapp.com/login',
},
}),
});
res.json({ success: true, user });
});Password Reset Flow
Complete password reset implementation with email notifications.
// Request password reset
app.post('/api/forgot-password', async (req, res) => {
const { email } = req.body;
// Generate reset token
const resetToken = crypto.randomBytes(32).toString('hex');
const resetExpiry = new Date(Date.now() + 3600000); // 1 hour
// Save token to database
await db.users.update(
{ email },
{ resetToken, resetExpiry }
);
// Send reset email
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'password-reset',
channel: 'email',
to: email,
variables: {
resetLink: `https://yourapp.com/reset-password?token=${resetToken}`,
expiryTime: '1 hour',
},
}),
});
res.json({ success: true });
});Order Confirmation (Multi-channel)
Send order confirmations via both email and SMS.
async function sendOrderConfirmation(order) {
const notifications = [
// Email confirmation
{
template: 'order-confirmation-email',
channel: 'email',
to: order.email,
variables: {
orderId: order.id,
items: order.items,
total: order.total,
trackingUrl: order.trackingUrl,
},
},
// SMS notification
{
template: 'order-confirmation-sms',
channel: 'sms',
to: order.phone,
variables: {
orderId: order.id,
total: order.total,
},
},
];
// Send all notifications in parallel
await Promise.all(
notifications.map(notification =>
fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(notification),
})
)
);
}Slack Alert on Critical Error
Send Slack alerts when critical errors occur in production.
// Error monitoring middleware
app.use((error, req, res, next) => {
// Log error
console.error(error);
// Send Slack alert for 500 errors
if (res.statusCode >= 500) {
fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'critical-error-alert',
channel: 'slack',
variables: {
errorMessage: error.message,
stack: error.stack,
url: req.url,
method: req.method,
timestamp: new Date().toISOString(),
},
}),
}).catch(console.error); // Don't block response
}
res.status(500).json({ error: 'Internal server error' });
});Daily Summary Email (Scheduled)
Send daily summary emails using cron jobs or scheduled tasks.
// Using node-cron
const cron = require('node-cron');
// Run every day at 9 AM
cron.schedule('0 9 * * *', async () => {
const users = await db.users.findAll({ subscribed: true });
for (const user of users) {
// Get user's daily stats
const stats = await getUserDailyStats(user.id);
// Send summary email
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'daily-summary',
channel: 'email',
to: user.email,
variables: {
name: user.name,
newMessages: stats.newMessages,
tasks: stats.tasks,
date: new Date().toLocaleDateString(),
},
}),
});
}
});Push Notification on New Message
Send browser push notifications when users receive messages.
Backend (Send Notification)
app.post('/api/messages', async (req, res) => {
const { recipientId, message } = req.body;
// Save message to database
const savedMessage = await db.messages.create({
recipientId,
message,
createdAt: new Date(),
});
// Get recipient's push subscription
const recipient = await db.users.findById(recipientId);
if (recipient.pushToken) {
// Send push notification
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
channel: 'push',
to: recipient.pushToken,
title: 'New Message',
body: message.substring(0, 100),
data: {
messageId: savedMessage.id,
url: `/messages/${savedMessage.id}`,
},
}),
});
}
res.json({ success: true, message: savedMessage });
});Frontend (Subscribe to Push)
// Initialize SDK and subscribe
const notigrid = window.Notigrid.init({
projectId: 'YOUR_PROJECT_ID',
apiKey: 'YOUR_PUBLIC_API_KEY',
});
// Subscribe with user ID
await notigrid.subscribe({
userId: currentUser.id,
email: currentUser.email,
});
// Handle notification clicks
notigrid.on('notification:clicked', (notification) => {
// Navigate to message
window.location.href = notification.data.url;
});Bulk Email Campaign
Send email campaigns to multiple recipients efficiently.
async function sendEmailCampaign(campaign) {
const recipients = await db.users.findAll({
subscribed: true,
segment: campaign.segment,
});
// Batch requests (100 at a time)
const batchSize = 100;
for (let i = 0; i < recipients.length; i += batchSize) {
const batch = recipients.slice(i, i + batchSize);
await Promise.all(
batch.map(recipient =>
fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: campaign.templateId,
channel: 'email',
to: recipient.email,
variables: {
name: recipient.name,
unsubscribeUrl: `https://yourapp.com/unsubscribe?id=${recipient.id}`,
...campaign.variables,
},
}),
})
)
);
// Rate limiting: Wait 1 second between batches
if (i + batchSize < recipients.length) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
console.log(`Campaign sent to ${recipients.length} recipients`);
}Next.js Server Actions
Use NotiGrid with Next.js Server Actions.
// app/actions.ts
'use server';
export async function sendContactForm(formData: FormData) {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
const message = formData.get('message') as string;
// Send notification to your team
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'contact-form-submission',
channel: 'slack',
variables: {
name,
email,
message,
timestamp: new Date().toISOString(),
},
}),
});
// Send confirmation email to user
await fetch('https://api.notigrid.com/v1/notify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIGRID_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'contact-form-confirmation',
channel: 'email',
to: email,
variables: { name },
}),
});
return { success: true };
}Looking for more examples? Check out our GitHub examples repository or join our Discord community.