Skip to content

OneSignalDevelopers/onesignal-supabase-sample-integration-supabase

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

91 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

OneSignal

Quickstart Β Β β€’Β Β  Website Β Β β€’Β Β  Docs Β Β β€’Β Β  Examples

OneSignal + Supabase Sample Omni-channel Integration

OneSignal makes engaging customers simple and is the fastest, most reliable service to send push notifications, in-app messages, SMS, and emails.

This project demonstrates how to use OneSignal as an integration with Supabase to handle your messaging needs, including push notifications, SMS text messages, email, and in-app messaging. Feel free to use this sample as a reference for your own Supabase integration.

Table of Contents

🚦 Getting started

This project assumes that you already have a few things setup.

Setup OneSignal App

  1. From the OneSignal Dashboard, select New App/Website to create an app. Select New App/Website to create new app
  2. Name app and choose the Android platform to setup. Onesignal platform configuration
  3. Enter FCM credentials for the Firebase project you want to handle Android notifications and choose Save & Continue. FCM configuration form

Setup iOS Platform

iOS configuration requires substantially more effort to integrate due to needing signed certs from Apple. Due to this fact, follow this guide for detailed instructions on creating the certificate needed to use Apple's Push Notification Service (APNs).

After you have the certificate, head to the OneSignal Dashboard

  1. Choose Settings -> Platforms
  2. Activate the iOS card Platform settings
  3. Upload your certificate and enter the password you used to encrypt it. If you didn't set a password, leave the password input blank. Apple iOS (APNs) Configuration form

Craft an In-App Message

Consent is required before we can present push notifications to a user. It's recommend to use an in-app message to ask for consent because no prior consent is needed to present them. This is particularly useful in situations where a user accidentally declines consent. We have an in-depth guide explaining this strategy here.

  1. Select New Message -> New In-App and name it "prompt_notification" Select new in app message

  2. Configure an in-app message with at least one button; here's the message with two buttons I configured for this sample using our Block Editor! Example in-app message

  3. Add the Push Permission Prompt Click Action to the primary call to action button. Adding a cliock action

  4. Select Add Trigger -> In-App Trigger to present the in-app message when specific conditions are met Adding in-app trigger

  5. Schedule the message to start showing Immediately, to Show forever, and to show Every time trigger conditions are satisfied

  6. Select Make Message Live to publish message

If you didn't name your in-app message "prompt_notification", you'll need to update the Flutter app's code to use your name.

Setup Supabase Project

Initialize Supabase project

Run this command to interactively configure a new Supabase project

supabase projects create onesignal-supabase-sample-integration -i

asciicast

Disable email confirmation authentication

Disable Supabase email confirmation

Supabase projects are more secure by default. The front-end client consuming this project does not support magic links. Disabling email confirmation is needed to run the companion sample app.

  1. From the Supabase Dashboard, navigate to your project's Authenication pane. Select Providers on Authentication page
  2. Select Providers under the Configuration header. Disable Confirm email
  3. Disable Confirm email and select Save.

Edit Database Triggers

We can rely on Supabase to automatically insert a user profile after user signup. Supabase provides Database Functions and Triggers that enable us to react to events on the database. For this sample integration, we will edit the existing function on_auth_user_created.

  1. Navigate to Database -> Triggers on_auth_user_created Trigger

  2. Edit the backing function by navigating to Functions and clicking the edit button located in the context-menu for the record handle_new_user. Navigate to Supabase Database Functions

  3. Paste the πŸ‘‡ script as the Defintion and select Confirm

begin
  insert into public.profiles (id, email)
  values (new.id, new.raw_user_meta_data->>'email');
  return new;
end;

Database function edit form

Create Edge Function

The Supabase CLI's command to create a function will add the boilerplate for an edge function located in a directory with the name specified in the command, push/index.ts.

supabase functions new push-order-confirmation-to-customer

asciicast

This function is responsible for calling the OneSignal API using onesignal-node-sdk.

Function Implementation

Supabase Edge Functions are executed in the Deno enfironment on the edge, so

  • Functions are written in TypeScript
  • You can't install packages with a package manager like npm or Yarn

Function logic is implemented in push/index.ts (Here).

We can't use a traditional package manager to install packages, so we're using esm.sh – a global CDN for npm packages – to load the onesignal-node-api module.

import * as OneSignal from "https://esm.sh/@onesignal/node-onesignal@1.0.

Deno's Deno.env object exposes the values we need.

export const _OnesignalAppId_ = Deno.env.get("ONESIGNAL_APP_ID")!
const _OnesignalUserAuthKey_ = Deno.env.get("USER_AUTH_KEY")!
export const _OnesignalRestApiKey_ = Deno.env.get("ONESIGNAL_REST_API_KEY")!

Create the OneSignal API client so we can send a request to the API.

export const onesignal = new OneSignal.DefaultApi(configuration)

Now we can configure the notification object.

const notification = new OneSignal.Notification()
notification.app_id = _OnesignalAppId_
notification.include_external_user_ids = [profile]
notification.contents = {
en: generateMessage(record.amount, record.currency),
}

And send the notification to OneSignal to send the push notification.

const onesignalApiRes = await onesignal.createNotification(notification)

Set Environment Variables

Locally

Supabase will respect local environment variables set in supabase/.env.local.

Copy .env.example and fill in your keys from OneSignal app.

$ cp supabase/.env.example supabase/.env.local

On Supabase

Use the Supabase CLI to set environment variables in the Supabase project.

$ supabase secrets set test=123
Finished supabase secrets set.

asciicast

How to Remove Variable

Use the Supabase CLI to remove environmental variables in the Supabase project.

$ supabase secrets unset test
Finished supabase secrets unset.

Run Migrations

πŸ’‘You only need to run steps 1 since this sample includes migrations files (here).

  1. Run supabase db diff and copy its output Generate SQL script for Supabase migration

  2. Create a new migration and paste the output from the previous step into the .sql file Create Supabase Migration

  3. Run supabase db push to apply migrations to the hosted project

Deploy Edge Function

We can deploy edge functions to a local or production environment. Developing locally allows us to test and iterate quickly.

Hosting locally

  1. Start the Supabase Docker container, navigate to the root directory of this sample project and run supabase start
  2. To serve the function, run supabase functions serve push --env-file ./supabase/.env.local --debug
  3. Submit a request to the endpoint making sure to use the anon key as your bearer token.

Result of running supabase start

$ supabase start
Seeding data supabase/seed.sql...
Started supabase local development setup.

API URL: http://localhost:54321
DB URL: postgresql://postgres:postgres@localhost:54322/postgres
Studio URL: http://localhost:54323
Inbucket URL: http://localhost:54324
JWT secret: super-secret-jwt-token-with-at-least-32-characters-long
anon key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs
service_role key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSJ9.vI9obAHOGyVVKa3pD--kJlyxp-Z2zV9UUMAhKpNLAcU

Serving a function to the local instance of Supabase.

asciicast

To Production

Supabase makes deploying your project to production simple with their CLI.

supabase functions deploy push

If the command ☝️ doesn't work for you, try executing the command with the --legacy-bundle flag set.

asciicast

Create Database Webhook

For complete instructions on creating a webhooks, please refer to the Supabase docs.

Sample hook

  1. From the Database -> Webhooks page Select Create a new hook button
  2. Name the hook "push-order-confirmation-to-user"
  3. Set the table to orders
  4. Select Insert checkbox
  5. Set hook type to HTTP Request
  6. Set the HTTP request method to POST
  7. Set the URL to the edge function, push-order-confirmation-to-customer
  8. Add a HTTP Header named Authorization and set the value to Bearer [Your Supabase project's anonKey]
  9. Select Confirm confirm button to complete setup

πŸ’‘We need to include the Authorization header so the edge function can verify the request. Without this header, anyone would be able to call our endpoint.

Example Database Webhook event
{
    type: "INSERT",
    table: "orders",
    record: {
      id: "796a354b-c087-4afe-8614-5a1015221d04",
      amount: 1099,
      currency: "usd",
      created_at: "2022-11-30T18:41:42.605",
      stripe_pi_id: "pi_3M9vDvKCO1JeQB0L1PGzangD",
      stripe_customer_id: "cus_MtibdpF533vFYn"
    },
    schema: "public",
    old_record: null
}

πŸš€πŸš€πŸš€ Launch Companion App

The companion app and supporting API can be built from source to run alongside this Supabase project.

App demo

Debugging

The Supabase dashboard presents all deployed functions along with their time of deployment and status.

Functions deployed to production

Inspect Supabase Edge Function Requests

Supabase enables you to review HTTP request logs to assist with our debugging.

Inspecting function requests

Review Server Logs

Our console.logs will appear here!

Reviewing function logs


❀️ Developer Community

For additional resources, please join the OneSignal Developer Community.

Get in touch with us or learn more about OneSignal through the channels below.

Show your support

Give a ⭐️ if this project helped you, and watch this repo to stay up to date.