Supabase Tutorial: Local Setup, Migrations, and RLS

Updated 3 min read

Modern web development often gets bogged down by repetitive boilerplate for databases, user authentication, and access rules. This Supabase tutorial guides full-stack JavaScript and TypeScript developers through setting up an end-to-end backend workflow. By following these steps, you will establish a local development environment, define version-controlled schemas, secure data with database policies, and query your database via the official client library.

Watch the video on YouTube

Before you start

  • Basic knowledge of JavaScript and SQL syntax
  • Node.js version 20 or later installed locally
  • Docker Engine running on your machine for local database emulation

Project Setup and CLI Installation

Rather than installing database management tools globally across your operating system, the official recommendation is to add the CLI as a project development dependency. This keeps your dependencies pinned and prevents version discrepancies between team members and automated build systems.

Initialize your package file and install the supabase package as shown below. Finally, run the project initialization command to generate the configuration files and scaffolding directories needed for local emulation.

TerminalNot verified in our test run
npm init -y
npm install --save-dev supabase
npx supabase init --vscode=false
Output from our test run
$ npm init -y
Wrote to /root/package.json:

{
  "name": "root",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

$ npm install --save-dev supabase

added 8 packages, and audited 9 packages in 9s

4 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
$ npx supabase init --vscode=false

Understanding the Local Stack Architecture

Supabase emulates its entire cloud infrastructure on your machine using Docker containers. Running the start command spins up a full PostgreSQL database, the GoTrue authentication engine, and PostgREST for automated HTTP endpoints.

This local setup also includes Supabase Studio, an administrative web dashboard running locally alongside your services. Developing locally allows you to iterate on schemas and test backend functionality offline without incurring cloud computing costs or modifying live production records.

Creating Versioned Database Migrations

Modifying database tables through web dashboards makes tracking changes and collaborating difficult. A reproducible development process relies on versioned SQL migrations stored directly in your source code repository.

Use the migration command displayed below to generate a new timestamped SQL file inside the migrations folder. You will use this generated file to write and commit your table definitions and database constraints.

TerminalNot verified in our test run
# Generate a timestamped SQL migration file
npx supabase migration new create_profiles_and_posts

Configuring Row Level Security (RLS)

Supabase exposes automated REST endpoints directly to the public web, making Row Level Security essential. If you omit enabling Row Level Security on a new table, any client holding your public anonymous key can read or mutate your records without restriction.

Activating Row Level Security denies all access by default until you declare explicit policies. In the migration file shown below, one policy allows read access to everyone, while an insert policy ensures that authenticated users can only create records matching their user ID.

supabase/migrations/20250101000000_create_profiles_and_posts.sql
create table public.profiles (
  id uuid references auth.users on delete cascade primary key,
  username text unique not null,
  created_at timestamptz default now() not null
);

alter table public.profiles enable row level security;

create policy "Public profiles are viewable by everyone"
  on public.profiles for select
  using (true);

create policy "Users can insert their own profile"
  on public.profiles for insert
  with check ((select auth.uid()) = id);

Installing the Client SDK and Key Management

To connect your frontend or backend application to your database, install the official client library shown in the command below. Managing API keys securely is vital when distributing access across different application tiers.

The public anonymous key is intentionally designed to be exposed to client-side browsers and is entirely constrained by your database policies. Conversely, the secret service role key bypasses every access control rule and must never be exposed in client bundles or public repositories.

TerminalNot verified in our test run
# Install the official Supabase client library
npm install @supabase/supabase-js

Integrating the Supabase Client

You can configure and export your client instance by importing the client factory method and supplying your project credentials. The exported client instance exposes chainable helper methods for querying, inserting, and ordering database rows.

Review the JavaScript implementation below for an example of retrieving ordered profiles. If your project uses server-side rendering frameworks like Next.js or Remix, avoid using a single global client across multiple requests, and instead adopt cookie-based authentication libraries to avoid leaking sessions between users.

src/supabaseClient.js
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.SUPABASE_URL || 'https://xyzcompany.supabase.co';
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || 'public-anon-key';

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

export async function getProfiles() {
  const { data, error } = await supabase
    .from('profiles')
    .select('id, username, created_at')
    .order('created_at', { ascending: false });

  if (error) {
    throw error;
  }
  return data;
}

Verifying Client Initialization

Once your dependencies are in place, you can evaluate client initialization using an inline Node script. Running the command below imports the module dynamically, instantiates the client using placeholder values, and checks that query-building methods are defined.

Testing the module import directly validates that your runtime environment correctly resolves the installed package before you wire it into your application code.

TerminalNot verified in our test run
# Verify client module resolution and instantiation
node -e "import('@supabase/supabase-js').then(({ createClient }) => { const client = createClient('https://example.supabase.co', 'sb-anon-key-placeholder'); console.log('Client initialized successfully:', typeof client.from === 'function'); });"

Deploying to Production

After verifying your database schema and policies locally, you can synchronize your work with the cloud. Linking your repository to a hosted Supabase project prepares your environment for automated schema deployments.

Pushing your migrations applies your local SQL history directly to your hosted database. This ensures your remote production and staging environments reflect the exact schema tracked in your version control system.

Wrap-up

You now have a structured workflow for developing with Supabase, moving from local containerized emulation to version-controlled database migrations and secure client querying. Relying on declarative SQL policies and properly scoped API keys ensures your full-stack applications remain robust and secure. Continue expanding your project by exploring storage buckets and server-side authentication flows as your architecture grows.

FAQ

Why should I install the Supabase CLI as a dev-dependency instead of globally?

Installing the CLI locally pins the exact version inside your package configuration, ensuring consistent behavior across all team members and continuous integration pipelines.

What happens if I forget to enable Row Level Security on a table?

Because Supabase generates public HTTP endpoints automatically, leaving Row Level Security disabled allows anyone with your public anonymous key to read, update, or delete records in that table.

Can I use the standard JavaScript client in modern SSR frameworks?

Using a single global client instance in server-rendered environments can leak user sessions across incoming requests; SSR frameworks should use cookie-based client packages instead.

Sources

Subscribe for more tested tutorials