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.
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.
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.
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):
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:
Once we have our function to generate signature, we can create another function to send the webhook request with the signature:
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
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.
Finally, we can verify the signature in our webhook endpoint. We can do this by comparing the signature in
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.