Generate TypeScript types from your Supabase schema with our step-by-step guide. Learn to set up Supabase, install the CLI, and automate type generation for type safety.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Supabase
Make sure you have a Supabase project set up. If not, you can start by creating an account at Supabase and setting up your database.
Get your API URL and the Anon key from your Supabase project dashboard. These will be used to connect your application to the Supabase instance.
Step 2: Install Supabase CLI
Supabase CLI is required for generating types. To install it, you should have Node.js installed on your system. Use the following command to install the Supabase CLI globally:
npm install -g supabase
Step 3: Generate Types via Supabase CLI
Once the Supabase CLI is installed, navigate to your project directory in the terminal.
Use the following command to authenticate your CLI session with Supabase:
supabase login
Fetch the database schema from your Supabase project. Use this command to output the current schema to the console:
supabase db dump
To generate TypeScript types from the Supabase schema, run:
supabase gen types typescript --db-url="your_database_url"
Replace your_database_url
with the connection URL of your Supabase project.
Step 4: Use the Generated Types in Your Project
After generating the types, they are typically saved in the supabase/types
directory within your project. Inspect this folder to confirm the TypeScript files.
Import the generated types in your project files where you need to use them. For example:
import { YourTableType } from './supabase/types';
Use these types in your application to ensure type safety when dealing with data from your Supabase database.
Step 5: Automate Type Generation
Consider creating a script in your package.json to automate this type generation process, especially if your database schema changes often. Here's an example of how to set it up:
In your package.json, add:
"scripts": {
"generate:types": "supabase gen types typescript --db-url='your_database_url'"
}
Now, you can run this command anytime to update the types:
npm run generate:types
Step 6: Incorporate Types with Supabase Client
If you're using the Supabase client in your application, you can enhance it with the generated types to leverage TypeScript's type checking features:
import { createClient } from "@supabase/supabase-js";
import { Database } from "./supabase/types"; // Adjust the path as needed
const supabase = createClient("your_supabase_url", "your_anon_key");
This will ensure that all your interactions with the database through the Supabase client are type-checked against your defined schema.
Step 7: Monitor for Schema Changes
Conclusion
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.