Skip to main content
POST
/
api
/
notifications
/
send
Send Push Notification
curl --request POST \
  --url https://api.example.com/api/notifications/send \
  --header 'Content-Type: application/json' \
  --data '
{
  "userId": "<string>",
  "title": "<string>",
  "body": "<string>",
  "url": "<string>"
}
'
{
  "success": true,
  "message": "<string>",
  "400 Bad Request": {},
  "404 Not Found": {}
}

Overview

This endpoint sends a custom push notification to all devices registered for a specific user. The notification is delivered via the Web Push protocol to all active subscriptions.

Authentication

This is typically an admin or system endpoint. Ensure proper authorization is in place before exposing this endpoint.

Request Body

userId
string
required
MongoDB ObjectId of the target user
title
string
required
Notification title (shown prominently in the notification)
body
string
required
Notification body text (main message content)
url
string
URL to navigate to when the notification is clicked. Defaults to /

Response

success
boolean
Indicates whether the notification was sent successfully to at least one device
message
string
Human-readable message indicating how many devices received the notification

Notification Payload Structure

The endpoint constructs a Web Push payload with the following structure:
{
  title: string,              // Notification title
  body: string,               // Notification message
  icon: '/logo192.png',       // App icon URL
  badge: '/badge.png',        // Badge icon for notification bar
  data: {
    url: string,              // Click destination URL
    timestamp: number         // Unix timestamp
  }
}

Behavior

  • Sends to all active devices for the specified user
  • Automatically removes expired subscriptions (HTTP 410 responses)
  • Returns success if at least one device receives the notification
  • Uses Promise.allSettled to ensure all devices are attempted even if some fail
const response = await fetch('/api/notifications/send', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${adminToken}`
  },
  body: JSON.stringify({
    userId: '507f1f77bcf86cd799439011',
    title: 'Welcome to FitAiid!',
    body: 'Your personalized workout plan is ready',
    url: '/workouts'
  })
});

const result = await response.json();
console.log(result);

Response Example

{
  "success": true,
  "message": "Notificación enviada a 2 dispositivo(s)"
}

Error Responses

400 Bad Request
error
Missing required parameters
{
  "error": "Faltan parámetros requeridos: userId, title, body"
}
404 Not Found
error
No active subscriptions found for user
{
  "error": "Error al enviar notificación"
}

Implementation Details

The endpoint uses the notificationService.sendNotificationToUser() method which:
  1. Queries all PushSubscription documents for the given userId
  2. Constructs a JSON payload with the notification data
  3. Sends the notification to each subscription using the web-push library
  4. Handles failures gracefully:
    • HTTP 410 (Gone): Subscription expired → automatically deleted from database
    • Other errors: Logged but don’t prevent other sends
  5. Returns success if at least one notification was delivered

Automatic Cleanup

Expired or invalid subscriptions are automatically removed when they return:
  • 410 Gone - Subscription expired or unsubscribed
This keeps the database clean and prevents unnecessary send attempts.

Specialized Notification Types

Automatic Notifications

FitAiid automatically sends notifications for these events:
  • Workout Completed - After completing a workout session
  • Achievement Unlocked - When a new achievement is unlocked
  • Streak Milestones - At 7, 14, 30-day streaks
  • Inactivity Reminders - After 3, 5, 7, or 14 days of inactivity

Subscribe

Register a device for push notifications

User Achievements

View unlocked achievements

User Statistics

Get workout statistics

Build docs developers (and LLMs) love