Generating Types
Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions.
The Supabase CLI is a single binary Go application that provides everything you need to setup a local development environment.
You can install the CLI via npm or other supported package managers. The minimum required version of the CLI is v1.8.1 .
npm i supabase@">=1.8.1" --save-dev
Login with your Personal Access Token:
Generate types for your project to produce the types/supabase.ts
file:
npx supabase gen types typescript --project-id " $PROJECT_REF " --schema public > types/supabase.ts
After you have generated your types, you can use them in src/index.ts
import { NextApiRequest, NextApiResponse } from 'next'
import { createClient } from '@supabase/supabase-js'
import { Database } from '../types/supabase'
const supabase = createClient < Database >(
process.env. NEXT_PUBLIC_SUPABASE_URL ,
process.env. SUPABASE_SECRET_KEY
export default async (req : NextApiRequest, res : NextApiResponse) => {
const allOnlineUsers = await supabase. from ( 'users' ). select ( '*' ). eq ( 'status' , 'ONLINE' )
res. status ( 200 ). json (allOnlineUsers)
One way to keep your type definitions in sync with your database is to set up a GitHub action that runs on a schedule.
Add the script above to your package.json
to run it using npm run update-types
"update-types" : "npx supabase gen types typescript --project-id \" $PROJECT_REF \" > types/supabase.ts"
Create a file .github/workflows/update-types.yml
with the following snippet to define the action along with the environment variables. This script will commit new type changes to your repo every night.
name : Update database types
# sets the action to run daily. You can modify this to run the action more or less frequently
SUPABASE_ACCESS_TOKEN : ${{ secrets.ACCESS_TOKEN }}
PROJECT_REF : <your-project-id>
- uses : actions/checkout@v2
persist-credentials : false
- uses : actions/setup-node@v2.1.5
- run : npm run update-types
- name : check for file changes
echo "::set-output name=status::$(git status -s)"
if : ${{contains(steps.git_status.outputs.status, ' ')}}
git add types/database/index.ts
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "Update database types" -a
if : ${{contains(steps.git_status.outputs.status, ' ')}}
uses : ad-m/github-push-action@master
github_token : ${{ secrets.GITHUB_TOKEN }}
branch : ${{ github.ref }}
Alternatively, you can use a community-supported GitHub action: generate-supabase-db-types-github-action .