Supabase

How to implement push notifications using Supabase?

Discover how to seamlessly set up push notifications with Supabase. Boost user engagement and real-time communication in your app with our easy-to-follow guide.

Developer profile skeleton
a developer thinking

Overview

Diving into push notifications with Supabase means combining a few crucial elements to make sure real-time alerts and messages work smoothly. Start by getting a Supabase project up and running. Then, set up your database to store notifications, using Supabase's authentication to keep user data secure. For the front-end, pick a framework like React or Vue.js, which are both popular choices. Don't forget to arrange a background service for firing off the notifications, such as Firebase Cloud Messaging. To keep things live and instant, use Supabase's Realtime API. This guide lays out all the steps, from configuration to coding, to help you set up push notifications effectively.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement push notifications using Supabase?

Pre-requisites

Before you dive in, make sure you've got these covered:

  • A Supabase project is ready to go.
  • Firebase Cloud Messaging (FCM) is set up for push notifications.

Step 1: Set Up Firebase Cloud Messaging (FCM)

  1. Head over to the Firebase Console.
  2. Either start a new project or pick one you already have.
  3. Go to Project Settings > Cloud Messaging.
  4. Grab the Server key and Sender ID.

Step 2: Configure Supabase

  1. Open the Supabase Dashboard.

  2. Choose your project.

  3. Go to Database > Tables and create a new table to store FCM tokens:

    ```sql
    create table fcm_tokens (
    id serial primary key,
    user_id uuid references auth.users(id),
    fcm_token text not null
    );
    ```

Step 3: Register Devices for FCM

  1. Add the Firebase SDK to your client app:

    ```html

    ```

  2. Set up Firebase in your client app:

    ```javascript
    const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
    };

    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    ```

  3. Get the device token and save it in Supabase:

```javascript
messaging.getToken({ vapidKey: 'YOUR_PUBLIC_VAPID_KEY' }).then((currentToken) => {
if (currentToken) {
// Send token to your server
saveTokenToDatabase(currentToken);
} else {
console.warn('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.error('An error occurred while retrieving token. ', err);
});

function saveTokenToDatabase(token) {
fetch('https://YOUR_SUPABASE_URL/rest/v1/fcm\_tokens', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': 'YOUR_SUPABASE_ANON_KEY',
'Authorization': Bearer ${SUPABASE_SESSION_TOKEN}
},
body: JSON.stringify({
user_id: YOUR_USER_ID,
fcm_token: token
}),
});
}
```

Step 4: Send Push Notifications

  1. Create a function to fetch FCM tokens from Supabase:

    ```javascript
    async function getFcmTokens() {
    const response = await fetch('https://YOUR_SUPABASE_URL/rest/v1/fcm\_tokens', {
    method: 'GET',
    headers: {
    'Content-Type': 'application/json',
    'apikey': 'YOUR_SUPABASE_ANON_KEY',
    'Authorization': Bearer ${SUPABASE_SESSION_TOKEN}
    },
    });

    return await response.json();
    }
    ```

  2. Send notifications using the FCM server key:

    ```javascript
    const fcmTokens = await getFcmTokens();

    fcmTokens.forEach(token => {
    fetch('https://fcm.googleapis.com/fcm/send', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Authorization': key=${YOUR_SERVER_KEY}
    },
    body: JSON.stringify({
    notification: {
    title: 'Notification Title',
    body: 'Notification Body',
    click_action: 'https://your-site.com',
    icon: 'https://your-site.com/icon.png'
    },
    to: token.fcm_token
    }),
    }).then(response => response.json())
    .then(data => console.log('Success:', data))
    .catch((error) => console.error('Error:', error));
    });
    ```

Step 5: Handle Incoming Notifications

  1. Add a background message handler in your client app:

    ```javascript
    messaging.onBackgroundMessage((payload) => {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize and display notification here
    });
    ```

  2. Add a click event handler:

    ```javascript
    self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(
    clients.openWindow('https://your-site.com')
    );
    });
    ```

This guide walks you through setting up push notifications with Supabase.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.