Supabase JavaScript V2  - Method Cheat Sheet
5 min read

Here is a quick reference for the Supabase JavaScript V2 SDK!

Setup

export const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_KEY
);

Authentication

// email signup
const { data, error } = await supabase.auth.signUp({ email, password });

// email login
const { error } = await supabase.auth.signInWithPassword({ email, password });

// magic link
const { error } = await supabase.auth.signInWithOtp({
  email,
  options: {
    emailRedirectTo: 'url to redirect to'
  }
});

// reset password
const { error } = await supabase.auth.resetPasswordForEmail(email);

// oAuth login
const { error } = await supabase.auth.signInWithOAuth({
  provider: 'oauth provider',
  options: {
    redirectTo: 'url to redirect to'
  }
});

// get user data
const user = (await this.sb.supabase.auth.getUser()).data.user;

Write Operations

// add record
const { error } = await supabase.from('profiles').insert({ ...data });

// update record by filter
const { error } = await supabase.from('profiles').update({ username }).eq('id', id);

// upsert record (add or merge record)
const { error } = await this.sb.supabase.from('profiles').upsert({ ...data });

// delete record by filter
const { error } = await this.sb.supabase.from('profiles').delete().eq('id', id);

Read Operations

// select all by filter
const { error, data } = await supabase.from('profiles').select('*').eq('username', username);

// select all with count
const { error, data, count } = await supabase.from('profiles').select('*', {count: 'exact')
  .eq('username', username);

// pagination
const getPagination = (page, size) => {
  const limit = size ? +size : 3
  const from = page ? page * limit : 0
  const to = page ? from + size - 1 : size - 1
  return { from, to }
};

const { from, to } = getPagination(page, 10);

const { error, data } = await supabase.from('profiles').select('*').range(from, to);

// order
const { error, data } = await supabase.from('profiles').select('*')
  .order('username', { ascending: true });

// inner joins (all joins use to_json() to convey child data with uniqueness)
const { error, data } = await supabase.from('posts').select('*, author!inner(*)');

PostgREST is under-the-hood

PostgREST

Supabase JS V2 Select

Storage

// upload file
const { data, error } = await supabase.storage.from('photos').upload(path, file));

// delete file by url
const { error } = await supabase.storage.from('photos').remove([url]);

// get url
const { data } = this.sb.supabase.storage.from('photos').getPublicUrl(path);

I may update this with some more items I find useful over time.

J

supabase


Related Posts

10 min read



6 min read


© 2023 Code.Build