Notifications API
API reference for email notifications and user notification preferences in BrewHoard
The Notifications API provides endpoints for managing user notification preferences and handles email delivery for various application events.
Base URL
/api/v1/notificationsAuthentication
All endpoints require authentication via session cookie.
Notification Preferences
Get Notification Preferences
Retrieve the current user’s notification preferences and email configuration status.
GET /api/v1/notifications/preferencesResponse
{
"preferences": {
"email_enabled": true,
"welcome_emails": true,
"transaction_emails": true,
"rating_emails": true,
"marketplace_emails": true,
"collection_reminders": false,
"marketing_emails": false
},
"email_config": {
"enabled": true,
"provider": "resend",
"from": "noreply@brewhoard.com",
"hasApiKey": true,
"environment": "production"
},
"can_send_emails": true
}Response Fields
| Field | Type | Description |
|---|---|---|
preferences | object | User’s notification preferences |
email_config | object | Server email configuration status |
can_send_emails | boolean | Whether emails can be sent (config enabled AND user enabled) |
Preference Fields
| Field | Type | Default | Description |
|---|---|---|---|
email_enabled | boolean | true | Master toggle for all email notifications |
welcome_emails | boolean | true | Welcome messages and onboarding emails |
transaction_emails | boolean | true | Transaction status updates |
rating_emails | boolean | true | New rating notifications |
marketplace_emails | boolean | true | Marketplace activity alerts |
collection_reminders | boolean | false | Reminders to rate beers |
marketing_emails | boolean | false | Promotional and feature announcements |
Update Notification Preferences
Update the current user’s notification preferences.
PUT /api/v1/notifications/preferences
Content-Type: application/jsonRequest Body
{
"email_enabled": true,
"welcome_emails": true,
"transaction_emails": true,
"rating_emails": false,
"marketplace_emails": true,
"collection_reminders": true,
"marketing_emails": false
}All fields are optional. Only provided fields will be updated; omitted fields retain their current values.
Response
{
"preferences": {
"email_enabled": true,
"welcome_emails": true,
"transaction_emails": true,
"rating_emails": false,
"marketplace_emails": true,
"collection_reminders": true,
"marketing_emails": false
},
"email_config": {
"enabled": true,
"provider": "resend",
"from": "noreply@brewhoard.com",
"hasApiKey": true,
"environment": "production"
},
"can_send_emails": true,
"message": "Notification preferences updated successfully"
}Validation
- All preference values must be boolean (
trueorfalse) - Invalid values return a
400 Bad Requesterror
Email Templates
BrewHoard sends different email types based on application events. Each template respects user preferences.
Available Templates
| Template | Preference Key | Trigger Event |
|---|---|---|
welcome | welcome_emails | User registration |
transaction-created | transaction_emails | New marketplace transaction created |
transaction-updated | transaction_emails | Transaction status change |
rating-received | rating_emails | Someone rates user’s beer |
listing-sold | marketplace_emails | Marketplace listing sold |
new-listing | marketplace_emails | New listing alert (if subscribed) |
collection-reminder | collection_reminders | Unrated beers reminder |
Template Content
All emails include:
- BrewHoard branding header
- Template-specific content
- Unsubscribe link to notification settings
- Footer with preference management link
Internal Email Functions
These functions are used internally by the application and are not exposed via API.
sendWelcomeEmail
Sends a welcome email to new users.
import { sendWelcomeEmail } from '$lib/notifications/email.js';
await sendWelcomeEmail(userId);sendTransactionEmail
Sends transaction notification to buyer.
import { sendTransactionEmail } from '$lib/notifications/email.js';
await sendTransactionEmail(userId, transactionId, {
beer_name: 'Westvleteren 12',
brewery: 'Westvleteren Brewery',
quantity: 2,
total_price: 45.00,
seller_username: 'beertrader123'
});sendRatingEmail
Notifies beer owner when their beer receives a rating.
import { sendRatingEmail } from '$lib/notifications/email.js';
await sendRatingEmail(userId, {
beer_id: 'uuid',
beer_name: 'Pliny the Elder',
rater_username: 'hophead42',
rating: 5,
review: 'Exceptional IPA!'
});sendListingSoldEmail
Notifies seller when their listing sells.
import { sendListingSoldEmail } from '$lib/notifications/email.js';
await sendListingSoldEmail(userId, {
beer_name: 'Cantillon Gueuze',
brewery: 'Cantillon',
quantity: 1,
total_price: 65.00,
buyer_username: 'lambicfan'
});sendCollectionReminderEmail
Reminds users to rate beers in their collection.
import { sendCollectionReminderEmail } from '$lib/notifications/email.js';
await sendCollectionReminderEmail(userId, 15); // 15 unrated beersEmail Queue System
For high-volume scenarios, emails can be queued for batch processing.
Queue Functions
import {
queueEmail,
getEmailQueue,
updateQueueStatus
} from '$lib/notifications/email.server.js';
// Queue an email
const queueId = await queueEmail({
userId: 'user-uuid',
template: 'collection-reminder',
data: { unratedCount: 10 },
priority: 5 // 1=high, 5=normal, 10=low
});
// Get pending emails
const queue = await getEmailQueue(10); // Get up to 10 emails
// Update queue item status
await updateQueueStatus(queueId, 'completed');Queue Priority Levels
| Priority | Use Case |
|---|---|
| 1 | Critical notifications (password reset, security alerts) |
| 5 | Normal notifications (transaction updates, ratings) |
| 10 | Low priority (reminders, marketing) |
Email Statistics
Track email delivery performance (admin use).
import { getEmailStatistics } from '$lib/notifications/email.server.js';
// Global statistics
const stats = await getEmailStatistics();
// User-specific statistics
const userStats = await getEmailStatistics(userId);Statistics Response
{
"total_sent": 1250,
"delivered": 1200,
"failed": 35,
"bounced": 15,
"sent_last_24h": 45,
"sent_last_7d": 280,
"sent_last_30d": 1100,
"template_stats": [
{ "template": "transaction-created", "count": 450 },
{ "template": "welcome", "count": 320 },
{ "template": "rating-received", "count": 280 }
]
}Error Handling
HTTP Status Codes
| Code | Description |
|---|---|
| 200 | Success |
| 400 | Bad Request - Invalid preference values |
| 401 | Unauthorized - Authentication required |
| 500 | Server Error - Failed to process request |
Error Response Format
{
"error": "Invalid value for rating_emails: must be boolean"
}Email Provider Configuration
BrewHoard supports multiple email providers. Configuration is set via environment variables:
| Variable | Description | Default |
|---|---|---|
EMAIL_PROVIDER | Provider name (resend, sendgrid, etc.) | resend |
EMAIL_API_KEY | Provider API key | - |
EMAIL_FROM | Sender email address | noreply@brewhoard.com |
EMAIL_REPLY_TO | Reply-to address | support@brewhoard.com |
BASE_URL | Application base URL | http://localhost:5173 |
Development Mode
In development (NODE_ENV !== 'production'), emails are logged to console instead of being sent.
Database Schema
user_notification_preferences
| Column | Type | Description |
|---|---|---|
user_id | UUID | Primary key, references users |
preferences | JSONB | User preferences object |
created_at | TIMESTAMP | Creation timestamp |
updated_at | TIMESTAMP | Last update timestamp |
email_notifications
| Column | Type | Description |
|---|---|---|
id | UUID | Primary key |
user_id | UUID | User ID |
template | VARCHAR | Email template name |
subject | VARCHAR | Email subject |
recipient_email | VARCHAR | Recipient address |
status | VARCHAR | pending, sent, delivered, failed, bounced |
provider | VARCHAR | Email provider used |
external_id | VARCHAR | Provider’s message ID |
error_message | TEXT | Error details if failed |
sent_at | TIMESTAMP | When sent |
delivered_at | TIMESTAMP | When delivered |
created_at | TIMESTAMP | Creation timestamp |
email_queue
| Column | Type | Description |
|---|---|---|
id | UUID | Primary key |
user_id | UUID | User ID |
template | VARCHAR | Email template name |
data | JSONB | Template data |
priority | INT | Priority level (1-10) |
status | VARCHAR | pending, processing, completed, failed |
attempts | INT | Number of send attempts |
max_attempts | INT | Maximum retry attempts |
next_attempt_at | TIMESTAMP | Scheduled retry time |
created_at | TIMESTAMP | Creation timestamp |
Best Practices
- Respect user preferences: Always check preferences before sending
- Use appropriate templates: Match the event type to the correct template
- Queue non-critical emails: Use the queue for batch operations
- Monitor delivery: Track failed emails and bounces
- Provide easy unsubscribe: Every email includes preference management links
Related Documentation
- Settings & Preferences - User settings UI
- Social API - Social notification triggers
- Marketplace API - Transaction notification triggers