Getting Started with Supabase Local Dev
course
Get started with Supabase on your machine
Browse
Find courses, lessons, articles, talks, and podcasts.
75 results for "supabase"
Showing 1–24 · Page 1 of 4
course
Get started with Supabase on your machine
lessonDuration 26sFree
Create a Supabase account and database quickly by going to https://database.new
lessonDuration 1m 25s
It is common, when working on a team, for changes to have been applied to a remote database and for your local instance to be out of sync. By running `npx supabase db pull` we can pull any changes to our remote database schema to keep our local database in sync.
lessonDuration 47s
When `npx supabase init`, `npx supabase start`, or `npx supabase db reset` is run, supabase will look for our `seed.sql` file and seed our local database. Since we have already created the project and we want to add seed data, we can run `npx supabase db reset`.
lessonDuration 1m 25s
With Supabase Link we can link our local project to a remote database. Then we can use the command `npx supabase db diff -f <fileName>` to create a local migration file. Then we use `npx supabase db push` to apply our local changes to the remote database.
lessonDuration 44s
With the project setup, we can now start our local instance of supabase. This gives us a local running version of the supabase studio that we can interact with. We will create a table in called todos in the studio
lessonDuration 55s
With our project setup we will use our supabase dev dependency to run the supabase cli. We will login to our supabase account and then init the project locally. To run supabase locally you need to have Docker installed and running on your computer. To install Docker and get it setup visit this link - https://docs.docker.com/desktop/
lessonDuration 3mFree
[Supabase](https://supabase.com/) allows us to subscribe to changes in the database, and update our UI, without the user needing to refresh the page. In this lesson, we create a subscription for `postgres_changes`, listening for any change events - insert, update or delete - on our tweets table. Additionally, we call the `router.refresh()` function to re-run our Server Components, fetching fresh data from Supabase. ## Code Snippets **Subscribe to database changes** ```tsx const channel = supabase .channel("realtime tweets") .on( "postgres_changes", { event: "*", schema: "public", table: "tweets", }, (payload) => { router.refresh(); } ) .subscribe(); ``` ## Resources - [Supabase Realtime docs](https://supabase.com/docs/guides/realtime) - [useRouter hook docs](https://nextjs.org/docs/app/api-reference/functions/use-router)
lessonDuration 4mFree
[TypeScript](https://www.typescriptlang.org/) reduces runtime errors and makes code more maintainable. In this lesson, we use the [Supabase](https://supabase.com/) CLI to introspect our PostgreSQL schema and generate TypeScript definitions. Additionally, we resolve a collection of TypeScript errors and create a custom union type for our transformed tweets - making it globally available throughout our Next.js application. ## Code Snippets **Custom type for TweetWithAuthor** ```tsx type TweetWithAuthor = Tweet & { author: Profile; likes: number; user_has_liked_tweet: boolean; }; ``` **Generate TypeScript definitions** ```bash npx supabase gen types typescript --project-id your-project-id > lib/database.types.ts ``` ## Resources - [TypeScript docs](https://www.typescriptlang.org/) - [Supabase CLI](https://supabase.com/docs/guides/cli) - [Generating TypeScript definitions](https://supabase.com/docs/guides/api/rest/generating-types)
lessonDuration 4m 6sFree
[Typescript](https://www.typescriptlang.org/) reduces runtime errors and makes our code more maintainable. [Supabase](https://supabase.com/) allows us to introspect our PostgreSQL schema and generate TypeScript definitions. In this lesson we generate an access token to use the [Supabase CLI](https://supabase.com/docs/guides/cli) and generate TypeScript definitions. Additionally, we write our types to a file, which can be passed to our Supabase client, giving our application full type-safety across client, server and database. Lastly, we make our Database types globally available so we don't need to import them every time we create a Supabase client. ## Code Snippets **Login to Supabase CLI** ```bash npx supabase login ``` **Generate TS definitions file** ```bash npx supabase gen types typescript --project-id your-project-id > lib/database.types.ts ``` ## Resources - [Generate Supabase access token](https://app.supabase.com/account/tokens) - [TypeScript docs](https://www.typescriptlang.org/) - [Supabase CLI](https://supabase.com/docs/guides/cli) - [Generating TypeScript definitions](https://supabase.com/docs/guides/api/rest/generating-types)
lessonDuration 2m 11sFree
Since we're using [Supabase](https://supabase.com/) to authenticate our users, it knows who our user is throughout the rest of the Supabase environment. In this lesson, we modify our Row Level Security (RLS) policy to only apply to the `authenticated` role to ensure that only authenticated users can select tweets. Additionally, we use the `useRouter` hook and `router.refresh()` to run our Server Component again and fetch fresh data from Supabase, after the user signs in or out. ## Code Snippets **Enable authenticated read access with RLS policy** ```sql create policy "anyone can select tweets" ON "public"."tweets" as permissive for select to authenticated using (true); ``` ## Resources - [Row Level Security docs](https://supabase.com/docs/guides/auth/row-level-security) - [useRouter hook](https://nextjs.org/docs/app/api-reference/functions/use-router#userouter)
lessonDuration 5m 58sFree
[Supabase](https://supabase.com) includes multiple authentication strategies. In this lesson, we create a Supabase client to trigger the OAuth authentication flow with GitHub. Additionally, we discuss the differences between Client and Server Components in the [Next.js App Router](https://nextjs.org/docs/app): - Client Components: user interactivity - Server Components: data fetching Lastly, we create a Route Handler to exchange an authentication code from GitHub for their Supabase session. ## Code Snippets **Authenticate with GitHub OAuth** ```tsx await supabase.auth.signInWithOAuth({ provider: "github", options: { redirectTo: "http://localhost:3000/auth/callback", }, }); ``` **Exchange code for Supabase session** ```tsx await supabase.auth.exchangeCodeForSession(code); ``` ## Resources - [Supabase Auth Helper docs](https://supabase.com/docs/guides/auth/auth-helpers/nextjs) - [Next.js App Router docs](https://nextjs.org/docs/app)
lessonDuration 3m 34sFree
Our [Supabase](https://supabase.com) project is a hosted PostgreSQL database. In this lesson, we install the [Supabase Auth Helpers](https://www.npmjs.com/package/@supabase/auth-helpers-nextjs) and [Supabase.js](https://www.npmjs.com/package/@supabase/supabase-js) npm packages, and configure environment variables to query data from Supabase: ``` NEXT_PUBLIC_SUPABASE_URL=your-supabase-url NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key ``` These values can be found in [your Supabase project's API Settings](https://app.supabase.com/project/_/settings/api). Additionally, we create a new Supabase instance using the `createServerComponentClient` function, then make our Server Component Async and suspend its rendering until our request for Supabase data resolves. Lastly, we implement a Row Level Security (RLS) policy to enable read access for the `tweets` table. ## Code Snippets **Install Supabase packages** ```bash npm i @supabase/auth-helpers-nextjs @supabase/supabase-js ``` **Import createServerComponentClient function** ```tsx import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"; import { cookies } from "next/headers"; ``` **Create Supabase client in Server Component** ```tsx const supabase = createServerComponentClient({ cookies }); ``` **Fetch data from Supabase** ```tsx const { data: tweets } = await supabase.from("tweets").select(); ``` **Pretty print data with JSON.stringify** ```tsx <pre>{JSON.stringify(tweets, null, 2)}</pre> ``` **Enable read access with RLS policy** ```sql create policy "anyone can select tweets" ON "public"."tweets" as permissive for select to public using (true); ``` ## Resources - [Supabase Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs) - [Supabase.js docs](https://supabase.com/docs/reference/javascript/installing) - [Row Level Security](https://supabase.com/docs/guides/auth/row-level-security)
lessonDuration 2m 4sFree
[Supabase](https://supabase.com/) is a collection of open source tools that wrap around a PostgreSQL database - Hosting, Auth, Realtime, File Storage, Edge Functions etc. In this lesson, we go to [database.new](https://database.new) to create a free Supabase project. Additionally, we create a `tweets` table and populate it with some seed data. ## Code Snippets **Create a `tweets` table** ```sql create table if not exists tweets ( id uuid default gen_random_uuid() primary key, created_at timestamp with time zone default timezone('utc'::text, now()) not null, title text not null ); ``` **Insert tweets** ```sql insert into tweets(title) values ('first tweet'), ('second tweet'), ('third tweet'); ``` ## Resources - [Supabase docs](https://supabase.com/docs) - [Supabase SQL Editor](https://app.supabase.com/project/_/sql)
lessonDuration 2m 4sFree
Since [Supabase](https://supabase.com/) requires our user to be authenticated to fetch tweets, it doesn't make sense for an unauthenticated user to visit the landing page. In this lesson, we implement protected routes that are only accessible to authenticated users. Additionally, we create a `/login` route to redirect unauthenticated users, which allows them to sign in with GitHub. ## Code Snippets **Redirect unauthenticated users** ```tsx const { data: { session }, } = await supabase.auth.getSession(); if (!session) { redirect("/login"); } ``` ## Resources - [Supabase Auth Helpers for Next.js docs](https://supabase.com/docs/guides/auth/auth-helpers/nextjs)
course
In this course, we build a Twitter clone from scratch, using the [Next.js App Router](https://nextjs.org/docs/app) and [Supabase](https://supabase.com/). We dive deep on the Next.js App Router, learning about: - Client Components - Server Components - Route Handlers - Server Actions - Middleware - Implementing Optimistic UI On the Supabase side we look at: - Configuring Supabase Auth to use cookies - Using Row Level Security (RLS) policies to implement Authorization - Querying data across multiple tables - Introspecting PostgreSQL schema to generate TypeScript definitions with the Supabase CLI - Subscribing to realtime database changes This course is a deep dive into modern web development and I'm very excited to see what you're going to build on the other side! 🚀
course
[Supabase](http://supabase.com?utm_source=egghead&utm_campaign=remix) is a collection of open-source tools that wrap around a PostgreSQL database. In this course, we look at building a realtime chat application with Remix, using Supabase for db hosting, authentication, authorization and subscribe to realtime db events - updating the UI as the database changes. We will learn about: - loaders and actions in Remix - querying and mutating data with Supabase - authentication with GitHub - authorization with RLS - merging client and server state with realtime events - deploying a Remix app to Vercel This course is 100% TypeScript, however, don't stress if you don't have any experience with TS, as Supabase does most of the heavy lifting here! 🎉
lessonDuration 4m 11sFree
TypeScript helps us build more robust, maintainable and safe applications. In this lesson, we look at installing the [Supabase CLI](https://supabase.com/docs/reference/cli), and using it to generate type definitions for Supabase. We can use this to add TypeScript support to our Supabase client, which flows through our entire application - server and client. This means we get in-editor feedback about what we can and can't do with Supabase, helping to discover cool new things, while reducing bugs. Additionally, we use the `LoaderArgs` type signature for our Loader function, which allows us to infer the return type in our component. > Note: this does not automatically update with changes to Supabase. You need to manually run this command whenever you change the structure of the database. ## Code Snippets **Generate TypeScript definitions from Supabase** ```bash supabase gen types typescript --project-id your-project-id > db_types.ts ``` **Create typesafe Supabase client** ```tsx import { createClient } from "@supabase/supabase-js"; import type { Database } from "db_types"; export default createClient<Database>( process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY! ); ``` **Fetch data with end-to-end type defs** ```tsx import { useLoaderData } from "@remix-run/react"; import supabase from "utils/supabase"; import type { LoaderArgs } from "@remix-run/node"; export const loader = async ({}: LoaderArgs) => { const { data } = await supabase.from("messages").select(); return { messages: data ?? [] }; }; export default function Index() { const { messages } = useLoaderData<typeof loader>(); return <pre>{JSON.stringify(messages, null, 2)}</pre>; } ``` ## Resources - [Supabase CLI](https://supabase.com/docs/reference/cli) - [Supabase TypeScript Support](https://supabase.com/docs/reference/javascript/typescript-support) - [Remix decision to infer types](https://github.com/remix-run/remix/blob/main/decisions/0003-infer-types-for-useloaderdata-and-useactiondata-from-loader-and-action-via-generics.md)
lessonDuration 5m 16sFree
[Supabase Realtime](https://supabase.com/docs/guides/realtime) allow us to subscribe to change events in the database - `insert`, `update` and `delete` - and update the UI dynamically. In this lesson, we [enable `replication` on the `messages` table](https://app.supabase.com/project/_/database/replication) to tell Supabase we want to know about changes to this table. Additionally, we use the Supabase client to set up a subscription for `insert` events on the `messages` table. This will receive websocket updates from Supabase, which we can handle in a callback function, and merge our server state with realtime updates, to allow our application to dynamically update as new messages are sent. ## Code Snippets **Subscribe to realtime updates** ```tsx useEffect(() => { const channel = supabase .channel("*") .on( "postgres_changes", { event: "INSERT", schema: "public", table: "messages" }, (payload) => { const newMessage = payload.new as Message; if (!messages.find((message) => message.id === newMessage.id)) { setMessages([...messages, newMessage]); } } ) .subscribe(); return () => { supabase.removeChannel(channel); }; }, [supabase, messages, setMessages]); ``` **Enable realtime events on messages table** ```sql alter table public.messages replica identity full; ``` > SQL code snippets can be run against your Supabase database by heading over to your project's [SQL Editor](https://app.supabase.com/project/_/sql), pasting them into a new query, and clicking `RUN`. ## Resources - [Your project's replication settings](https://app.supabase.com/project/_/database/replication) - [Supabase docs - Realtime guide](https://supabase.com/docs/guides/realtime) - [Supabase docs - Realtime in JS](https://supabase.com/docs/reference/javascript/subscribe)
lessonDuration 9m 13sFree
Supabase supports [a collection of auth strategies](https://supabase.com/docs/guides/auth) - Email and password, passwordless and OAuth. In this lesson, we look at implementing OAuth with GitHub. In order to do this, we [create a new GitHub OAuth app](https://github.com/settings/applications/new), and configure Supabase to use its Client ID and Secret. Additionally, we create a `<Login />` component that uses the Supabase client to sign users in and out. This identifies a problem that we don't have access to the environment variables required to create a Supabase client outside of loaders or actions. Therefore, we pipe through our `SUPABASE_URL` and `SUPABASE_ANON_KEY` from the Loader function, and create a singleton Supabase client, to use across our components. Lastly, we look at sharing this single instance of Supabase through the Outlet Context and declare types to ensure we have TypeScript helping us out throughout the application. ## Code Snippets **Expose environment variables from the server** ```tsx export const loader = async ({}: LoaderArgs) => { const env = { SUPABASE_URL: process.env.SUPABASE_URL!, SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY!, }; return json({ env }); }; ``` **Access `env` in component** ```tsx const { env } = useLoaderData<typeof loader>(); ``` **Create a singleton Supabase client** ```tsx const [supabase] = useState(() => createClient<Database>(env.SUPABASE_URL, env.SUPABASE_ANON_KEY) ); ``` **Share global variables with Outlet Context** ```tsx <Outlet context={{ supabase }} /> ``` **Consuming Outlet Context** ```tsx const { supabase } = useOutletContext<SupabaseOutletContext>(); ``` **Logging in with GitHub** ```tsx await supabase.auth.signInWithOAuth({ provider: "github", }); ``` **Logging out** ```tsx await supabase.auth.signOut(); ``` **Entire root component** ```tsx import { json, LoaderArgs, MetaFunction } from "@remix-run/node"; import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, } from "@remix-run/react"; import { createClient, SupabaseClient } from "@supabase/supabase-js"; import { useState } from "react"; import type { Database } from "db_types"; type TypedSupabaseClient = SupabaseClient<Database>; export type SupabaseOutletContext = { supabase: TypedSupabaseClient; }; export const meta: MetaFunction = () => ({ charset: "utf-8", title: "New Remix App", viewport: "width=device-width,initial-scale=1", }); export const loader = async ({}: LoaderArgs) => { const env = { SUPABASE_URL: process.env.SUPABASE_URL!, SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY!, }; return json({ env }); }; export default function App() { const { env } = useLoaderData<typeof loader>(); const [supabase] = useState(() => createClient<Database>(env.SUPABASE_URL, env.SUPABASE_ANON_KEY) ); return ( <html lang="en"> <head> <Meta /> <Links /> </head> <body> <Outlet context={{ supabase }} /> <ScrollRestoration /> <Scripts /> <LiveReload /> </body> </html> ); } ``` ## Resources - [Supabase docs - login with GitHub](https://supabase.com/docs/guides/auth/auth-github) - [Remix docs - Outlet Context](https://remix.run/docs/en/v1/api/remix#useoutletcontext)
lessonDuration 2m 12sFree
[Supabase](http://supabase.com?utm_source=egghead&utm_campaign=remix) handles hosting a database, authentication, authorization, file storage, realtime, edge functions, database functions, triggers and webhooks - lots of ways to build apps and automate backend stuff. In this lesson, we head over to [database.new](https://database.new) to create a new Supabase project. Additionally, we use the dashboard to easily create a new table for our `messages`. We talk through some different data types and constraints that can be applied to columns. Lastly, we populate our new table with some example messages. ## Code Snippets > SQL code snippets can be run against your Supabase database by heading over to your project's [SQL Editor](https://app.supabase.com/project/_/sql), pasting them into a new query, and clicking `RUN`. **Create a messages table** ```sql create table if not exists messages ( id uuid default uuid_generate_v4() primary key, created_at timestamp with time zone default timezone('utc'::text, now()) not null, content text not null ); ``` **Insert messages** ```sql insert into messages(content) values ('first message'), ('second message'); ``` ## Resources - [Supabase Docs](https://supabase.com/docs)
lessonDuration 4m 22sFree
To mutate data in Remix, we use an Action function. In this lesson, we look at creating a Remix `<Form />` to submit the content of a message as a `post` request to our `Action` function. Additionally, we use the server-side Supabase client from the Remix Auth Helpers package to make an authenticated request to Supabase, writing the new message to the `messages` table. Futhermore, we run into an issue with RLS as we have not yet written a policy for the `insert` action. By setting this to the `authenticated` role and ensuring that the `user_id` column is equal to the value returned by the `auth.uid()` function - a function we get from Supabase to retrieve the ID for the user attempting to insert a new row - we ensure that users can not write a message on someone else's behalf. Lastly, we use the `auth.uid()` function to set the default value of the `user_id` column to the ID of the user attempting to `insert` the new row in the `messages` table. ## Code Snippets **Write data to Supabase** ```tsx export const action = async ({ request }: ActionArgs) => { const response = new Response(); const supabase = createServerSupabase({ request, response }); const { message } = Object.fromEntries(await request.formData()); await supabase.from("messages").insert({ content: String(message) }); return json(null, { headers: response.headers }); }; ``` **Form to submit to action** ```tsx <Form method="post"> <input type="text" name="message" /> <button type="submit">Send</button> </Form> ``` **Add policy for insert** ```sql create policy "users can insert their own messages" on "public"."messages" as permissive for insert to authenticated wuth check (user_id = auth.uid()); ``` > SQL code snippets can be run against your Supabase database by heading over to your project's [SQL Editor](https://app.supabase.com/project/_/sql), pasting them into a new query, and clicking `RUN`. ## Resources - [Supabase docs - insert](https://supabase.com/docs/reference/javascript/insert) - [Implement Row Level Security in Supabase (video)](https://www.youtube.com/watch?v=Ow_Uzedfohk) - [Remix docs - Writing data](https://remix.run/docs/en/v1/guides/data-writes)
lessonDuration 3m 52sFree
The [supabase-js](https://supabase.com/docs/reference/javascript) package allows us to connect to our Supabase project, and easily query and mutate data. In this lesson, we install `supabase-js`, set up environment variables for `SUPABASE_URL` and `SUPABASE_ANON_KEY`, and create a Supabase client to use across our application. Additionally, we look at writing an RLS policy to enable `read` access to our `messages` table, use our Supabase client to select all messages, and display them in our Remix app on load. ## Code Snippets **Install supabase-js** ```bash npm i @supabase/supabase-js ``` **Use a Loader function to fetch data** ```tsx export const loader = async () => { return null; }; ``` **Fetch data with Supabase Client** ```tsx const { data } = await supabase.from("messages").select(); ``` **Full component** ```tsx import { useLoaderData } from "@remix-run/react"; import supabase from "utils/supabase"; export const loader = async ({}) => { const { data } = await supabase.from("messages").select(); return { data }; }; export default function Index() { const { data } = useLoaderData(); return <pre>{JSON.stringify(data, null, 2)}</pre>; } ``` **Enable read access with RLS policy** ```sql create policy "users can read messages" ON "public"."messages" as permissive for select to public using (true); ``` > SQL code snippets can be run against your Supabase database by heading over to your project's [SQL Editor](https://app.supabase.com/project/_/sql), pasting them into a new query, and clicking `RUN`. ## Resources - [Supabase-js docs](https://supabase.com/docs/reference/javascript) - [Implement Row Level Security in Supabase (video)](https://www.youtube.com/watch?v=Ow_Uzedfohk) - [Auto-generated project docs](https://app.supabase.com/project/_/api)
lessonDuration 5m 31sFree
Remix Loaders allow us to fetch data server-side, before rendering a component. This works great if you are implementing your authorization rules for data fetching in the loader function, however, Supabase allows us to use Row Level Security policies to write access policies alongside the data in the database. By default, `supabase-js` stores session data in `localStorage`, which exists only within the user's browser. If we want this session to be available within Loader or Action functions in Remix, we need to store the session in a cookie. Cookies are automatically sent with every request to the server. In this lesson, we look at using the Supabase Auth Helpers package for Remix to automate this process, and swap out the storage mechanism for the Supabase client, to use cookies to store session data. Additionally, we refactor our application to use the new `createServerClient` and `createBrowserClient` functions, making cookies the single source of truth about the user's current session, across the server and client-side of our Remix app. ## Code Snippets **Install Remix Auth Helpers** ```bash npm i @supabase/auth-helpers-remix ``` **Create server-side Supabase client** ```tsx import { createServerClient } from "@supabase/auth-helpers-remix"; import type { Database } from "db_types"; export default ({ request, response, }: { request: Request; response: Response; }) => createServerClient<Database>( process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY!, { request, response } ); ``` **Create client-side Supabase client (simplified)** ```tsx import { useState } from "react"; import { createBrowserClient } from "@supabase/auth-helpers-remix"; export const loader = async ({ request }: LoaderArgs) => { const env = { SUPABASE_URL: process.env.SUPABASE_URL!, SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY!, }; return json({ env }); }; const { env, session } = useLoaderData<typeof loader>(); const [supabase] = useState(() => createBrowserClient<Database>(env.SUPABASE_URL, env.SUPABASE_ANON_KEY) ); return <Outlet context={{ supabase }} />; ``` **Use Supabase in a loader** ```tsx export const loader = async ({ request }: LoaderArgs) => { const response = new Response(); const supabase = createServerSupabase({ request, response }); const { data } = await supabase.from("messages").select(); return json({ data }, { headers: response.headers }); }; ``` **Use Supabase in an action** ```tsx export const action = async ({ request }: ActionArgs) => { const response = new Response(); const supabase = createServerSupabase({ request, response }); const { data } = await supabase.from("messages").insert({ content: "hello" }); return json({ data }, { headers: response.headers }); }; ``` **Use Supabase in a component** ```tsx import { useOutletContext } from "@remix-run/react"; import type { SupabaseOutletContext } from "~/root"; export default function Login() { const { supabase } = useOutletContext<SupabaseOutletContext>(); const handleLogin = async () => { await supabase.auth.signInWithOAuth({ provider: "github", }); }; return <button onClick={handleLogin}>Login</button>; } ``` ## Resources - [Supabase docs - Remix Auth Helpers](https://supabase.com/docs/guides/auth/auth-helpers/remix)