Web Development · Module 11 · Lesson 21 min read

Using Supabase from JavaScript

Supabase in a few lines

Supabase gives you a PostgreSQL database, authentication, file storage and real-time updates, with a JavaScript client.

Terminal
npm install @supabase/supabase-js
JavaScript
import { createClient } from "@supabase/supabase-js";
const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY);

Reading and writing

JavaScript
const { data, error } = await supabase
  .from("posts")
  .select("id, title, authors(name)")   // join through the foreign key
  .eq("published", true)
  .order("created_at", { ascending: false })
  .limit(10);

await supabase.from("posts").insert({ title: "Hello" });
await supabase.from("posts").update({ title: "Hi" }).eq("id", 1);
await supabase.from("posts").delete().eq("id", 1);

⚠️ .order() sorts descending unless you pass { ascending: true }. Always check error.

Row Level Security (RLS): essential 🔐

The anon key is public (it's in your browser bundle). Your data is protected by RLS policies in the database:

SQL
alter table posts enable row level security;
create policy "read published" on posts for select using (published);
create policy "authors edit own" on posts for update using (auth.uid() = user_id);

Without RLS, anyone with your anon key could read or change everything.

Keys

  • anon key: in apps and browsers, limited by RLS.
  • service_role key: bypasses RLS. Only on servers, never in front-end code.

Example

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

const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_ANON_KEY,
);

export async function latestPosts() {
  const { data, error } = await supabase
    .from("posts")
    .select("id, title, created_at")
    .eq("published", true)
    .order("created_at", { ascending: false })
    .limit(10);
  if (error) throw error;
  return data;
}

export async function signUp(email, password) {
  const { data, error } = await supabase.auth.signUp({ email, password });
  if (error) throw error;
  return data.user;
}

// Real-time: react to new posts
supabase
  .channel("posts")
  .on("postgres_changes", { event: "INSERT", schema: "public", table: "posts" },
      (payload) => console.log("New post:", payload.new))
  .subscribe();
// 💻 Run in a Vite project with your Supabase URL and anon key in .env