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

Text
/api/v1/notifications

Authentication

All endpoints require authentication via session cookie.

Notification Preferences

Get Notification Preferences

Retrieve the current user’s notification preferences and email configuration status.

HTTP
GET /api/v1/notifications/preferences

Response

JSON
{
  "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

FieldTypeDescription
preferencesobjectUser’s notification preferences
email_configobjectServer email configuration status
can_send_emailsbooleanWhether emails can be sent (config enabled AND user enabled)

Preference Fields

FieldTypeDefaultDescription
email_enabledbooleantrueMaster toggle for all email notifications
welcome_emailsbooleantrueWelcome messages and onboarding emails
transaction_emailsbooleantrueTransaction status updates
rating_emailsbooleantrueNew rating notifications
marketplace_emailsbooleantrueMarketplace activity alerts
collection_remindersbooleanfalseReminders to rate beers
marketing_emailsbooleanfalsePromotional and feature announcements

Update Notification Preferences

Update the current user’s notification preferences.

HTTP
PUT /api/v1/notifications/preferences
Content-Type: application/json

Request Body

JSON
{
  "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

JSON
{
  "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 (true or false)
  • Invalid values return a 400 Bad Request error

Email Templates

BrewHoard sends different email types based on application events. Each template respects user preferences.

Available Templates

TemplatePreference KeyTrigger Event
welcomewelcome_emailsUser registration
transaction-createdtransaction_emailsNew marketplace transaction created
transaction-updatedtransaction_emailsTransaction status change
rating-receivedrating_emailsSomeone rates user’s beer
listing-soldmarketplace_emailsMarketplace listing sold
new-listingmarketplace_emailsNew listing alert (if subscribed)
collection-remindercollection_remindersUnrated 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.

JavaScript
import { sendWelcomeEmail } from '$lib/notifications/email.js';

await sendWelcomeEmail(userId);

sendTransactionEmail

Sends transaction notification to buyer.

JavaScript
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.

JavaScript
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.

JavaScript
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.

JavaScript
import { sendCollectionReminderEmail } from '$lib/notifications/email.js';

await sendCollectionReminderEmail(userId, 15); // 15 unrated beers

Email Queue System

For high-volume scenarios, emails can be queued for batch processing.

Queue Functions

JavaScript
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

PriorityUse Case
1Critical notifications (password reset, security alerts)
5Normal notifications (transaction updates, ratings)
10Low priority (reminders, marketing)

Email Statistics

Track email delivery performance (admin use).

JavaScript
import { getEmailStatistics } from '$lib/notifications/email.server.js';

// Global statistics
const stats = await getEmailStatistics();

// User-specific statistics
const userStats = await getEmailStatistics(userId);

Statistics Response

JSON
{
  "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

CodeDescription
200Success
400Bad Request - Invalid preference values
401Unauthorized - Authentication required
500Server Error - Failed to process request

Error Response Format

JSON
{
  "error": "Invalid value for rating_emails: must be boolean"
}

Email Provider Configuration

BrewHoard supports multiple email providers. Configuration is set via environment variables:

VariableDescriptionDefault
EMAIL_PROVIDERProvider name (resend, sendgrid, etc.)resend
EMAIL_API_KEYProvider API key-
EMAIL_FROMSender email addressnoreply@brewhoard.com
EMAIL_REPLY_TOReply-to addresssupport@brewhoard.com
BASE_URLApplication base URLhttp://localhost:5173

Development Mode

In development (NODE_ENV !== 'production'), emails are logged to console instead of being sent.


Database Schema

user_notification_preferences

ColumnTypeDescription
user_idUUIDPrimary key, references users
preferencesJSONBUser preferences object
created_atTIMESTAMPCreation timestamp
updated_atTIMESTAMPLast update timestamp

email_notifications

ColumnTypeDescription
idUUIDPrimary key
user_idUUIDUser ID
templateVARCHAREmail template name
subjectVARCHAREmail subject
recipient_emailVARCHARRecipient address
statusVARCHARpending, sent, delivered, failed, bounced
providerVARCHAREmail provider used
external_idVARCHARProvider’s message ID
error_messageTEXTError details if failed
sent_atTIMESTAMPWhen sent
delivered_atTIMESTAMPWhen delivered
created_atTIMESTAMPCreation timestamp

email_queue

ColumnTypeDescription
idUUIDPrimary key
user_idUUIDUser ID
templateVARCHAREmail template name
dataJSONBTemplate data
priorityINTPriority level (1-10)
statusVARCHARpending, processing, completed, failed
attemptsINTNumber of send attempts
max_attemptsINTMaximum retry attempts
next_attempt_atTIMESTAMPScheduled retry time
created_atTIMESTAMPCreation timestamp

Best Practices

  1. Respect user preferences: Always check preferences before sending
  2. Use appropriate templates: Match the event type to the correct template
  3. Queue non-critical emails: Use the queue for batch operations
  4. Monitor delivery: Track failed emails and bounces
  5. Provide easy unsubscribe: Every email includes preference management links

Related Documentation