How do I get Supabase database types?

2k views Asked by At

I'm coming from Firebase I'm trying to get the types for database. For example, I'm used to get the type for timestamp like this:

import type { Timestamp } from 'firebase/firestore';

export type User = {
 //..   
 createdAt: Timestamp;   
 updatedAt: Timestamp | null; 
};

How do I get the types for Supabase database?

2

There are 2 answers

1
k_ison On BEST ANSWER

You can check out the official Supabase docs for Generating Types. There are few examples as well that you can refer to.

https://supabase.com/docs/guides/api/generating-types

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)
}
0
lanan On

You should define your own types for individual tables, e.g.

  import supabase from '~/lib/supabase'
  import type { Database } from '~/lib/database.types'

  async function getMovies() {
    return await supabase.from('movies').select('id, title, actors(\*)')
  }

  type Actors = Database['public']['tables']['actors']['row']
  type MoviesResponse = Awaited<ReturnType<typeof getMovies>>
  type MoviesResponseSuccess = MoviesResponse['data'] & {
  actors: Actors[]
  }

form docs https://supabase.com/docs/reference/javascript/select