Supabase + tRPC = ❤️
Next.js is amazing and Typescript made development even more amazing! The entire time I was finding a way to have an end-to-end type safety solution until I met tRPC, almost perfect there.
But... it wasn't yet perfect enough.
There are a lot of examples of end-to-end tRPC on the web, where the majority that I followed was utilising Prisma as the ORM layer for type safety.
At this point, I am still in love with Supabase
Overall, Supabase is great, and I can generate types from Supabase directly by following the doc. But here's the issue... the generated types are not suitable to be inferred directly through tRPC routers, since I am only able to grab the main types from its definitions['table']
, but not the exact types that I am returning from the API.
And here I came across this cool tiny tool postgrest-js-tools. So how does this work? (I won't be going through how to use tRPC here, refer to the docs 😉)
First install the package:
yarn add postgrest-js-tools
Import the package into my tRPC router:
import { getFields, getShape } from "postgrest-js-tools";
Get the shape of a table:
// The shape infer the types for Supabase query and return only the field specified.
const expectedShape = getShape<definition["table"]>()({
id: true,
fieldThatIWant: true,
});
Request for data:
const { data, error } = await supabase
.from<typeof expectedShape>("table")
.select(getFields(expectedShape));
// data returned => { id: 1, fieldThatIWant: 'value' }
// typeof data => { id: number, fieldThatIWant: string }
Now we can pass the data down to the client through tRPC with type-safety!
Overall I am so happy that I found this tool. Just to end this, I still think Prisma should be a better fit in the stack for tRPC. I had considered using Prisma with Supabase, however, it seems like a hassle and a lot's of incompatibilities at this point in time. Will definitely revisit this in the future.
Try it out if you're using tRPC with Supabase, it's amazing still ❤️