Sending Push Notifications
Push notifications are an important part of any mobile app. They allow you to send notifications to your users even when they are not using your app. This guide will show you how to send push notifications to different mobile app frameworks from your Supabase edge functions.
Expo makes implementing push notifications easy. All the hassle with device information and communicating with Firebase Cloud Messaging (FCM) or Apple Push Notification Service (APNs) is done behind the scenes. This allows you to treat Android and iOS notifications in the same way and save time both on the frontend and backend.
Find the example code on GitHub.
Supabase setup
- Create a new Supabase project.
- Link your project:
supabase link --project-ref your-supabase-project-ref
- Start supabase locally:
supabase start
- Push up the schema:
supabase db push
(schema is defined in supabase/migrations)
Expo setup
To utilize Expo's push notification service, you must configure your app by installing a set of libraries, implementing functions to handle notifications, and setting up credentials for Android and iOS. Follow the official Expo Push Notifications Setup Guide to get the credentials for Android and iOS. This project uses Expo's EAS build service to simplify this part.
- Install the dependencies:
npm i
- Create a new Expo project
- Link this app to your project:
npm install --global eas-cli && eas init --id your-expo-project-id
- Create a build for your physical device
- Start the development server for your project:
npx expo start --dev-client
- Scan the QR code shown in the terminal with your physical device.
- Sign up/in to create a user in Supabase Auth.
Enhanced security for push notifications
- Navigate to your Expo Access Token Settings.
- Create a new token for usage in Supabase Edge Functions.
- Toggle on "Enhanced Security for Push Notifications".
- Create the local
.env
file:cp .env.local.example .env.local
- In the newly created
.env.local
file, set yourEXPO_ACCESS_TOKEN
value.
Deploy the Supabase Edge Function
The database webhook handler to send push notifications is located in supabase/functions/push/index.ts. Deploy the function to your linked project and set the EXPO_ACCESS_TOKEN
secret.
supabase functions deploy push
supabase secrets set --env-file .env.local
Create the database webhook
Navigate to the Database Webhooks settings in your Supabase Dashboard.
- Enable and create a new hook.
- Conditions to fire webhook: Select the
notifications
table and tick theInsert
event. - Webhook configuration: Supabase Edge Functions.
- Edge Function: Select the
push
edge function and leave the method asPOST
and timeout as1000
. - HTTP Headers: Click "Add new header" > "Add auth header with service key" and leave Content-type:
application/json
. - Click "Create webhook".
Send push notification
- Navigate to the table editor in your Supabase Dashboard.
- In your
notifications
table, insert a new row. - Watch the magic happen 🪄