This is a serverless function for handling push notifications in the chat application. It can be deployed to Vercel to send Firebase Cloud Messaging (FCM) notifications.
- Go to the Firebase Console
- Navigate to Project Settings > Service Accounts
- Click "Generate new private key"
- Save the JSON file securely
Set the following environment variables in your Vercel project settings:
FIREBASE_TYPE=service_account
FIREBASE_PROJECT_ID=your-firebase-project-id
FIREBASE_PRIVATE_KEY_ID=your-private-key-id
FIREBASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY\n-----END PRIVATE KEY-----\n
FIREBASE_CLIENT_EMAIL=your-client-email@your-project.iam.gserviceaccount.com
FIREBASE_CLIENT_ID=your-client-id
FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIREBASE_AUTH_PROVIDER_X509_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIREBASE_CLIENT_X509_CERT_URL=https://www.googleapis.com/robot/v1/metadata/x509/your-client-email%40your-project.iam.gserviceaccount.com
-
Install Vercel CLI:
npm install -g vercel
-
Deploy the project:
vercel --prod
Update your Flutter app to use the deployed Vercel URL by setting the environment variable:
flutter run --dart-define=NOTIFICATION_SERVER_URL=https://your-deployment-url.vercel.appOr for production builds:
flutter build --dart-define=NOTIFICATION_SERVER_URL=https://your-deployment-url.vercel.appPOST /api/send-notification
{
"userId": "recipient-user-id",
"title": "Notification Title",
"body": "Notification Body",
"data": {
"key": "value"
}
}{
"success": true,
"message": "Notification sent successfully",
"response": "Firebase message ID"
}- Create a
.env.localfile with your Firebase service account credentials - Run the development server:
vercel dev
The server handles various error cases:
- Missing required fields
- User not found
- Invalid or expired FCM tokens
- Firebase messaging errors