Generate TypeScript Type Definitions with the Supabase CLI

InstructorJon Meyers

Share this video with your friends

Send Tweet

TypeScript helps us build more robust, maintainable and safe applications. In this lesson, we look at installing the Supabase CLI, and using it to generate type definitions for Supabase.

We can use this to add TypeScript support to our Supabase client, which flows through our entire application - server and client. This means we get in-editor feedback about what we can and can't do with Supabase, helping to discover cool new things, while reducing bugs.

Additionally, we use the LoaderArgs type signature for our Loader function, which allows us to infer the return type in our component.

Note: this does not automatically update with changes to Supabase. You need to manually run this command whenever you change the structure of the database.

Code Snippets

Generate TypeScript definitions from Supabase

supabase gen types typescript --project-id your-project-id > db_types.ts

Create typesafe Supabase client

import { createClient } from "@supabase/supabase-js";

import type { Database } from "db_types";

export default createClient<Database>(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_ANON_KEY!
);

Fetch data with end-to-end type defs

import { useLoaderData } from "@remix-run/react";
import supabase from "utils/supabase";

import type { LoaderArgs } from "@remix-run/node";

export const loader = async ({}: LoaderArgs) => {
  const { data } = await supabase.from("messages").select();
  return { messages: data ?? [] };
};

export default function Index() {
  const { messages } = useLoaderData<typeof loader>();
  return <pre>{JSON.stringify(messages, null, 2)}</pre>;
}

Resources

Mannuel Ferreira
~ 2 years ago

generate access token here: https://app.supabase.com/account/tokens then generate the types

Mannuel Ferreira
~ 2 years ago

Ubuntu 22.04 users you may have to put a full path to project folder, or it will save the types file to your $HOME directory.

so:

supabase gen types typescript --prabsoluteoject-id xxxxxxxxxx >> $HOME/workspace/chatter/db_types.ts