Typing `Unknown` Supabase RPC Calls

October 13, 2024

Typing `Unknown` Supabase RPC Calls featured image

Recently I was working with the Supabase SDK on a personal project and inside this project, I am using the .rpc() method to call a SQL function. This function attempts to aggregate data around a user’s current link stats; how many there are, what’s being clicked, etc.

Without going into too much detail, using RPC functions is the suggested method to gain access to full SQL queries when using the Supabase SDK.

What do the Supabase Docs say?

In the Supabase Docs, there is a reference about how to handle Typescript with the QueryData type, however, this only seems to apply for .from() calls and doesn’t work for the .rpc() function call 🤦‍♂️

The *current* solution…

For the the time being I’ve decided to create a wrapper function that applies the desired type at the return

import { getServerClient } from '@/utils/server/getServerClient'

export type LinkStatsRpcReturn = {
  links_created: number
  total_clicks: number | null
  conversion_rate: number | null
  top_referrer: string | null
}

export async function getLinkStats() {
  const supabase = getServerClient()
  const { data, error } = await supabase.rpc('get_link_stats').single()

  if (error) {
    throw error
  }

  return data as LinkStatsRpcReturn
}

Now I can call getLinkStats and the returned object is properly typed 🎉

Future Thoughts…

I am still curious if there is a more refined approach to typing an .rpc() call where one could avoid creating the additional helper method 💭 I admittedly didn’t dig too far into the source code on this one, but I’ll update this post if I return to the subject in the future.

headshot photo

Published on

October 13, 2024

griffen.codes

made with 💖 and

2024 © all rights are reserved | updated 16 seconds ago

Footer Background Image