Setup Webhook Signature with Supabase

Supabase Database Webhook is a great way to trigger a function when a database event occurs. However, it is important to secure the webhook endpoint to prevent abuse. This article will show you how to setup webhook signature with Supabase.

Supabase Database Webhook is a great way to trigger a function when a database event occurs. However, it is important to secure the webhook endpoint to prevent abuse.

What is a webhook signature?

A webhook signature is a way to verify that the webhook request is coming from Supabase. It is a signature that is generated using a secret key and the request body. The signature is then sent along with the request as a header. The receiver can then verify the signature using the secret key and the request body.

How to setup webhook signature with Supabase?

1. Generate a secret key

First, we'll need a secret key to use to sign the webhook request. We can generate a secret key using uuid generator for example.

2. Create secrets in Supabase Vault

Next, we'll create two secrets in Supabase Vault. One for the secret key and another for the URL of our webhook endpoint (to allow for different secrets/endpoints per environments):

3. Create a function to generate the signature

Next, we'll create a function to generate the signature. This function will take the request body as an argument, generate a signature using the secret key and encode using base64:

4. Create a function to send the webhook with the signature

Once we have our function to generate signature, we can create another function to send the webhook request with the signature:

5. Create a database trigger

Finally, we can create a database trigger to call our webhook function when a database event occurs. In the next example, we'll create a trigger to call our webhook function when a new row is inserted into the todos table:

Now, every time a new row is inserted into the todos table, our webhook function will be called and the webhook request will be sent with the signature.

6. Verify the signature in your webhook endpoint

Finally, we can verify the signature in our webhook endpoint. We can do this by comparing the signature in the X-Supabase-Signature header with the signature generated using the secret key and the request body. In this example, we are using Nest.js and a guard, but you can use any framework you like:

That's it! Now we have secure webhooks with Supabase.