Appearance
Send Your First Notification
This guide will walk you through sending your first notification with Nexus. We'll cover everything from basic API calls to creating workflows and templates.
Before You Start
Make sure you have:
- ✅ Installed Nexus
- ✅ Created an organization
- ✅ Your API key ready (
sk_test_...orsk_live_...)
Method 1: Simple API Call
The fastest way to send a notification is with a direct API call.
Basic Email Notification
bash
curl -X POST https://api.nexus.dev/v1/messages/email \
-H "Authorization: Bearer sk_test_1234567890abcdef" \
-H "Content-Type: application/json" \
-d '{
"to": "[email protected]",
"subject": "Welcome to Nexus!",
"content": "Thanks for trying Nexus. This is your first notification!",
"from": {
"email": "[email protected]",
"name": "Your App Name"
}
}'javascript
const response = await fetch('https://api.nexus.dev/v1/messages/email', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
body: JSON.stringify({
to: '[email protected]',
subject: 'Welcome to Nexus!',
content: 'Thanks for trying Nexus. This is your first notification!',
from: {
email: '[email protected]',
name: 'Your App Name'
}
})
})
const result = await response.json()
console.log('Message sent:', result.data.id)python
import requests
response = requests.post(
'https://api.nexus.dev/v1/messages/email',
headers={
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
json={
'to': '[email protected]',
'subject': 'Welcome to Nexus!',
'content': 'Thanks for trying Nexus. This is your first notification!',
'from': {
'email': '[email protected]',
'name': 'Your App Name'
}
}
)
result = response.json()
print('Message sent:', result['data']['id'])php
<?php
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.nexus.dev/v1/messages/email',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer sk_test_1234567890abcdef',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode([
'to' => '[email protected]',
'subject' => 'Welcome to Nexus!',
'content' => 'Thanks for trying Nexus. This is your first notification!',
'from' => [
'email' => '[email protected]',
'name' => 'Your App Name'
]
])
]);
$response = curl_exec($ch);
$result = json_decode($response, true);
echo 'Message sent: ' . $result['data']['id'];
?>Expected Response
json
{
"data": {
"id": "msg_1234567890abcdef",
"status": "sent",
"to": "[email protected]",
"subject": "Welcome to Nexus!",
"channel": "email",
"createdAt": "2024-01-15T10:30:00Z",
"deliveredAt": null
}
}Basic SMS Notification
bash
curl -X POST https://api.nexus.dev/v1/messages/sms \
-H "Authorization: Bearer sk_test_1234567890abcdef" \
-H "Content-Type: application/json" \
-d '{
"to": "+1234567890",
"content": "Welcome to Nexus! This is your first SMS notification.",
"from": "+1987654321"
}'javascript
const response = await fetch('https://api.nexus.dev/v1/messages/sms', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
body: JSON.stringify({
to: '+1234567890',
content: 'Welcome to Nexus! This is your first SMS notification.',
from: '+1987654321'
})
})
const result = await response.json()
console.log('SMS sent:', result.data.id)python
import requests
response = requests.post(
'https://api.nexus.dev/v1/messages/sms',
headers={
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
json={
'to': '+1234567890',
'content': 'Welcome to Nexus! This is your first SMS notification.',
'from': '+1987654321'
}
)
result = response.json()
print('SMS sent:', result['data']['id'])Method 2: Using Workflows (Recommended)
Workflows provide more flexibility and allow you to send notifications across multiple channels with templates and conditional logic.
Step 1: Create a Subscriber
First, create a subscriber to receive notifications:
bash
curl -X POST https://api.nexus.dev/v1/subscribers \
-H "Authorization: Bearer sk_test_1234567890abcdef" \
-H "Content-Type: application/json" \
-d '{
"subscriberId": "user_123",
"email": "[email protected]",
"phone": "+1234567890",
"firstName": "John",
"lastName": "Doe",
"data": {
"plan": "free",
"signupDate": "2024-01-15",
"preferences": {
"marketing": true,
"transactional": true
}
}
}'javascript
const subscriber = await fetch('https://api.nexus.dev/v1/subscribers', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
body: JSON.stringify({
subscriberId: 'user_123',
email: '[email protected]',
phone: '+1234567890',
firstName: 'John',
lastName: 'Doe',
data: {
plan: 'free',
signupDate: '2024-01-15',
preferences: {
marketing: true,
transactional: true
}
}
})
})
const result = await subscriber.json()
console.log('Subscriber created:', result.data.subscriberId)Step 2: Create Your First Workflow
Create a simple welcome workflow:
bash
1. Go to Workflows in your dashboard
2. Click "Create Workflow"
3. Enter workflow details:
- Name: "Welcome Email"
- Trigger: "user-signup"
- Description: "Send welcome email to new users"
4. Add an Email step:
- Subject: "Welcome to {{company.name}}!"
- Content: "Hi {{subscriber.firstName}}, thanks for signing up!"
5. Save the workflowjavascript
const workflow = await fetch('https://api.nexus.dev/v1/workflows', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Welcome Email',
identifier: 'user-signup',
description: 'Send welcome email to new users',
steps: [
{
type: 'email',
name: 'Send Welcome Email',
subject: 'Welcome to {{company.name}}!',
content: 'Hi {{subscriber.firstName}}, thanks for signing up! We\'re excited to have you on board.',
from: {
email: '[email protected]',
name: 'Your App Name'
}
}
]
})
})
const result = await workflow.json()
console.log('Workflow created:', result.data.id)Step 3: Trigger the Workflow
Now trigger the workflow for your subscriber:
bash
curl -X POST https://api.nexus.dev/v1/events/trigger \
-H "Authorization: Bearer sk_test_1234567890abcdef" \
-H "Content-Type: application/json" \
-d '{
"name": "user-signup",
"to": {
"subscriberId": "user_123"
},
"payload": {
"signupDate": "2024-01-15T10:30:00Z",
"source": "website",
"plan": "free"
}
}'javascript
const trigger = await fetch('https://api.nexus.dev/v1/events/trigger', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'user-signup',
to: {
subscriberId: 'user_123'
},
payload: {
signupDate: '2024-01-15T10:30:00Z',
source: 'website',
plan: 'free'
}
})
})
const result = await trigger.json()
console.log('Workflow triggered:', result.data.transactionId)python
import requests
from datetime import datetime
response = requests.post(
'https://api.nexus.dev/v1/events/trigger',
headers={
'Authorization': 'Bearer sk_test_1234567890abcdef',
'Content-Type': 'application/json'
},
json={
'name': 'user-signup',
'to': {
'subscriberId': 'user_123'
},
'payload': {
'signupDate': datetime.now().isoformat(),
'source': 'website',
'plan': 'free'
}
}
)
result = response.json()
print('Workflow triggered:', result['data']['transactionId'])Method 3: Using SDK
Install and use the official Nexus SDK for easier integration:
Installation
bash
npm install @nexus/nodebash
pip install nexus-notificationsbash
gem install nexus-notificationsbash
composer require nexus/notificationsSDK Usage
javascript
import { Nexus } from '@nexus/node'
const nexus = new Nexus({
apiKey: process.env.NEXUS_API_KEY
})
// Create subscriber
const subscriber = await nexus.subscribers.create({
subscriberId: 'user_123',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe'
})
// Trigger workflow
const result = await nexus.trigger('user-signup', {
to: {
subscriberId: 'user_123'
},
payload: {
welcomeMessage: 'Thanks for joining us!',
accountType: 'free'
}
})
console.log('Notification sent:', result.transactionId)python
from nexus import Nexus
nexus = Nexus(api_key=os.getenv('NEXUS_API_KEY'))
# Create subscriber
subscriber = nexus.subscribers.create(
subscriber_id='user_123',
email='[email protected]',
first_name='John',
last_name='Doe'
)
# Trigger workflow
result = nexus.trigger(
'user-signup',
to={'subscriberId': 'user_123'},
payload={
'welcomeMessage': 'Thanks for joining us!',
'accountType': 'free'
}
)
print('Notification sent:', result.transaction_id)ruby
require 'nexus'
nexus = Nexus::Client.new(api_key: ENV['NEXUS_API_KEY'])
# Create subscriber
subscriber = nexus.subscribers.create(
subscriberId: 'user_123',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe'
)
# Trigger workflow
result = nexus.trigger(
'user-signup',
to: { subscriberId: 'user_123' },
payload: {
welcomeMessage: 'Thanks for joining us!',
accountType: 'free'
}
)
puts "Notification sent: #{result.transaction_id}"php
<?php
use Nexus\Client;
$nexus = new Client(['apiKey' => $_ENV['NEXUS_API_KEY']]);
// Create subscriber
$subscriber = $nexus->subscribers->create([
'subscriberId' => 'user_123',
'email' => '[email protected]',
'firstName' => 'John',
'lastName' => 'Doe'
]);
// Trigger workflow
$result = $nexus->trigger('user-signup', [
'to' => ['subscriberId' => 'user_123'],
'payload' => [
'welcomeMessage' => 'Thanks for joining us!',
'accountType' => 'free'
]
]);
echo 'Notification sent: ' . $result->transactionId;
?>Advanced Examples
Multi-Channel Workflow
Create a workflow that sends notifications across multiple channels:
javascript
const workflow = await nexus.workflows.create({
name: 'User Onboarding',
identifier: 'user-onboarding',
steps: [
{
type: 'email',
name: 'Welcome Email',
subject: 'Welcome to {{company.name}}!',
content: 'Hi {{subscriber.firstName}}, welcome aboard!'
},
{
type: 'delay',
duration: '1 hour'
},
{
type: 'sms',
name: 'Setup Reminder',
content: 'Hi {{subscriber.firstName}}, don\'t forget to complete your profile setup!',
conditions: {
subscriber: {
phone: { $exists: true }
}
}
},
{
type: 'delay',
duration: '1 day'
},
{
type: 'push',
name: 'Tips Notification',
title: 'Pro Tips',
body: 'Check out these tips to get the most out of {{company.name}}',
conditions: {
subscriber: {
data: {
hasCompletedOnboarding: false
}
}
}
}
]
})python
# Trigger multi-channel workflow
result = nexus.trigger(
'user-onboarding',
to={
'subscriberId': 'user_123',
'email': '[email protected]',
'phone': '+1234567890'
},
payload={
'firstName': 'John',
'plan': 'premium',
'onboardingStep': 1,
'referralCode': 'ABC123'
},
# Override specific channels
overrides={
'email': {
'subject': 'Welcome to Premium, {{subscriber.firstName}}!'
},
'sms': {
'content': 'Welcome {{subscriber.firstName}}! Your premium account is ready.'
}
}
)Conditional Logic
Send different notifications based on subscriber data:
javascript
const workflow = await nexus.workflows.create({
name: 'Welcome Based on Plan',
identifier: 'plan-based-welcome',
steps: [
{
type: 'email',
name: 'Free Plan Welcome',
subject: 'Welcome to {{company.name}} - Free Plan',
templateId: 'free-welcome-template',
conditions: {
payload: {
plan: 'free'
}
}
},
{
type: 'email',
name: 'Premium Plan Welcome',
subject: 'Welcome to {{company.name}} Premium!',
templateId: 'premium-welcome-template',
conditions: {
payload: {
plan: 'premium'
}
}
},
{
type: 'delay',
duration: '3 days'
},
{
type: 'email',
name: 'Upgrade Prompt',
subject: 'Upgrade to Premium',
templateId: 'upgrade-prompt-template',
conditions: {
payload: {
plan: 'free'
}
}
}
]
})
// Trigger for free user
await nexus.trigger('plan-based-welcome', {
to: { subscriberId: 'user_free' },
payload: { plan: 'free', trialDays: 14 }
})
// Trigger for premium user
await nexus.trigger('plan-based-welcome', {
to: { subscriberId: 'user_premium' },
payload: { plan: 'premium', features: ['advanced-analytics', 'priority-support'] }
})Bulk Notifications
Send notifications to multiple subscribers:
javascript
// Send to multiple subscribers
const result = await nexus.bulkTrigger('newsletter', {
to: [
{ subscriberId: 'user_1', email: '[email protected]' },
{ subscriberId: 'user_2', email: '[email protected]' },
{ subscriberId: 'user_3', email: '[email protected]' }
],
payload: {
newsletterTitle: 'Monthly Update - January 2024',
articles: [
{ title: 'New Features Released', url: 'https://blog.example.com/new-features' },
{ title: 'Customer Success Story', url: 'https://blog.example.com/success-story' }
]
}
})
console.log(`Bulk notification sent to ${result.totalSubscribers} subscribers`)python
# Create a topic
topic = nexus.topics.create(
key='product-updates',
name='Product Updates'
)
# Add subscribers to topic
nexus.topics.add_subscribers('product-updates', {
'subscribers': ['user_1', 'user_2', 'user_3', 'user_4']
})
# Send to all topic subscribers
result = nexus.trigger(
'product-announcement',
to={'type': 'topic', 'topicKey': 'product-updates'},
payload={
'productName': 'Nexus 2.0',
'releaseDate': '2024-02-01',
'features': ['Enhanced API', 'New Dashboard', 'Better Performance']
}
)Verification and Testing
Check Notification Status
bash
curl -H "Authorization: Bearer sk_test_..." \
https://api.nexus.dev/v1/messages/msg_1234567890abcdef
# Response includes delivery status
{
"data": {
"id": "msg_1234567890abcdef",
"status": "delivered",
"deliveredAt": "2024-01-15T10:31:25Z",
"opens": 0,
"clicks": 0
}
}javascript
// Get recent messages for a subscriber
const messages = await nexus.messages.list({
subscriberId: 'user_123',
limit: 10
})
messages.data.forEach(message => {
console.log(`${message.channel}: ${message.status} - ${message.subject}`)
})View Activity Feed
bash
1. Go to Activity in your dashboard
2. Filter by subscriber, workflow, or channel
3. View detailed delivery status
4. Check open/click rates
5. Debug failed notificationsjavascript
const activities = await nexus.activities.list({
subscriberId: 'user_123',
status: 'failed',
limit: 50
})
// Debug failed notifications
activities.data.forEach(activity => {
if (activity.status === 'failed') {
console.log('Failed notification:', activity.error)
}
})Common Use Cases
1. User Registration Welcome
javascript
// In your signup endpoint
app.post('/api/signup', async (req, res) => {
const user = await createUser(req.body)
// Create subscriber in Nexus
await nexus.subscribers.create({
subscriberId: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
data: {
signupDate: new Date().toISOString(),
source: req.body.source || 'website',
plan: user.plan
}
})
// Send welcome notification
await nexus.trigger('user-signup', {
to: { subscriberId: user.id },
payload: {
firstName: user.firstName,
verificationUrl: `${process.env.APP_URL}/verify/${user.verificationToken}`
}
})
res.json({ success: true, user })
})2. E-commerce Order Updates
javascript
// Order confirmation
await nexus.trigger('order-confirmed', {
to: { subscriberId: order.customerId },
payload: {
orderNumber: order.number,
total: order.total,
items: order.items,
estimatedDelivery: order.estimatedDelivery
}
})
// Order shipped
await nexus.trigger('order-shipped', {
to: { subscriberId: order.customerId },
payload: {
orderNumber: order.number,
trackingNumber: shipping.trackingNumber,
trackingUrl: shipping.trackingUrl,
carrier: shipping.carrier
}
})
// Order delivered
await nexus.trigger('order-delivered', {
to: { subscriberId: order.customerId },
payload: {
orderNumber: order.number,
deliveryDate: new Date().toISOString(),
reviewUrl: `${process.env.APP_URL}/orders/${order.id}/review`
}
})3. Security Alerts
javascript
// Send security alert via multiple channels
await nexus.trigger('security-alert', {
to: { subscriberId: user.id },
payload: {
alertType: 'suspicious-login',
ipAddress: req.ip,
location: geoLocation,
timestamp: new Date().toISOString(),
actionUrl: `${process.env.APP_URL}/security/review`
},
overrides: {
email: {
priority: 'high'
},
sms: {
content: `Security alert: Suspicious login from ${geoLocation}. If this wasn't you, secure your account at ${process.env.APP_URL}/security`
},
push: {
title: 'Security Alert',
body: 'Suspicious login detected',
data: { action: 'security_review' }
}
}
})Troubleshooting
Common Issues
1. "Subscriber not found" Error
javascript
// Make sure subscriber exists before triggering
try {
await nexus.subscribers.get('user_123')
} catch (error) {
if (error.code === 'SUBSCRIBER_NOT_FOUND') {
// Create subscriber first
await nexus.subscribers.create({
subscriberId: 'user_123',
email: '[email protected]'
})
}
}2. "Workflow not found" Error
javascript
// Verify workflow exists and is active
const workflows = await nexus.workflows.list()
const workflow = workflows.data.find(w => w.identifier === 'user-signup')
if (!workflow) {
console.error('Workflow not found')
} else if (!workflow.active) {
console.error('Workflow is inactive')
}3. Rate Limit Exceeded
javascript
// Implement retry with exponential backoff
async function sendWithRetry(triggerFn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await triggerFn()
} catch (error) {
if (error.code === 'RATE_LIMIT_EXCEEDED' && i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000 // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay))
continue
}
throw error
}
}
}Best Practices
1. Error Handling
javascript
try {
const result = await nexus.trigger('workflow-id', data)
console.log('Success:', result.transactionId)
} catch (error) {
console.error('Notification failed:', error.message)
// Don't block the main application flow
// Log error for investigation
// Consider queuing for retry
}2. Use Idempotency Keys
javascript
await nexus.trigger('order-confirmation', {
to: { subscriberId: 'user_123' },
payload: { orderId: 'order_456' },
idempotencyKey: `order-confirmation-${orderId}` // Prevents duplicates
})3. Respect User Preferences
javascript
// Check preferences before sending
const subscriber = await nexus.subscribers.get('user_123')
if (subscriber.preferences?.marketing === false) {
console.log('User opted out of marketing emails')
return
}
await nexus.trigger('marketing-campaign', {
to: { subscriberId: 'user_123' },
payload: { campaignId: 'summer-sale' }
})Next Steps
Now that you've sent your first notification:
- Set up the notification widget for in-app notifications
- Create custom email templates with rich HTML content
- Build complex workflows with multiple steps and conditions
- Configure webhook endpoints to track delivery status
Getting Help
- 📖 API Reference for detailed endpoint documentation
- 💬 Discord Community for questions and discussions
- 🎥 Video Tutorials for visual learning
- 📧 Support Team for technical assistance