The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Copy over all files from guides folder from reference
Joshen Lim5531d7403e13
diff --git a/apps/temp-docs/docs/guides/_partials/project_setup.mdx b/apps/temp-docs/docs/guides/_partials/project_setup.mdxnew file mode 100644index 00000000000..271a3c426cb--- /dev/null+++ b/apps/temp-docs/docs/guides/_partials/project_setup.mdx@@ -0,0 +1,66 @@+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import UserManagementSQLTemplate from './user_management_quickstart_sql_template.md'++## Project set up++Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase+and then creating a "schema" inside the database.++### Create a project++1. Go to [app.supabase.com](https://app.supabase.com).+1. Click on "New Project".+1. Enter your project details.+1. Wait for the new database to launch.++### Set up the database schema++Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,+or you can just copy/paste the SQL from below and run it yourself.++<Tabs+ groupId="language"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>+<TabItem value="dashboard">++1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard.+2. Click **User Management Starter**.+3. Click **Run**.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/sql-user-management-starter.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++</TabItem>+<TabItem value="sql">+<UserManagementSQLTemplate />+</TabItem>+</Tabs>++### Get the API Keys++Now that you've created some database tables, you are ready to insert data using the auto-generated API.+We just need to get the URL and `anon` key from the API settings.++1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard.+2. Click **API** in the sidebar.+3. Find your API `URL`, `anon`, and `service_role` keys on this page.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>diff --git a/apps/temp-docs/docs/guides/_partials/quickstart_intro.md b/apps/temp-docs/docs/guides/_partials/quickstart_intro.mdnew file mode 100644index 00000000000..36b56131364--- /dev/null+++ b/apps/temp-docs/docs/guides/_partials/quickstart_intro.md@@ -0,0 +1,11 @@+## Intro++This example provides the steps to build a basic user management app. It includes:++- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data.+- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email).+- Supabase [Storage](/docs/guides/storage): users can upload a photo.+- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data.+- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables.++By the end of this guide you'll have an app which allows users to login and update some basic profile details:diff --git a/apps/temp-docs/docs/guides/_partials/user_management_quickstart_sql_template.md b/apps/temp-docs/docs/guides/_partials/user_management_quickstart_sql_template.mdnew file mode 100644index 00000000000..ba55c4aeab3--- /dev/null+++ b/apps/temp-docs/docs/guides/_partials/user_management_quickstart_sql_template.md@@ -0,0 +1,55 @@+```sql+-- Create a table for public profiles+create table profiles (+ id uuid references auth.users not null primary key,+ updated_at timestamp with time zone,+ username text unique,+ full_name text,+ avatar_url text,+ website text,++ constraint username_length check (char_length(username) >= 3)+);+-- Set up Row Level Security (RLS)+-- See https://supabase.com/docs/guides/auth/row-level-security for more details.+alter table profiles+ enable row level security;++create policy "Public profiles are viewable by everyone." on profiles+ for select using (true);++create policy "Users can insert their own profile." on profiles+ for insert with check (auth.uid() = id);++create policy "Users can update own profile." on profiles+ for update using (auth.uid() = id);++-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth.+-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details.+create function public.handle_new_user()+returns trigger as $$+begin+ insert into public.profiles (id, full_name, avatar_url)+ values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');+ return new;+end;+$$ language plpgsql security definer;+create trigger on_auth_user_created+ after insert on auth.users+ for each row execute procedure public.handle_new_user();++-- Set up Storage!+insert into storage.buckets (id, name)+ values ('avatars', 'avatars');++-- Set up access controls for storage.+-- See https://supabase.com/docs/guides/storage#policy-examples for more details.+create policy "Avatar images are publicly accessible." on storage.objects+ for select using (bucket_id = 'avatars');++create policy "Anyone can upload an avatar." on storage.objects+ for insert with check (bucket_id = 'avatars');++create policy "Anyone can update their own avatar." on storage.objects+ for update using (auth.uid() = owner) with check (bucket_id = 'avatars');+```diff --git a/apps/temp-docs/docs/guides/api.mdx b/apps/temp-docs/docs/guides/api.mdxnew file mode 100644index 00000000000..b4e3e48bd09--- /dev/null+++ b/apps/temp-docs/docs/guides/api.mdx@@ -0,0 +1,414 @@+---+id: api+title: APIs+description: Auto-generating and Realtime APIs.+sidebar_label: Overview+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import useBaseUrl from '@docusaurus/useBaseUrl'++## Overview++Supabase generates three types of API directly from your database schema.++- REST - interact with your database through a restful interface.+- Realtime - listen to database changes.+- GraphQL - [in beta](https://supabase.com/blog/pg-graphql).++The APIs are:++- **Instant and auto-generated.** <br />As you update your database the changes are immediately accessible through your API.+- **Self documenting.** <br />Supabase generates documentation in the Dashboard which updates as you make database changes.+- **Secure.** <br />The API is configured to work with PostgreSQL's Row Level Security, provisioned behind an API gateway with key-auth enabled.+- **Fast.** <br />Our benchmarks for basic reads are more than 300% faster than Firebase. The API is a very thin layer on top of Postgres, which does most of the heavy lifting.+- **Scalable.** <br />The API can serve thousands of simultaneous requests, and works well for Serverless workloads.++### REST API {#rest-api-overview}++Supabase provides a RESTful API using [PostgREST](https://postgrest.org/). This is a very thin API layer on top of Postgres.+It provides everything you need from a CRUD API:++- Basic CRUD operations+- Deeply nested joins, allowing you to fetch data from multiple tables in a single fetch+- Works with Postgres Views+- Works with Postgres Functions+- Works with the Postgres security model - including Row Level Security, Roles, and Grants.++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/rPAJJFdtPw0"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++### GraphQL API {#graphql-api-overview}++:::note++GraphQL is in Beta, and may have breaking changes. It is only available on self-hosted setups and Supabase projects created after 28th March 2022.++:::++GraphQL in Supabase works through [pg_graphql](https://supabase.com/blog/pg-graphql), an open source PostgreSQL extension for GraphQL.++### Realtime API {#realtime-api-overview}++Supabase provides a Realtime API using [Realtime](https://github.com/supabase/realtime). You can use this to listen to database changes over websockets.+Realtime leverages PostgreSQL's built-in logical replication. You can manage your Realtime API simply by managing Postgres publications.++## Getting started++All APIs are auto-created from Database tables. After you have added tables or functions to your database, you can use the APIs provided.++### Creating API Routes++API routes are automatically created when you create Postgres Tables, Views, or Functions.++Let's create our first+API route by creating a table called `todos` to store tasks.+This creates a corresponding route `todos` which can accept `GET`, `POST`, `PATCH`, & `DELETE` requests.++<Tabs+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+1. Click **New Table** and create a table with the name `todos`.+1. Click **Save**.+1. Click **New Column** and create a column with the name `task` and type `text`.+1. Click **Save**.++<video width="99%" muted playsInline controls="true">+ <source+ src={useBaseUrl('/videos/api/api-create-table-sm.mp4')}+ type="video/mp4"+ muted+ playsInline+ />+</video>++</TabItem>+<TabItem value="sql">++```sql+-- Create a table called "todos" with a column to store tasks.++create table todos (+ id bigint generated by default as identity primary key,+ task text check (char_length(task) > 3)+);+```++</TabItem>+</Tabs>++### API URL and Keys++Every Supabase project has a unique API URL. Your API is secured behind an API gateway which requires an API Key for every request.++1. Go to the [Settings](https://app.supabase.com/project/_/settings/general) page in the Dashboard.+2. Click **API** in the sidebar.+3. Find your API `URL`, `anon`, and `service_role` keys on this page.++<video width="99%" muted playsInline controls="true">+ <source+ src={useBaseUrl('/videos/api/api-url-and-key.mp4')}+ type="video/mp4"+ muted+ playsInline+ />+</video>++The REST API and the GraphQL API are both accessible through this URL:++- REST: `https://<project_ref>.supabase.co/rest/v1`+- GraphQL: `https://<project_ref>.supabase.co/graphql/v1`++Both of these routes require the `anon` key to be passed through an `apikey` header.++#### API Keys++You are provided with two keys:++- an `anon` key, which is safe to be used in a browser context.+- a `service_role` key, which should only be used on a server. This key can bypass Row Level Security. NEVER use this key in a browser.++### Accessing the docs in the Dashboard++#### REST API {#rest-api-dashboard-docs}++Supabase generates documentation in the [Dashboard](https://app.supabase.com) which updates as you make database changes.+Let's view the documentation for a `countries` table which we created in our database.++1. Go to the [API](https://app.supabase.com/project/_/api) page in the Dashboard.+2. Find the `countries` table under **Tables and Views** in the sidebar.+3. Switch between the JavaScript and the cURL docs using the tabs.++<video width="99%" muted playsInline controls="true">+ <source+ src={useBaseUrl('/videos/api/api-docs.mp4')}+ type="video/mp4"+ muted+ playsInline+ />+</video>++#### GraphQL++The GraphQL Endpoint that we provide (`https://<project_ref>.supabase.co/graphql/v1`) is compatible with any GraphiQL implementation that can pass an `apikey` header.+Some suggested applications:++- [paw.cloud](https://paw.cloud)+- [insomnia.rest](https://insomnia.rest)+- [postman.com/graphql](https://www.postman.com/graphql/)+- Self-hosted GraphiQL: GraphiQL can be served through a simple HTML file. See [this discussion](https://github.com/supabase/supabase/discussions/6144) for more details.++## Using the API++### REST API++You can interact with your API directly via HTTP requests, or you can use the client libraries which we provide.++Let's see how to make a request to the `todos` table which we created in the first step,+using the API URL (`SUPABASE_URL`) and Key (`SUPABASE_ANON_KEY`) we provided:++<Tabs+ groupId="language"+ defaultValue="javascript"+ values={[+ {label: 'JavaScript', value: 'javascript'},+ {label: 'cURL', value: 'curl'},+ ]}>++<TabItem value="javascript">++```javascript+// Initialize the JS client+import { createClient } from '@supabase/supabase-js'+const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)++// Make a request+const { data: todos, error } = await supabase.from('todos').select('*')+```++</TabItem>+<TabItem value="curl">++```bash+# Append /rest/v1/ to your URL, and then use the table name as the route+curl '<SUPABASE_URL>/rest/v1/todos' \+-H "apikey: <SUPABASE_ANON_KEY>" \+-H "Authorization: Bearer <SUPABASE_ANON_KEY>"+```++</TabItem>+</Tabs>++JS Reference: [select()](../reference/javascript/select),+[insert()](../reference/javascript/insert),+[update()](../reference/javascript/update),+[upsert()](../reference/javascript/upsert),+[delete()](../reference/javascript/delete),+[rpc()](../reference/javascript/rpc) (call Postgres functions).++### GraphQL API++:::note++To rebuild your GraphQL schema from the SQL schema, call `select graphql.rebuild_schema();`.+Be sure to rebuild the GraphQL schema after altering the SQL schema.++:::++You can use any GraphQL client with the Supabase GraphQL API. For our GraphQL example we will use [urql](https://formidable.com/open-source/urql/docs/).++<Tabs+ groupId="language"+ defaultValue="javascript"+ values={[+ {label: 'JavaScript', value: 'javascript'},+ {label: 'cURL', value: 'curl'},+ ]}>++<TabItem value="javascript">++```javascript+import { createClient, useQuery } from 'urql'++// Prepare API key and Authorization header+const headers = {+ apikey: <SUPABASE_ANON_KEY>,+ authorization: `Bearer ${<SUPABASE_ANON_KEY}`>+}++// Create GraphQL client+// See: https://formidable.com/open-source/urql/docs/basics/react-preact/#setting-up-the-client+const client = createClient({+ url: '<SUPABASE_URL>/graphql/v1',+ fetchOptions: function createFetchOptions() {+ return { headers }+ },+})++// Prepare our GraphQL query+const TodosQuery = `+ query {+ todosCollection {+ edges {+ node {+ id+ title+ }+ }+ }+ }+`++// Query for the data (React)+const [result, reexecuteQuery] = useQuery({+ query: TodosQuery,+})++// Read the result+const { data, fetching, error } = result+```++</TabItem>+<TabItem value="curl">++```bash+# Append /graphql/v1/ to your URL, and then use the table name as the route+curl --request POST '<SUPABASE_URL>/graphql/v1' \+-H 'apikey: <SUPABASE_ANON_KEY>' \+-H 'Authorization: Bearer <SUPABASE_ANON_KEY>' \+-d '{ "query":"{ todos(first: 3) { edges { node { id } } } }" }'+```++</TabItem>+</Tabs>++### Realtime API++By default Realtime is disabled on your database. Let's turn on Realtime for the `todos` table.++<Tabs+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Replication** in the sidebar.+3. Control which database events are sent by toggling **Insert**, **Update**, and **Delete**.+4. Control which tables broadcast changes by selecting **Source** and toggling each table.++<video width="99%" muted playsInline controls="true">+ <source+ src={useBaseUrl('/videos/api/api-realtime.mp4')}+ type="video/mp4"+ muted+ playsInline+ />+</video>++</TabItem>+<TabItem value="sql">++```sql+alter publication supabase_realtime add table todos;+```++</TabItem>+</Tabs>++From the client, we can listen to any new data that is inserted into the `todos` table:++```javascript+// Initialize the JS client+import { createClient } from '@supabase/supabase-js'+const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)++// Create a function to handle inserts+const handleInserts = (payload) => {+ console.log('Change received!', payload)+}++// Listen to inserts+const { data: todos, error } = await supabase+ .from('todos')+ .on('INSERT', handleInserts)+ .subscribe()+```++Use [subscribe()](/docs/reference/javascript/subscribe) to listen to database changes.+The Realtime API works through PostgreSQL's replication functionality. Postgres sends database changes to a [publication](/docs/guides/database/replication#publications)+called `supabase_realtime`, and by managing this publication you can control which data is broadcast.++## API Security++### Securing your Routes++Your API is designed to work with Postgres Row Level Security (RLS). If you use Supabase [Auth](/guides/auth), you can restrict data based on the logged-in user.+To control access to your data, you can use [Policies](/guides/auth#policies).+When you create a table in Postgres, Row Level Security is disabled by default. To enable RLS:++<Tabs+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Authentication](https://app.supabase.com/project/_/auth/users) page in the Dashboard.+2. Click on **Policies** in the sidebar.+3. Select **Enable RLS** to enable Row Level Security.++</TabItem>+<TabItem value="sql">++```sql+alter table todos enable row level security;+```++</TabItem>+</Tabs>++### The `service_role` key++Never expose the `service_role` key in a browser or anywhere where a user can see it. This Key is designed to bypass Row Level Security - so it should only be used on a private server.++We have [partnered with GitHub](https://github.blog/changelog/2022-03-28-supabase-is-now-a-github-secret-scanning-partner/) to scan for Supabase `service_role` keys pushed to public repositories.+If they detect any keys with service_role privileges being pushed to GitHub, they will forward the API key to us, so that we can automatically revoke the detected secrets and notify you, protecting your data against malicious actors.++### Safeguards towards accidental deletes and updates++For all projects, by default, the Postgres extension [safeupdate](https://github.com/eradman/pg-safeupdate) is enabled for all queries coming from the API.+This ensures that any `delete()` or `update()` would fail if there are no accompanying filters provided.+To confirm that safeupdate is enabled for queries going through the API of your project, the following query could be run:++```sql+select usename,useconfig from pg_shadow where usename = 'authenticator' ;+```++The expected value for `useconfig` should be:++```+["session_preload_libraries=supautils, safeupdate"]+```diff --git a/apps/temp-docs/docs/guides/api/generating-types.mdx b/apps/temp-docs/docs/guides/api/generating-types.mdxnew file mode 100644index 00000000000..7c1ccdb41f8--- /dev/null+++ b/apps/temp-docs/docs/guides/api/generating-types.mdx@@ -0,0 +1,119 @@+---+id: generating-types+title: 'Generating Types'+description: How to generate types for your API and Supabase libraries.+---++Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions.++### Generating types from OpenAPI specification++Supabase generates an OpenAPI specification file for your database which can be used to generate your data types for usage with TypeScript.++The OpenAPI specification for your Supabase project can be accessed as follows:++```txt+https://your-project.supabase.co/rest/v1/?apikey=your-anon-key+```++Using the open source [openapi-typescript](https://github.com/drwpow/openapi-typescript#%EF%B8%8F-reading-specs-from-remote-resource) tool you can generate your types and store them locally:++```bash+npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/supabase.ts+```++Important notes:++- Since the generator uses JSON API, there is no way to determine if a column is an Array. It will generate array types as `string`, even though Supabase handles this automatically and returns arrays.+ You can fix this manually in the files by changing the type, e.g. `names: string` -> `names: string[]`+- The types won't automatically stay in sync with your database, so make sure to regenerate your types after you make changes to your database.++After you have generated your types, you can use them in your TypeScript projects:++```ts+import { NextApiRequest, NextApiResponse } from 'next'+import { createClient } from '@supabase/supabase-js'+import { definitions } from '../../types/supabase'++const supabase = createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.SUPABASE_SECRET_KEY+)++export default async (req: NextApiRequest, res: NextApiResponse) => {+ const allOnlineUsers = await supabase+ .from<definitions['users']>('users')+ .select('*')+ .eq('status', 'ONLINE')+ res.status(200).json(allOnlineUsers)+}+```++For more advance type-support, check out [`postgrest-js-tools`](https://github.com/mzalevski/postgrest-js-tools).++## Update types automatically with GitHub Actions++One way to keep your type definitions in sync with your database is to set up a GitHub action that runs on a schedule.++The following script can be run in your terminal to produce the file `types/database/index.ts`.++```+npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/database/index.ts+```++You can add this script to your `package.json` and run it using `npm run update-types`:++```+"update-types": "npx openapi-typescript \"${SUPABASE_URL}/rest/v1/?apikey=${SUPABASE_ANON_KEY}\" --version=2 --output types/database/index.ts"+```++You can use GitHub actions to generate this file automatically. This script will commit the change to your repo every night.+Create a file `.github/workflows/update-types.yml` and add the following snippet into this file to define the action along with the environment variables.++```yml+name: Update database types++on:+ schedule:+ # sets the action to run daily. You can modify this to run the action more or less frequently+ - cron: '0 0 * * *'++jobs:+ update:+ runs-on: ubuntu-latest+ env:+ SUPABASE_URL: ${{secrets.SUPABASE_URL}}+ SUPABASE_ANON_KEY: ${{secrets.SUPABASE_ANON_KEY}}+ steps:+ - uses: actions/checkout@v2+ with:+ persist-credentials: false+ fetch-depth: 0+ - uses: actions/[email protected]+ with:+ node-version: 14+ - run: npm run update-types+ - name: check for file changes+ id: git_status+ run: |+ echo "::set-output name=status::$(git status -s)"+ - name: Commit files+ if: ${{contains(steps.git_status.outputs.status, ' ')}}+ run: |+ git add types/database/index.ts+ git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"+ git config --local user.name "github-actions[bot]"+ git commit -m "Update database types" -a+ - name: Push changes+ if: ${{contains(steps.git_status.outputs.status, ' ')}}+ uses: ad-m/github-push-action@master+ with:+ github_token: ${{ secrets.GITHUB_TOKEN }}+ branch: ${{ github.ref }}+```++Alternatively, you can use a community-supported GitHub action: [generate-supabase-db-types-github-action](https://github.com/lyqht/generate-supabase-db-types-github-action).++## Resources++- [Generating Supabase types with GitHub Actions](https://blog.esteetey.dev/how-to-create-and-test-a-github-action-that-generates-types-from-supabase-database)diff --git a/apps/temp-docs/docs/guides/apis.mdx b/apps/temp-docs/docs/guides/apis.mdxdeleted file mode 100644index cac8fc84f2c..00000000000--- a/apps/temp-docs/docs/guides/apis.mdx+++ /dev/null@@ -1,192 +0,0 @@-----title: 'APIs'-description: 'Supabase APIs'------# APIs--## Overview--Supabase generates APIs directly from your database schema. The API is:--- Instant and auto-generated: as you update your database the changes are immediately accessible through your API.-- Self documenting: Supabase generates documentation in the Dashboard which updates as you make database changes.-- Secure: the API is configured to work with PostgreSQL's Row Level Security, provisioned behind an API gateway with key-auth enabled.-- Fast: our benchmarks for basic reads are more than 300% faster than Firebase. The API is a very thin layer on top of Postgres, which does most of the heavy lifting.-- Scalable: the API can serve thousands of simultaneous requests, and works well for Serverless workloads.--### RESTful API--Supabase provides a RESTful API using [PostgREST](https://postgrest.org/). This is a very thin API layer on top of Postgres. It provides everything you need from a CRUD API:--- Basic CRUD operations-- Deeply nested joins, allowing you to fetch data from multiple tables in a single fetch-- Works with Postgres Views-- Works with Postgres Functions-- Works with the Postgres security model - including Row Level Security, Roles, and Grants.--<iframe width="560" height="315" src="https://www.youtube.com/embed/rPAJJFdtPw0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>--### Realtime API--Supabase provides a [Realtime](https://github.com/supabase/realtime) API using Realtime. You can use this to listen to database changes over websockets. Realtime leverages PostgreSQL's built-in logical replication. You can manage your Realtime API simply by managing Postgres publications.--## Getting started--After you have added tables or functions to your database, you can use the API.--### Creating API Routes--API routes are automatically created when you create Postgres Tables, Views, or Functions.--Let's create our first API route by creating a table called `todos` (which will store some public user information). This will create a corresponding route `todos` which can accept `GET`, `POST`, `PATCH`, & `DELETE` requests.--<!---TODO: Tabs-Tab name: UI-1. Go to the "Table editor" section.-2. Click "New Table".-3. Enter the table name "todos".-4. Click "Save".-5. Click "New Column".-6. Enter the column name "task" and make the type "text".-7. Click "Save".--Tab name: SQL--- Create a table called "todos" with a column to store tasks.--create table todos (- id bigint generated by default as identity primary key,- task text check (char_length(task) > 3)-);---->---<video width="99%" playsinline controls>- <source src="/docs/videos/api/api-create-table-sm.mp4" type="video/mp4" playsInline />-</video>--### API URL and Keys--Every Supabase project has a unique API URL. Your API is secured behind an API gateway which requires an API Key for every request.--You can find the Keys inside the Dashboard.--<!---Tabs-tab name: UI---->-```-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--**Details and links:**--You are provided with two keys initially:--- an `anon` key, which is safe to be used in a browser context.-- a `service_role` key, which should only be used on a server. This key can bypass Row Level Security.--### Accessing the Docs--Supabase generates documentation in the Dashboard which updates as you make database changes.--Let's view the documentation for the todos table which we created in the first step.--<!---Todo: Tabs-Tab name: UI--->--```-1. Go to the "API" section.-2. Find "todos" in the "Tables and Views" section.-3. Switch between the Javascript and the cURL docs using the tabs.-```--### Using the API--You can interact with your API directly via HTTP requests, or you can use the client libraries which we provide.--Let's see how to make a request to the `todos` table which we created in the first step, using the API URL (`[SUPABASE_URL]`) and Key (`[SUPABASE_ANON_KEY]`) we provided:--<!---TODO: Tabs--Tab name: Javascript--// Initialize the JS client-import { createClient } from '@supabase/supabase-js'-const supabase = createClient([SUPABASE_URL], [SUPABASE_ANON_KEY])--// Make a request-let { data: todos, error } = await supabase- .from('todos')- .select('*')--Tab name: cURL-# Append /rest/v1/ to your URL, and then use the table name as the route-curl '[SUPABASE_URL]/rest/v1/todos' \--H "apikey: [SUPABASE_ANON_KEY]" \--H "Authorization: Bearer SUPABASE_ANON_KEY"---->---**Details and links:**--- When you create a table in Postgres, Row Level Security is disabled by default. Make sure you secure it by [enabling RLS](https://supabase.com/docs/guides/api#securing-your-routes).-- Never expose the service_role key in a browser or anywhere where a user can see it.-- JS Reference: [select()](https://supabase.com/docs/reference/javascript/select), [insert()](https://supabase.com/docs/reference/javascript/insert), [update()](https://supabase.com/docs/reference/javascript/update), [upsert()](https://supabase.com/docs/reference/javascript/upsert), [delete()](https://supabase.com/docs/reference/javascript/delete), [rpc()](https://supabase.com/docs/reference/javascript/rpc) (call Postgres functions).--### Managing Realtime-The Realtime API works through PostgreSQL's replication functionality. Postgres sends database changes to a "publication" called `supabase_realtime`, and by managing this publication you can control which data is broadcast.--By default Realtime is disabled on your database. Let's turn on Realtime for the `todos` table.--<!---TODO: Tabs-Tab name: UI-1. Go to the "Database" section.-2. Click on "Replication" in the sidebar.-3. Control which database events are sent by toggling the Insert/Update/Delete toggles.-4. Control which tables broadcast changes by clicking into the "Source" and toggling the tables.--Tab name: SQL-alter publication supabase_realtime add table products;--->---**Details and links:**--- You should only turn on realtime for Public tables (where all data should be accessible).-- [JS Reference](https://supabase.com/docs/reference/javascript/subscribe): Subscribe to database changes using the realtime client--### Securing your Routes--<!---TODO: Tabs--Tab name: UI-1. Go to the "Authentication" section.-2. Click on "Policies" in the sidebar.-3. Click on the Padlock to enable Row Level Security.--Tab name: SQL-alter table todos enable row level security;->---->--**Details and links:**-- Your API is designed to work with Postgres Row Level Security. If you use Supabase [Auth](https://supabase.com/docs/guides/auth), you can restrict data based on the logged-in user.-- To control access to your data, you can use [Policies](https://supabase.com/docs/guides/auth#policies).----diff --git a/apps/temp-docs/docs/guides/auth.mdx b/apps/temp-docs/docs/guides/auth.mdxindex eb664dfc758..f292dccfa2b 100644--- a/apps/temp-docs/docs/guides/auth.mdx+++ b/apps/temp-docs/docs/guides/auth.mdx@@ -1,61 +1,151 @@----title: 'Auth'-description: 'Supabase auth'+id: auth+title: Auth+description: Use Supabase to Authenticate and Authorize your users.+sidebar_label: Overview----# Auth--<iframe- width="560"- height="315"- src="https://www.youtube.com/embed/6ow_jW4epf8"- title="YouTube video player"- frameborder="0"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowfullscreen-></iframe>--## User Management--Supabase makes it simple to manage your users.--<video width="99%" playsinline controls>- <source src="/docs/videos/auth-zoom2.mp4" type="video/mp4" playsInline />-</video>--When users sign up, Supabase assigns them a unique ID. You can reference this ID anywhere in your database. For example, you might create a '`profiles`' table referencing id in the `auth.users` table using a `user_id` field.--Supabase provides the routes to [sign up](https://supabase.com/docs/reference/javascript/auth-signup), [log in](https://supabase.com/docs/reference/javascript/auth-signin), [log out](https://supabase.com/docs/reference/javascript/auth-signout), and manage users in your apps and websites.--## Third Party Logins--We currently support the following OAuth providers:--<AuthProviders />--You can enable providers by navigating to Authentication > Settings > External OAuth Providers and inputting your `Client ID` and `Secret` for each.--<img src="https://supabase.com/docs/assets/images/supabase-oauth-logins-465421be6d56c5d1bedf19df6786c520.png" />--## Row Level Security+import Link from '@docusaurus/Link'+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import providers from '@site/src/data/authProviders'+import ButtonCard from '@site/src/components/ButtonCard'+import useBaseUrl from '@docusaurus/useBaseUrl'++## Overview++There are two parts to every Auth system:++- **Authentication:** should this person be allowed in? If yes, who are they?+- **Authorization:** once they are in, what are they allowed to do?++Supabase Auth is designed to work either as a standalone product, or deeply integrated with the other Supabase products.+Postgres is at the heart of everything we do, and the Auth system follows this principle. We leverage Postgres' built-in Auth functionality wherever possible.++Here's a quick, 2 minute tour of the Auth features built-in to Supabase:++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/6ow_jW4epf8"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Authentication++You can authenticate your users in several ways:++- Email & password.+- Magic links (one-click logins).+- Social providers.+- Phone logins.++### Providers++We provide a suite of Providers and login methods, as well as [Auth helpers](/docs/guides/auth/auth-helpers/).++<div class="container" style={{ padding: 0 }}>+ <div class="row is-multiline">+ {providers.map((x) => (+ <div key={x.name} class="col col--6">+ <ButtonCard+ class="card"+ to={useBaseUrl(x.href)}+ title={x.name}+ style={{ height: '100%' }}+ >+ <div class="button-card__inner">+ <div+ class=""+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ gap: 10,+ }}+ >+ {x.logo && <img src={x.logo} alt={x.name} width="20" />}+ <p>{x.name}</p>+ <p>+ {x.official ? (+ <span class={`badge badge--official`}>Official</span>+ ) : (+ <span class={`badge badge--unofficial`}>Unofficial</span>+ )}+ </p>+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>+ <div+ class="code-block"+ style={{+ width: '100%',+ display: 'flex',+ justifyContent: 'space-between',+ fontSize: '0.7rem',+ }}+ >+ <span>Platform:</span>+ <span>{x.platform.toString()}</span>+ </div>+ <div+ class="code-block"+ style={{+ width: '100%',+ display: 'flex',+ justifyContent: 'space-between',+ fontSize: '0.7rem',+ }}+ >+ <span>Self-Hosted:</span>+ <span>{x.selfHosted.toString()}</span>+ </div>+ </div>+ </div>+ </ButtonCard>+ </div>+ ))}+ </div>+</div>++### Configure third-party providers++You can enable third-party providers with the click of a button by navigating to Authentication > Settings > Auth Providers and inputting your `Client ID` and `Secret` for each.++++## Authorization++When you need granular authorization rules, nothing beats PostgreSQL's Row Level Security (RLS).++Policies are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.++Get started with our [Row Level Security Guides](/docs/guides/auth/row-level-security).++### Row Level SecurityAuthentication only gets you so far. When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). Supabase makes it simple to turn RLS on and off.-<video width="99%" playsinline controls>- <source src="/docs/videos/rls-zoom2.mp4" type="video/mp4" playsInline />+<video width="99%" muted playsInline controls="true">+ <source src="/docs/videos/rls-zoom2.mp4" type="video/mp4" muted playsInline /></video>-## Policies+### Policies[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.-<video width="99%" playsinline controls>- <source src="/docs/videos/policies-zoom2.mp4" type="video/mp4" playsInline />+<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/policies-zoom2.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-With policies, your database becomes the rules engine. Instead of repetitively filtering your queries, like this...+With policies, your database becomes the rules engine. Instead of repetitively filtering your queries, like this ...-```Javascript+```jsconst loggedInUserId = 'd0714948'let { data, error } = await supabase.from('users')@@ -68,14 +158,14 @@ let { data, error } = await supabase... you can simply define a rule on your database table, `auth.uid() = user_id`, and your request will return the rows which pass the rule, even when you remove the filter from your middleware:-```Javascript-let user = await supabase.from('users').select('user_id, name')+```js+let { data, error } = await supabase.from('users').select('user_id, name')// console.log(data)// Still => { id: 'd0714948', name: 'Jane' }```-## How It Works+### How It Works1. A user signs up. Supabase creates a new user in the `auth.users` table.2. Supabase returns a new JWT, which contains the user's `UUID`.@@ -85,34 +175,22 @@ let user = await supabase.from('users').select('user_id, name')Supabase provides a special function in Postgres, `auth.uid()`, which extracts the user's UID from the JWT. This is especially useful when creating policies.-## Tips--**Enable Realtime for database tables**--Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies. We recommend that you enable row level security and set row security policies on tables that you add to the publication. However, you may choose to disable RLS on a table and have changes broadcast to all connected clients.--```sql-/**- * REALTIME SUBSCRIPTIONS- * Realtime enables listening to any table in your public schema.- */--begin;- -- remove the realtime publication- drop publication if exists supabase_realtime;-- -- re-create the publication but don't enable it for any tables- create publication supabase_realtime;-commit;---- add a table to the publication-alter publication supabase_realtime add table products;---- add other tables to the publication-alter publication supabase_realtime add table posts;-```--## Next Steps+## User Management-- Read more about Auth in the [Guides](https://supabase.com/docs/guides/auth/intro).-- Sign in: [app.supabase.com](https://app.supabase.com/)+Supabase provides multiple endpoints to authenticate and manage your users:+- [Sign up](/docs/reference/javascript/auth-signup)+- [Sign in with password](/docs/reference/javascript/auth-signinwithpassword)+- [Sign in with passwordless / one-time password (OTP)](/docs/reference/javascript/auth-signinwithotp)+- [Sign in with OAuth](/docs/reference/javascript/auth-signinwithoauth)+- [Sign out](/docs/reference/javascript/auth-signout)++When users sign up, Supabase assigns them a unique ID. You can reference this ID anywhere in your database. For example, you might create a `profiles` table referencing `id` in the `auth.users` table using a `user_id` field.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/auth-zoom2.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>diff --git a/apps/temp-docs/docs/guides/auth/auth-apple.mdx b/apps/temp-docs/docs/guides/auth/auth-apple.mdxindex 9f83c19fe0c..524212403b3 100644--- a/apps/temp-docs/docs/guides/auth/auth-apple.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-apple.mdx@@ -5,7 +5,7 @@ description: Add Apple OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Apple Auth for your project, you need to set up an Apple OAuth application and add the application credentials to your Supabase Dashboard.@@ -17,19 +17,17 @@ Apple OAuth consists of six broad steps:- Obtaining a `Services Id` - this will serve as the `client_id`.- Obtaining a `secret key` that will be used to get our `client_secret`.- Generating the `client_secret` using the `secret key`.-- Add your `client id` and `client secret` keys to your [Supabase Project](https://supabase.com).+- Add your `client id` and `client secret` keys to your [Supabase Project](https://app.supabase.com).- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js).-## Steps--### Access your Apple Developer account+## Access your Apple Developer account- Go to [developer.apple.com](https://developer.apple.com).- Click on `Account` at the top right to log in.-+-### Obtain an App ID+## Obtain an App ID- Go to `Certificates, Identifiers & Profiles`.- Click on `Identifiers` at the left.@@ -43,7 +41,7 @@ Apple OAuth consists of six broad steps:- Click `Continue` at the top right.- Click `Register` at the top right.-### Obtain a Services ID+## Obtain a Services IDThis will serve as the `client_id` when you make API calls to authenticate the user.@@ -58,23 +56,28 @@ This will serve as the `client_id` when you make API calls to authenticate the u- Click `Continue` at the top right.- Click `Register` at the top right.-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Configure your Services ID+## Configure your Services ID- Under `Identifiers`, click on your newly-created Services ID.- Check the box next to `Sign In With Apple` to enable it.@@ -86,7 +89,7 @@ The next step requires a callback URL, which looks like this:- Click `Continue` at the top right.- Click `Save` at the top right.-### Download your secret key+## Download your secret keyNow you'll need to download a `secret key` file from Apple that will be used to generate your `client_secret`.@@ -104,7 +107,7 @@ Now you'll need to download a `secret key` file from Apple that will be used to- Save the downloaded file -- this contains your "secret key" that will be used to generate your `client_secret`.- Click `Done` at the top right.-### Generate a `client_secret`+## Generate a `client_secret`The `secret key` you downloaded is used to create the `client_secret` string you'll need to authenticate your users.@@ -168,9 +171,9 @@ puts token2. From the command line, run: `ruby secret_gen.rb > client_secret.txt`.3. Your `client_secret` is now stored in this `client_secret.txt` file.-### Add your OAuth credentials to Supabase+## Add your OAuth credentials to Supabase-- Go to your [Supabase Dashboard](https://supabase.com).+- Go to your [Supabase Dashboard](https://app.supabase.com).- In the left sidebar, click the `Authentication` icon (near the top).- Click `Settings` from the list to go to the `Authentication Settings` page.- Enter the final (hosted) URL of your app under `Site URL` (this is important).@@ -178,27 +181,19 @@ puts token- Enter your `client_id` and `client_secret` saved in the previous steps.- Click `Save`.-### Add login code to your client app--The JavaScript client code is documented in the [Supabase OAuth Reference](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers).--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'apple',-})-```+## Add login code to your client app-Add a function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `apple` as the `provider`:```jsasync function signInWithApple() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'apple',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-azure.mdx b/apps/temp-docs/docs/guides/auth/auth-azure.mdxnew file mode 100644index 00000000000..6475d9d8470--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-azure.mdx@@ -0,0 +1,98 @@+---+id: auth-azure+title: 'Login with Azure'+description: Add Azure OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable Azure Auth for your project, you need to set up an Azure OAuth application and add the application credentials to your Supabase Dashboard.++## Overview++Azure OAuth consists of four broad steps:++- Create an application under Azure Active Directory.+- Obtain a `Application (client) ID` with “Sign In with Azure” capabilities. This will be used as the `client id`.+- Create a `Secret ID` with “Sign In with Azure” capabilities. The value of the secret will be used as the `client secret`.+- Add the callback url of your application to the allowlist.++## Access your Azure Developer account++- Go to [portal.azure.com](https://portal.azure.com/#home).+- Login and select "Azure Active Directory" under the list of Azure Services.++## Register an application++- Under Azure Active Directory, select "App registrations" in the side panel.+- Select "New registration".+- Choose a name and select your preferred option for the supported account types.+- Specify the "Redirect URI".+- The redirect / callback URI should look like this: `https://<project-ref>.supabase.co/auth/v1/callback`+- Click "Register" at the bottom of the form.++++## Obtain a Client ID++This will serve as the `client_id` when you make API calls to authenticate the user.++- Once your app has been registered, the client id can be found under the [list of app registrations](https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps) under the column titled "Application (client) ID".++++## Obtain a Secret ID++This will serve as the `client_secret` when you make API calls to authenticate the user.++- Click on the name of the app registered above.+- Under "Essentials", click on "Client credentials".+- Navigate to the "Client secrets" tab and select "New client secret".+- Enter a description and choose your preferred expiry for the secret.+- Once the secret is generated, save the `value` (not the secret ID).++++## Obtain the Tenant URL++This will allow your users to use your custom Azure login page when logging in.++- Select the Directory (Tenant) ID value.+- The Azure Tenant URL should look like this: `https://login.microsoftonline.com/<tenant-id>`++++## Add login code to your client app++:::tip+Supabase Auth requires that Azure returns a valid email address. Therefore you must request the `email` scope in the `signIn` method above.+:::++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `azure` as the `provider`:++```js+async function signInWithAzure() {+ const { data, error } = await supabase.auth.signInWithOAuth(+ {+ provider: 'azure',+ },+ {+ scopes: 'email',+ }+ )+}+```++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- [Azure Developer Account](https://portal.azure.com)+- [GitHub Discussion](https://github.com/supabase/gotrue/pull/54#issuecomment-757043573)diff --git a/apps/temp-docs/docs/guides/auth/auth-bitbucket.mdx b/apps/temp-docs/docs/guides/auth/auth-bitbucket.mdxindex def7bf4cb22..d7e279cd3c3 100644--- a/apps/temp-docs/docs/guides/auth/auth-bitbucket.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-bitbucket.mdx@@ -5,7 +5,7 @@ description: Add Bitbucket OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Bitbucket Auth for your project, you need to set up a BitBucket OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,35 +14,38 @@ To enable Bitbucket Auth for your project, you need to set up a BitBucket OAuthSetting up Bitbucket logins for your application consists of 3 parts:- Create and configure a Bitbucket OAuth Consumer on [Bitbucket](https://bitbucket.org)-- Add your Bitbucket OAuth Consumer keys to your [Supabase Project](https://supabase.com)+- Add your Bitbucket OAuth Consumer keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your Bitbucket account+## Access your Bitbucket account- Go to [bitbucket.org](https://bitbucket.org/).- Click on `Login` at the top right to log in.-+-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Bitbucket OAuth app+## Create a Bitbucket OAuth app- Click on your profile icon at the bottom left- Click on `All Workspaces`@@ -57,9 +60,9 @@ The next step requires a callback URL, which looks like this:- Click on your app name (the name of your new OAuth Consumer)- Copy your `Key` (`client_key`) and `Secret` (`client_secret`) codes-### Add your Bitbucket credentials into your Supabase Project+## Add your Bitbucket credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -67,27 +70,19 @@ The next step requires a callback URL, which looks like this:- Enter your `client_id` and `client_secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'bitbucket',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `bitbucket` as the `provider`:```jsasync function signInWithBitbucket() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'bitbucket',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-captcha.mdx b/apps/temp-docs/docs/guides/auth/auth-captcha.mdxnew file mode 100644index 00000000000..65837976a17--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-captcha.mdx@@ -0,0 +1,113 @@+---+id: auth-captcha+title: 'Enable Captcha Protection'+description: Add Captcha Protection to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++# hCaptcha guide++Supabase provides you with the option of adding captcha to your sign-in, sign-up, and password reset forms. This keeps your website safe from bots and malicious scripts. Supabase authentication has support for [hCaptcha](https://www.hcaptcha.com/).++### Sign up for hCaptcha++Go to the [hCaptcha](https://www.hcaptcha.com/) website and sign up for an account. On the welcome page, copy the **Sitekey** and **Secret key**.++If you have already signed up and didn't copy this information from the welcome page, you can get the **Secret key** from the settings page.++++The **Sitekey** can be found in the **Settings** of the active site you created.++++In the Settings page, look for the **Sitekey** section and copy the key.++++### Enable hCaptcha protection for your Supabase project++Navigate to the **[Authentication](https://app.supabase.com/project/_/auth/settings)** page in the Supabase Dashboard and find the **Enable hCaptcha protection** toggle under the **Security and Protection** section.++++Enter your hCaptcha **Secret key** and click **Save**.++### Add the hCaptcha frontend component++The frontend requires some changes to provide the captcha on-screen for the user. This example uses React and the hCaptcha React component, but hCaptcha can be used with any JavaScript framework.++Install `@hcaptcha/react-hcaptcha` in your project as a dependency.++```bash+npm install @hcaptcha/react-hcaptcha+```++Now import the `HCaptcha` component from the `@hcaptcha/react-hcaptcha` library.++```javascript+import HCaptcha from '@hcaptcha/react-hcaptcha'+```++Let’s create a empty state to store our `captchaToken`++```jsx+const [captchaToken, setCaptchaToken] = useState()+```++Now lets add the HCaptcha component to the JSX section of our code++```html+<HCaptcha />+```++We will pass it the sitekey we copied from the hCaptcha website as a property along with a onVerify property which takes a callback function. This callback function will have a token as one of its properties. Let's set the token in the state using `setCaptchaToken`++```jsx+<HCaptcha+ sitekey="your-sitekey"+ onVerify={(token) => { setCaptchaToken(token) }+/>+```++Now lets use the captcha token we receive in our Supabase signUp function.++```jsx+await supabase.auth.signUp({+ email,+ password,+ options: { captchaToken },+})+```++We will also need to reset the captcha challenge after we have made a call to the function above.++Create a ref to use on our HCaptcha component.++```jsx+const captcha = useRef()+```++Let's add a ref attribute on the `HCaptcha` component and assign the `captcha` constant to it.++```jsx+<HCaptcha+ ref={captcha}+ sitekey="your-sitekey"+ onVerify={(token) => {+ setCaptchaToken(token)+ }}+/>+```++Reset the `captcha` after the signUp function is called using the following code:++```jsx+captcha.current.resetCaptcha()+```++In order to test that this works locally we will need to use something like [ngrok](https://ngrok.com/) or add an entry to your hosts file. You can read more about this in the [hCaptcha docs](https://docs.hcaptcha.com/#local-development).++Run the application and you should now be provided with a captcha challenge.diff --git a/apps/temp-docs/docs/guides/auth/auth-discord.mdx b/apps/temp-docs/docs/guides/auth/auth-discord.mdxindex 45d22b63e9a..11193ec9c8a 100644--- a/apps/temp-docs/docs/guides/auth/auth-discord.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-discord.mdx@@ -5,7 +5,7 @@ description: Add Discord OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Discord Auth for your project, you need to set up a Discord Application and add the Application OAuth credentials to your Supabase Dashboard.@@ -14,39 +14,42 @@ To enable Discord Auth for your project, you need to set up a Discord ApplicatioSetting up Discord logins for your application consists of 3 parts:- Create and configure a Discord Application [Discord Developer Portal](https://discord.com/developers)-- Add your Discord OAuth Consumer keys to your [Supabase Project](https://supabase.com)+- Add your Discord OAuth Consumer keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your Discord account+## Access your Discord account- Go to [discord.com](https://discord.com/).- Click on `Login` at the top right to log in.-+- Once logged in, go to [discord.com/developers](https://discord.com/developers).-+-### Find your callback URL+## Find your callback URLIn the next step you require a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Discord Application+## Create a Discord Application- Click on `New Application` at the top right.- Enter the name of your application and click `Create`.@@ -56,9 +59,9 @@ In the next step you require a callback URL, which looks like this:- Click `Save Changes` at the bottom.- Copy your `Client ID` and `Client Secret` under `Client information`.-### Add your Discord credentials into your Supabase Project+## Add your Discord credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -66,27 +69,21 @@ In the next step you require a callback URL, which looks like this:- Enter your `client_id` and `client_secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'discord',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `discord` as the `provider`:```jsasync function signInWithDiscord() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'discord',})}```-To log out:+If your user is already signed in, Discord prompts the user again for authorization.++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-email.mdx b/apps/temp-docs/docs/guides/auth/auth-email.mdxindex 5f8fcc24526..c4c24a828a6 100644--- a/apps/temp-docs/docs/guides/auth/auth-email.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-email.mdx@@ -5,106 +5,77 @@ description: Use Supabase to Authenticate and Authorize your users using email.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'## OverviewSetting up Email logins for your Supabase application.- Add Email authenticator to your [Supabase Project](https://app.supabase.com)-- Add the login code to your application - [Javascript](https://github.com/supabase/supabase-js) | [Dart](https://github.com/supabase/supabase-dart)+- Add the login code to your application - [JavaScript](https://github.com/supabase/supabase-js) | [Flutter](https://github.com/supabase/supabase-flutter)-## Add Email into your Supabase Project+## Configure email settings-- Go to your [Supabase Project Dashboard](https://app.supabase.com)-- In the left sidebar, click the `Authentication` icon (near the top)-- Click `Settings` from the list to go to the `Authentication Settings` page-- Enter the final (hosted) URL of your app under `Site URL` (this is important)-- Under `Email Auth` turn `Enable Email Signup` to ON-- Click `Save`+1. Go to the [Authentication Settings](https://app.supabase.com/project/_/auth/settings) page in the Dashboard.+1. For **Site URL**, enter the final (hosted) URL of your app.+1. Under Auth Providers, **enable email provider**.-### Add login code to your client app+:::note Self hosting-The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)+For self-hosting, you can update your project configuration using the files and environment variables provided.+See the [self-hosting docs](/docs/guides/hosting/overview#configuration) for details.-<Tabs- defaultActiveId="js"- groupId="guides/auth"- values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}->--<TabsPanel id="js" label="js">--```js-const { user, error } = await supabase.auth.signIn({- email: '[email protected]',- password: 'example-password',-})-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-final res = await supabase.auth.signIn(- email: '[email protected]',- password: 'example-password'-);--final user = res.data?.user;-final error = res.error;-```--</TabsPanel>--</Tabs>+:::-Add this function which you can call from a button, link, or UI element.+## Add login code to your client app<Tabs- defaultActiveId="js"+ defaultValue="js"groupId="guides/auth"values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}>-<TabsPanel id="js" label="js">+<TabItem value="js">++When your user signs in, call [signInWithPassword()](/docs/reference/javascript/auth-signinwithpassword) with their email address and password:```jsasync function signInWithEmail() {- const { user, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithPassword({email: '[email protected]',password: 'example-password',})}```-</TabsPanel>+</TabItem>++<TabItem value="dart">-<TabsPanel id="dart" label="dart">+When your user signs in, call [signInWithPassword()](/docs/reference/dart/auth-signinwithpassword) with their email address and password:```dart-function SignInWithEmail() {- await supabase.auth.signIn(+Future<void> signInWithEmail() async {+ final AuthResponse res = await supabase.auth.signInWithPassword(email: '[email protected]',password: 'example-password');}```-</TabsPanel>+</TabItem></Tabs>-To log out:-<Tabs- defaultActiveId="js"+ defaultValue="js"groupId="guides/auth"values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}>-<TabsPanel id="js" label="js">+<TabItem value="js">++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signOut() {@@ -112,17 +83,19 @@ async function signOut() {}```-</TabsPanel>+</TabItem>++<TabItem value="dart">-<TabsPanel id="dart" label="dart">+When your user signs out, call [signOut()](/docs/reference/dart/auth-signout) to remove them from the browser session and any objects from localStorage:```dart-function SignOut() {- await supabase.auth.signOut();+Future<void> signOut() async {+ await supabase.auth.signOut();}```-</TabsPanel>+</TabItem></Tabs>@@ -130,4 +103,4 @@ function SignOut() {- [Supabase Account - Free Tier OK](https://supabase.com)- [Supabase JS Client](https://github.com/supabase/supabase-js)-- [Supabase Dart Client](https://github.com/supabase/supabase-dart)+- [Supabase Flutter Client](https://github.com/supabase/supabase-flutter)diff --git a/apps/temp-docs/docs/guides/auth/auth-facebook.mdx b/apps/temp-docs/docs/guides/auth/auth-facebook.mdxindex 07e46c04301..3cb6ac68947 100644--- a/apps/temp-docs/docs/guides/auth/auth-facebook.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-facebook.mdx@@ -5,7 +5,7 @@ description: Add Facebook OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Facebook Auth for your project, you need to set up a Facebook OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,19 +14,17 @@ To enable Facebook Auth for your project, you need to set up a Facebook OAuth apSetting up Facebook logins for your application consists of 3 parts:- Create and configure a Facebook Application on the [Facebook Developers Site](https://developers.facebook.com)-- Add your Facebook keys to your [Supabase Project](https://supabase.com)+- Add your Facebook keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your Facebook Developer account+## Access your Facebook Developer account- Go to [developers.facebook.com](https://developers.facebook.com).- Click on `Log In` at the top right to log in.-+-### Create a Facebook App+## Create a Facebook App- Click on `My Apps` at the top right.- Click `Create App` near the top right.@@ -34,23 +32,28 @@ Setting up Facebook logins for your application consists of 3 parts:- Fill in your app information, then click `Create App`.- This should bring you to the screen: `Add Products to Your App`. (Alternatively you can click on `Add Product` in the left sidebar to get to this screen.)-### Find your callback URI+## Find your callback URIThe next step requires a callback URI, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Set up FaceBook Login for your Facebook App+## Set up FaceBook Login for your Facebook AppFrom the `Add Products to your App` screen:@@ -67,16 +70,16 @@ From the `App Review -> Permissions and Features` screen:You can read more about access levels [here](https://developers.facebook.com/docs/graph-api/overview/access-levels/)-### Copy your Facebook App ID and Secret+## Copy your Facebook App ID and Secret- Click `Settings / Basic` in the left sidebar- Copy your App ID from the top of the `Basic Settings` page- Under `App Secret` click `Show` then copy your secret- Make sure all required fields are completed on this screen.-### Enter your Facebook App ID and Secret into your Supabase Project+## Enter your Facebook App ID and Secret into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -84,27 +87,19 @@ You can read more about access levels [here](https://developers.facebook.com/doc- Enter your `Facebook client ID` and `Facebook secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'facebook',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `facebook` as the `provider`:```jsasync function signInWithFacebook() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'facebook',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-github.mdx b/apps/temp-docs/docs/guides/auth/auth-github.mdxindex 12e0d207806..471d37935b1 100644--- a/apps/temp-docs/docs/guides/auth/auth-github.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-github.mdx@@ -5,7 +5,7 @@ description: Add GitHub OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable GitHub Auth for your project, you need to set up a GitHub OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,19 +14,17 @@ To enable GitHub Auth for your project, you need to set up a GitHub OAuth applicSetting up GitHub logins for your application consists of 3 parts:- Create and configure a GitHub OAuth App on [GitHub](https://github.com)-- Add your GitHub OAuth keys to your [Supabase Project](https://supabase.com)+- Add your GitHub OAuth keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your GitHub account+## Access your GitHub account- Go to [github.com](https://github.com).- Click on `Sign In` at the top right to log in.-+-### Create a GitHub Oauth App+## Create a GitHub Oauth AppGo to the [GitHub Developer Settings](https://github.com/settings/developers) page:@@ -35,23 +33,28 @@ Go to the [GitHub Developer Settings](https://github.com/settings/developers) pa- In the left sidebar, click `Developer settings` (near the bottom)- In the left sidebar, click `OAuth Apps`-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Register a new OAuth application+## Register a new OAuth application- Click `Register a new application`. If you've created an app before, click `New OAuth App` here.- In `Application name`, type the name of your app.@@ -67,9 +70,9 @@ Copy your new OAuth credentials- Click `Generate a new client secret`.- Copy and save your `Client secret`.-### Enter your GitHub credentials into your Supabase Project+## Enter your GitHub credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -77,27 +80,19 @@ Copy your new OAuth credentials- Enter your `GitHub Client ID` and `GitHub Client Secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'github',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `github` as the `provider`:```js-async function signInWithGithub() {- const { user, session, error } = await supabase.auth.signIn({+async function signInWithGitHub() {+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'github',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-gitlab.mdx b/apps/temp-docs/docs/guides/auth/auth-gitlab.mdxindex 71718e6b031..9f5bfd29360 100644--- a/apps/temp-docs/docs/guides/auth/auth-gitlab.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-gitlab.mdx@@ -5,7 +5,7 @@ description: Add GitLab OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable GitLab Auth for your project, you need to set up a GitLab OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,35 +14,38 @@ To enable GitLab Auth for your project, you need to set up a GitLab OAuth applicSetting up GitLab logins for your application consists of 3 parts:- Create and configure a GitLab Application on [GitLab](https://gitlab.com)-- Add your GitLab Application keys to your [Supabase Project](https://supabase.com)+- Add your GitLab Application keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your GitLab account+## Access your GitLab account- Go to [gitlab.com](https://gitlab.com).- Click on `Login` at the top right to log in.-+-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create your GitLab Application+## Create your GitLab Application- Click on your `profile logo` (avatar) in the top-right corner.- Select `Edit profile`.@@ -54,9 +57,9 @@ The next step requires a callback URL, which looks like this:- Click `Save Application` at the bottom.- Copy and save your `Application ID` (`client_id`) and `Secret` (`client_secret`) which you'll need later.-### Add your GitLab credentials into your Supabase Project+## Add your GitLab credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- In the left sidebar, click the `Authentication` icon (near the top).- Click `Settings` from the list to go to the `Authentication Settings` page.- Enter the final (hosted) URL of your app under `Site URL` (this is important).@@ -64,27 +67,19 @@ The next step requires a callback URL, which looks like this:- Enter your `client_id` and `client_secret` saved in the previous step.- Click `Save`.-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'gitlab',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `gitlab` as the `provider`:```jsasync function signInWithGitLab() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'gitlab',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-google.mdx b/apps/temp-docs/docs/guides/auth/auth-google.mdxindex 4e55dc324b6..051ce6cab03 100644--- a/apps/temp-docs/docs/guides/auth/auth-google.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-google.mdx@@ -5,7 +5,7 @@ description: Add Google OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Google Auth for your project, you need to set up a Google OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,19 +14,17 @@ To enable Google Auth for your project, you need to set up a Google OAuth applicSetting up Google logins for your application consists of 3 parts:- Create and configure a Google Project on the [Google Cloud Platform Console](https://console.cloud.google.com/home/dashboard)-- Add your Google OAuth keys to your [Supabase Project](https://supabase.com)+- Add your Google OAuth keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your Google Cloud Platform account+## Access your Google Cloud Platform account- Go to [cloud.google.com](https://cloud.google.com).- Click on `Sign in` at the top right to log in.-+-### Create a Google Cloud Platform Project+## Create a Google Cloud Platform Project- Click on `Select a Project` at the top left.- (Or, if a project is currently selected, click on the current project name at the top left.)@@ -35,7 +33,7 @@ Setting up Google logins for your application consists of 3 parts:- (This can take a few minutes.)- This should bring you to the dashboard for your new project.-### Create the OAuth Keys for your project+## Create the OAuth Keys for your projectFrom your project's dashboard screen:@@ -44,30 +42,35 @@ From your project's dashboard screen:- On the `OAuth consent screen` page select `External`.- Click `Create`.-### Edit your app information+## Edit your app information- On the `Edit app registration` page fill out your app information.- Click `Save and continue` at the bottom.-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create your credentials+## Create your Google credentials-- Click `Credentials` at the left to go to the `Credentials` page+- Click `Credentials` at the left to go to the `Credentials` page on the Google Cloud Platform console.- Click `Create Credentials` near the top then select `OAuth client ID`- On the `Create OAuth client ID` page, select your application type. If you're not sure, choose `Web application`.- Fill in your app name.@@ -82,9 +85,9 @@ Copy your new OAuth credentials- A box will appear called `OAuth client created`.- Copy and save the values under `Your Client ID` and `Your Client Secret`.-### Enter your Google credentials into your Supabase Project+## Enter your Google credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -92,27 +95,19 @@ Copy your new OAuth credentials- Enter your `Google Client ID` and `Google Client Secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'google',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `google` as the `provider`:```jsasync function signInWithGoogle() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'google',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-helpers/auth-ui.mdx b/apps/temp-docs/docs/guides/auth/auth-helpers/auth-ui.mdxnew file mode 100644index 00000000000..0ee2493a61e--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-helpers/auth-ui.mdx@@ -0,0 +1,297 @@+---+id: auth-ui+title: Auth UI+description: A prebuilt, customizable React component for authenticating users.+---++Auth UI is a pre-built React component for authenticating users.+It supports custom themes and extensible styles to match your brand and aesthetic.++<video width="99%" muted playsInline controls="true">+ <source+ src="https://supabase.com/images/blog/lw5-one-more/auth-ui-demo.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Set up Auth UI++Install the latest version of [supabase-js](/docs/reference/javascript) and the Auth UI package:++```bash+npm install @supabase/supabase-js @supabase/auth-ui-react+```++### Import the Auth component++Pass `supabaseClient` from `@supabase/supabase-js` as a prop to the component.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => <Auth supabaseClient={supabase} />+```++This renders the Auth component without any styling.+We recommend using one of the predefined themes to style the UI.+Import the theme you want to use and pass it to the `appearence.theme` prop.++```diff js title="/src/index.js"+import {+ Auth,+ // highlight-next-line+ ThemeSupa+} from '@supabase/auth-ui-react'++const App = () => (+ <Auth+ supabaseClient={supabase}+ // highlight-next-line+ appearance={{ theme: ThemeSupa }}+ />+)+```++## Customization++There are several ways to customize Auth UI:++- Use one of the [predefined themes](#predefined-themes) that comes with Auth UI+- Extend a theme by [overriding the variable tokens](#override-themes) in a theme+- [Create your own theme](#create-theme)+- [Use your own CSS classes](#custom-css-classes)+- [Use inline styles](#custom-inline-styles)+- [Use your own labels](#custom-labels)++### Predefined themes++Auth UI comes with several themes to customize the appearance. Each predefined theme comes with at least two variations, a `default` variation, and a `dark` variation. You can switch between these themes using the `theme` prop. Import the theme you want to use and pass it to the `appearence.theme` prop.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+//highlight-next-line+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ // highlight-next-line+ appearance={{ theme: ThemeSupa }}+ />+)+```++:::info+Currently there is only one predefined theme available, but we plan to add more.+:::++### Switch theme variations++Auth UI comes with two theme variations: `default` and `dark`. You can switch between these themes with the `theme` prop.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ appearance={{ theme: ThemeSupa }}+ // highlight-next-line+ theme="dark"+ />+)+```++If you don't pass a value to `theme` it uses the `"default"` theme. You can pass `"dark"` to the theme prop to switch to the `dark` theme. If your theme has other variations, use the name of the variation in this prop.++### Override themes++Auth UI themes can be overridden using variable tokens. See the [list of variable tokens](https://github.com/supabase-community/auth-ui/blob/main/packages/react/common/theming/Themes.tsx).++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ appearance={{+ theme: ThemeSupa,+ // highlight-start+ variables: {+ default: {+ colors: {+ brand: 'red',+ brandAccent: 'darkred',+ },+ },+ },+ // highlight-end+ }}+ />+)+```++If you created your own theme, you may not need to override any of the them.++### Create your own theme {#create-theme}++You can create your own theme by following the same structure within a `appearance.theme` property.+See the list of [tokens within a theme](https://github.com/supabase-community/auth-ui/blob/main/packages/react/common/theming/Themes.tsx).++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const customTheme = {+ default: {+ colors: {+ brand: 'hsl(153 60.0% 53.0%)',+ brandAccent: 'hsl(154 54.8% 45.1%)',+ brandButtonText: 'white',+ // ..+ },+ dark: {+ colors: {+ brandButtonText: 'white',+ defaultButtonBackground: '#2e2e2e',+ defaultButtonBackgroundHover: '#3e3e3e',+ //..+ },+ },+ // You can also add more theme variations with different names.+ evenDarker: {+ colors: {+ brandButtonText: 'white',+ defaultButtonBackground: '#1e1e1e',+ defaultButtonBackgroundHover: '#2e2e2e',+ //..+ },+ },+}++const App = () => (+ <Auth+ supabaseClient={supabase}+ theme="default" // can also be "dark" or "evenDarker"+ appearance={{ theme: customTheme}}+ />+)+```++You can swich between different variations of your theme with the ["theme" prop](#switch-theme-variations).++### Custom CSS classes {#custom-css-classes}++You can use custom CSS classes for the following elements:+`"button"`, `"container"`, `"anchor"`, `"divider"`, `"label"`, `"input"`, `"loader"`, `"message"`.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ appearance={{+ className: {+ anchor: 'my-awesome-anchor',+ button: 'my-awesome-button',+ //..+ },+ }}+ />+)+```++### Custom inline CSS {#custom-inline-styles}++You can use custom CSS inline styles for the following elements:+`"button"`, `"container"`, `"anchor"`, `"divider"`, `"label"`, `"input"`, `"loader"`, `"message"`.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ appearance={{+ style: {+ button: { background: 'red', color: 'white' },+ anchor: { color: 'blue' },+ //..+ },+ }}+ />+)+```++### Custom labels {#custom-labels}++You can use custom labels with `localization.variables`. See the [list of labels](https://github.com/supabase-community/auth-ui/blob/main/packages/react/common/lib/Localization/en.json) that can be overwritten.++```js title="/src/index.js"+import { createClient } from '@supabase/supabase-js'+import { Auth } from '@supabase/auth-ui-react'++const supabase = createClient(+ '<INSERT PROJECT URL>',+ '<INSERT PROJECT ANON API KEY>'+)++const App = () => (+ <Auth+ supabaseClient={supabase}+ //highlight-start+ localization={{+ variables: {+ sign_in: {+ email_label: 'Your email address',+ password_label: 'Your strong password',+ },+ },+ }}+ //highlight-end+ />+)+```diff --git a/apps/temp-docs/docs/guides/auth/auth-helpers/index.mdx b/apps/temp-docs/docs/guides/auth/auth-helpers/index.mdxnew file mode 100644index 00000000000..bcb52c6a759--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-helpers/index.mdx@@ -0,0 +1,59 @@+---+id: index+title: Auth Helpers+description: A collection of framework-specific Auth utilities for working with Supabase.+sidebar_label: Overview+---++import useBaseUrl from '@docusaurus/useBaseUrl'+import ButtonCard from '@site/src/components/ButtonCard'++A collection of framework-specific Auth utilities for working with Supabase.++<div class="container" style={{ padding: 0 }}>+ <div class="row is-multiline">+ {/* Auth UI */}+ <div class="col col--4">+ <ButtonCard+ class="card"+ to={useBaseUrl('/guides/auth/auth-helpers/auth-ui')}+ title={'Auth UI'}+ description={'A pre-built React component for authenticating users.'}+ style={{ height: '100%' }}+ />+ </div>+ {/* Next.js */}+ <div class="col col--4">+ <ButtonCard+ class="card"+ to={useBaseUrl('/guides/auth/auth-helpers/nextjs')}+ title={'Next.js'}+ description={+ 'Helpers for authenticating users in Next.js applications.'+ }+ style={{ height: '100%' }}+ />+ </div>+ {/* SvelteKit */}+ <div class="col col--4">+ <ButtonCard+ class="card"+ to={useBaseUrl('/guides/auth/auth-helpers/sveltekit')}+ title={'SvelteKit'}+ description={+ 'Helpers for authenticating users in SvelteKit applications.'+ }+ style={{ height: '100%' }}+ />+ </div>+ </div>+</div>++## Status++The Auth Helpers are in `beta`. They are usable in their current state, but it's likely that there will be breaking changes.++## Additional Links++- [Source code](https://github.com/supabase/auth-helpers)+- [Known bugs and issues](https://github.com/supabase/auth-helpers/issues)diff --git a/apps/temp-docs/docs/guides/auth/auth-helpers/nextjs.mdx b/apps/temp-docs/docs/guides/auth/auth-helpers/nextjs.mdxnew file mode 100644index 00000000000..b69b42d8936--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-helpers/nextjs.mdx@@ -0,0 +1,464 @@+---+id: nextjs+title: Supabase Auth with Next.js+description: Authentication helpers for Next.js API routes, middleware, and SSR.+sidebar_label: 'Next.js'+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++This submodule provides convenience helpers for implementing user authentication in Next.js applications.++## Install the Next.js helper library++<Tabs+ groupId="install"+ defaultValue="npm"+ values={[+ {label: 'npm', value: 'npm'},+ {label: 'Yarn', value: 'yarn'},+ ]}>++<TabItem value="npm">++```sh+npm install @supabase/auth-helpers-nextjs+```++This library supports the following tooling versions:++- Node.js: `^10.13.0 || >=12.0.0`+- Next.js: `>=10`++Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.++```sh+npm install @supabase/auth-helpers-react+```++</TabItem>+<TabItem value="yarn">++```sh+yarn add @supabase/auth-helpers-nextjs+```++This library supports the following tooling versions:++- Node.js: `^10.13.0 || >=12.0.0`+- Next.js: `>=10`++Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.++```sh+yarn add @supabase/auth-helpers-react+```++</TabItem>+</Tabs>++## Set up environment variables++Retrieve your project URL and anon key in your project's [API settings](https://app.supabase.com/project/_/settings/api) in the Dashboard to set up the following environment variables. For local development you can set them in a `.env.local` file. See an [example](https://github.com/supabase/auth-helpers/blob/main/examples/nextjs/.env.local.example).++```bash title=".env.local"+NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL+NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY+```++## Basic Setup++<Tabs+ defaultValue="js"+ values={[+ {label: 'JavaScript', value: 'js'},+ {label: 'TypeScript', value: 'ts'},+ ]}>+<TabItem value="js">++Wrap your `pages/_app.js` component with the `SessionContextProvider` component:++```jsx title="pages/_app.js"+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+import { SessionContextProvider } from '@supabase/auth-helpers-react'++function MyApp({ Component, pageProps }) {+ const router = useRouter()+ // Create a new supabase browser client on every first render.+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())++ return (+ <SessionContextProvider+ supabaseClient={supabaseClient}+ initialSession={pageProps.initialSession}+ >+ <Component {...pageProps} />+ </SessionContextProvider>+ )+}+```++</TabItem>+<TabItem value="ts">++Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:++```jsx title="pages/_app.tsx"+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+// highlight-next-line+import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'++function MyApp({+ Component,+ pageProps,+}: AppProps<{+ // highlight-next-line+ initialSession: Session,+}>) {+ // Create a new supabase browser client on every first render.+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())++ return (+ <SessionContextProvider+ supabaseClient={supabaseClient}+ initialSession={pageProps.initialSession}+ >+ <Component {...pageProps} />+ </SessionContextProvider>+ )+}+```++</TabItem>+</Tabs>++You can now determine if a user is authenticated by checking that the `user` object returned by the `useUser()` hook is defined.++## Usage with TypeScript++You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:++### Browser client++```ts+// Creating a new supabase client object:+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+import { Database } from '../database.types'++const supabaseClient = createBrowserSupabaseClient<Database>()+```++```ts+// Retrieving a supabase client object from the SessionContext:+import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { Database } from '../database.types'++const supabaseClient = useSupabaseClient<Database>()+```++### Server client++```ts+// Creating a new supabase server client object (e.g. in API route):+import type { NextApiRequest, NextApiResponse } from 'next'+import type { Database } from 'types_db'++export default async (req: NextApiRequest, res: NextApiResponse) => {+ const supabaseServerClient = createServerSupabaseClient<Database>({+ req,+ res,+ })+ const {+ data: { user },+ } = await supabaseServerClient.auth.getUser()++ res.status(200).json({ name: user?.name ?? '' })+}+```++## Client-side data fetching with RLS++For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSupabaseClient` hook and only run your query once the user is defined client-side in the `useUser()` hook:++```js+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'+import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'+import { useEffect, useState } from 'react'++const LoginPage = () => {+ const supabaseClient = useSupabaseClient()+ const user = useUser()+ const [data, setData] = useState()++ // highlight-start+ useEffect(() => {+ async function loadData() {+ const { data } = await supabaseClient.from('test').select('*')+ setData(data)+ }+ // Only run query once user is logged in.+ if (user) loadData()+ }, [user])+ // highlight-end++ if (!user)+ return (+ <Auth+ redirectTo="http://localhost:3000/"+ appearance={{ theme: ThemeSupa }}+ supabaseClient={supabaseClient}+ providers={['google', 'github']}+ socialLayout="horizontal"+ />+ )++ return (+ <>+ <button onClick={() => supabaseClient.auth.signOut()}>Sign out</button>+ <p>user:</p>+ <pre>{JSON.stringify(user, null, 2)}</pre>+ <p>client-side data fetching with RLS</p>+ <pre>{JSON.stringify(data, null, 2)}</pre>+ </>+ )+}++export default LoginPage+```++## Server-side rendering (SSR) - withPageAuth++If you wrap your `getServerSideProps` with `withPageAuth` your props object will be augmented with the user object.++```js title="pages/profile.js"+import { withPageAuth } from '@supabase/auth-helpers-nextjs'++export default function Profile({ user }) {+ return <div>Hello {user.name}</div>+}++export const getServerSideProps = withPageAuth({ redirectTo: '/login' })+```++If there is no authenticated user, they will be redirect to your home page, unless you specify the `redirectTo` option.++You can pass in your own `getServerSideProps` method, the props returned from this will be merged with the+user props. You can also access the user session data by calling `supabase.auth.getUser()` inside of this method, eg:++```js title="pages/protected-page.js"+import { withPageAuth } from '@supabase/auth-helpers-nextjs'++export default function ProtectedPage({ user, customProp }) {+ return <div>Protected content</div>+}++export const getServerSideProps = withPageAuth({+ redirectTo: '/foo',+ async getServerSideProps(ctx, supabase) {+ // Access the user object+ const {+ data: { user },+ } = await supabase.auth.getUser()+ return { props: { email: user?.email } }+ },+})+```++## Server-side data fetching with RLS++Both `withApiAuth` and `withPageAuth` return a supabase client that you can use to run [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) authenticated queries server-side:++```js+import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'++export default function ProtectedPage({+ user,+ data,+}: {+ user: User,+ data: any,+}) {+ return (+ <>+ <div>Protected content for {user.email}</div>+ <pre>{JSON.stringify(data, null, 2)}</pre>+ <pre>{JSON.stringify(user, null, 2)}</pre>+ </>+ )+}++export const getServerSideProps = withPageAuth({+ redirectTo: '/',+ async getServerSideProps(ctx, supabase) {+ // Run queries with RLS on the server+ const { data } = await supabase.from('test').select('*')+ return { props: { data } }+ },+})+```++## Server-side data fetching to OAuth APIs using `provider_token`++When using third-party auth providers, sessions are initiated with an additional `provider_token` field which is persisted as an HTTPOnly cookie upon logging in to enabled usage on the server side. The `provider_token` can be used to make API requests to the OAuth provider's API endpoints on behalf of the logged-in user. In the following example, we fetch the user's full profile from the third-party API during SSR using their id and auth token:++```js+import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'++export default function ProtectedPage({+ user,+ allRepos,+}: {+ user: User,+ allRepos: any,+}) {+ return (+ <>+ <div>Protected content for {user.email}</div>+ <p>Data fetched with provider token:</p>+ <pre>{JSON.stringify(allRepos, null, 2)}</pre>+ <p>user:</p>+ <pre>{JSON.stringify(user, null, 2)}</pre>+ </>+ )+}++export const getServerSideProps = withPageAuth({+ redirectTo: '/',+ async getServerSideProps(ctx, supabase) {+ const {+ data: { session },+ error,+ } = await supabase.auth.getSession()+ if (error) {+ throw error+ }+ if (!session) {+ return { props: {} }+ }++ // Retrieve provider_token & logged in user's third-party id from metadata+ const { provider_token, user } = session+ const userId = user.user_metadata.user_name++ const allRepos = await (+ await fetch(+ `https://api.github.com/search/repositories?q=user:${userId}`,+ {+ method: 'GET',+ headers: {+ Authorization: `token ${provider_token}`,+ },+ }+ )+ ).json()++ return { props: { allRepos, user } }+ },+})+```++## Protecting API routes++Wrap an API Route to check that the user has a valid session. If they're not logged in the handler will return a+401 Unauthorized.++```js title="pages/api/protected-route.js"+import { withApiAuth } from '@supabase/auth-helpers-nextjs'++export default withApiAuth(async function ProtectedRoute(req, res, supabase) {+ // Run queries with RLS on the server+ const { data } = await supabase.from('test').select('*')+ res.json(data)+})+```++If you visit `/api/protected-route` without a valid session cookie, you will get a 401 response.++## Protecting routes with [Nextjs Middleware](https://nextjs.org/docs/middleware)++As an alternative to protecting individual pages using `getServerSideProps` with `withPageAuth`, `withMiddlewareAuth` can be used from inside a `middleware` file to protect the entire directory or those that match the config object. In the following example, all requests to `/middleware-protected/*` will check whether a user is signed in, if successful the request will be forwarded to the destination route, otherwise the user will be redirected to `/login` (defaults to: `/`) with a 307 Temporary Redirect response status:++```ts title="middleware.ts"+import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs'++export const middleware = withMiddlewareAuth({ redirectTo: '/login' })++export const config = {+ matcher: ['/middleware-protected/:path*'],+}+```++It is also possible to add finer granularity based on the user logged in. I.e. you can specify a promise to determine if a specific user has permission or not.++```ts title="middleware.ts"+import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs'++export const middleware = withMiddlewareAuth({+ redirectTo: '/login',+ authGuard: {+ isPermitted: async (user) => user.email?.endsWith('@example.com') ?? false,+ redirectTo: '/insufficient-permissions',+ },+})++export const config = {+ matcher: ['/middleware-protected/:path*'],+}+```++## Migrating to version `0.4.X` {#migration}++- With `supabase-js` v2, the `auth` API routes are no longer required and you can delete the `auth` directory under the `/pages/api/` directory.+- The `/api/auth/logout` API route has been removed—use the `signout` method instead.+ ```js+ <button+ onClick={async () => {+ await supabaseClient.auth.signOut()+ router.push('/')+ }}+ >+ Logout+ </button>+ ```+- The `supabaseClient` and `supabaseServerClient` have been removed in favor of the `createBrowserSupabaseClient` and `createServerSupabaseClient` methods. This allows you to provide the CLI-generated types to the client:++ ```js+ // client-side+ import type { Database } from 'types_db';+ const [supabaseClient] = useState(() =>+ createBrowserSupabaseClient<Database>()+ );++ // server-side API route+ import type { NextApiRequest, NextApiResponse } from 'next'+ import type { Database } from 'types_db';++ export default async (req: NextApiRequest, res: NextApiResponse) => {+ const supabaseServerClient = createServerSupabaseClient<Database>({ req, res })+ const { data:{ user } } = await supabaseServerClient.auth.getUser()++ res.status(200).json({ name: user?.name ?? '' })+ }+ ```++- The `UserProvider` has been replaced by the `SessionContextProvider`. Make sure to wrap your `pages/_app.js` componenent with the `SessionContextProvider`. Then, throughout your application you can use the `useSessionContext` hook to get the `session` and the `useSupabaseClient` hook to get an authenticated `supabaseClient`.+- The `useUser` hook now returns the `user` object or `null`.+- Usage with TypeScript: You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:++ ```js+ // Creating a new supabase client object:+ import { Database } from '../database.types';++ const [supabaseClient] = useState(() =>+ createBrowserSupabaseClient<Database>()+ );+ ```++ ```js+ // Retrieving a supabase client object from the SessionContext:+ import { useSupabaseClient } from '@supabase/auth-helpers-react';+ import { Database } from '../database.types';++ const supabaseClient = useSupabaseClient<Database>();+ ```diff --git a/apps/temp-docs/docs/guides/auth/auth-helpers/sveltekit.mdx b/apps/temp-docs/docs/guides/auth/auth-helpers/sveltekit.mdxnew file mode 100644index 00000000000..5ba0d72572a--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-helpers/sveltekit.mdx@@ -0,0 +1,897 @@+---+id: sveltekit+title: Supabase Auth with SvelteKit+description: Convenience helpers for implementing user authentication in SvelteKit.+sidebar_label: SvelteKit+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++This submodule provides convenience helpers for implementing user authentication in [SvelteKit](https://kit.svelte.dev/) applications.++## Installation++This library supports Node.js `^16.15.0`.++<Tabs+ groupId="install"+ defaultValue="npm"+ values={[+ {label: 'npm', value: 'npm'},+ {label: 'Yarn', value: 'yarn'},+ ]}>++<TabItem value="npm">++```sh+npm install @supabase/auth-helpers-sveltekit+```++</TabItem>++<TabItem value="yarn">++```sh+yarn add @supabase/auth-helpers-sveltekit+```++</TabItem>+</Tabs>++## Getting Started++### Configuration++Set up the fillowing env vars. For local development you can set them in a `.env` file. See an [example](https://github.com/supabase/auth-helpers/blob/main/examples/sveltekit/.env.example).++```bash+# Find these in your Supabase project settings > API+PUBLIC_SUPABASE_URL=https://your-project.supabase.co+PUBLIC_SUPABASE_ANON_KEY=your-anon-key+```++### Set up the Supabase client++Start off by creating a `db.ts` file inside of the `src/lib` directory and instantiate the `supabaseClient`.++```ts title="src/lib/db.ts"+import { createClient } from '@supabase/supabase-js'+import { setupSupabaseHelpers } from '@supabase/auth-helpers-sveltekit'+import { dev } from '$app/environment'+import { env } from '$env/dynamic/public'+// or use the static env+// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';++export const supabaseClient = createClient(+ env.PUBLIC_SUPABASE_URL,+ env.PUBLIC_SUPABASE_ANON_KEY,+ {+ persistSession: false,+ autoRefreshToken: false,+ }+)++setupSupabaseHelpers({+ supabaseClient,+ cookieOptions: {+ secure: !dev,+ },+})+```++### Initialize the client++Edit your `+layout.svelte` file and set up the client-side.++```html title="src/routes/+layout.svelte"+<script lang="ts">+ // make sure the supabase instance is initialized on the client+ import '$lib/db'+ import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit'+ import { page } from '$app/stores'+ import { invalidateAll } from '$app/navigation'++ // this sets up automatic token refreshing+ startSupabaseSessionSync({+ page,+ handleRefresh: () => invalidateAll(),+ })+</script>++<slot />+```++### Set up hooks++The `hooks.server.ts` file is where the heavy lifting of this library happens:++```ts title="src/hooks.server.ts"+// make sure the supabase instance is initialized on the server+import '$lib/db'+import { dev } from '$app/environment'+import { auth } from '@supabase/auth-helpers-sveltekit/server'++export const handle = auth()++// use the sequence helper if you have additional Handle methods+import { sequence } from '@sveltejs/kit/hooks'++export const handle = sequence(auth(), yourHandler)+```++There are three handle methods available:++- `callback()`:+ This creates a handler for `/api/auth/callback`. The `client` forwards the session details here every time `onAuthStateChange` fires on the client-side. This is needed to set up the cookies for your application so that SSR works seamlessly.+- `session()`:+ This parses the session from the cookie and populate it in locals+- `auth()`:+ a shorthand for `sequence(callback(), session())` that uses both handlers++### Send session to client++In order to make the session available to the UI (e.g., pages and layouts), pass the session in the root layout load function:++```ts title="src/routes/+layout.server.ts"+import type { LayoutServerLoad } from './$types'++export const load: LayoutServerLoad = async ({ locals }) => {+ return {+ session: locals.session,+ }+}+```++### Typings++In order to get the most out of TypeScript and IntelliSense, import the types into the `app.d.ts` type definition file that comes with your SvelteKit project.++```ts title="src/app.d.ts"+/// <reference types="@sveltejs/kit" />++// See https://kit.svelte.dev/docs/types#app+// for information about these interfaces+// and what to do when importing types+declare namespace App {+ interface Locals {+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }+ interface PageData {+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }+ // interface Error {}+ // interface Platform {}+}+```++### Signing out++This library has provided a method to delete the session cookie.++Create a server only page with an action to delete the cookie++```ts title="src/routes/logout/+page.server.ts"+import { deleteSession } from '@supabase/auth-helpers-sveltekit/server'+import { redirect } from '@sveltejs/kit'+import type { Actions } from './$types'++export const actions: Actions = {+ async default({ cookies }) {+ deleteSession(cookies)+ throw redirect(303, '/')+ },+}+```++Then make a **POST** request with a form to the server only page above.++```html+<script lang="ts">+ import { enhanceAndInvalidate } from '@supabase/auth-helpers-sveltekit'+</script>++<form action="/logout" method="post" use:enhanceAndInvalidate>+ <button type="submit">Sign out</button>+</form>+```++### Basic setup++You can now determine if a user is authenticated on the client-side by checking that the `user` object in `$page.data.session` is defined.++```html title="src/routes/+page.svelte"+<script>+ import { page } from '$app/stores'+</script>++{#if !$page.data.session.user}+<h1>I am not logged in</h1>+{:else}+<h1>Welcome {$page.data.session.user.email}</h1>+<p>I am logged in!</p>+{/if}+```++## Client-side data fetching with RLS++For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to import the `{ supabaseClient }` from `$lib/db` and only run your query once the user is defined client-side in `$page.data.session`:++```html+<script>+ import { supabaseClient } from '$lib/db'+ import { page } from '$app/stores'++ let loadedData = []+ async function loadData() {+ const { data } = await supabaseClient.from('test').select('*').limit(20)+ loadedData = data+ }++ $: if ($page.data.session.user) {+ loadData()+ }+</script>++{#if $page.data.session.user}+<p>client-side data fetching with RLS</p>+<pre>{JSON.stringify(loadedData, null, 2)}</pre>+{/if}+```++## Server-side data fetching with RLS++```html title="src/routes/profile/+page.svelte"+<script>+ /** @type {import('./$types').PageData} */+ export let data+ $: ({ user, tableData } = data)+</script>++<div>Protected content for {user.email}</div>+<pre>{JSON.stringify(tableData, null, 2)}</pre>+<pre>{JSON.stringify(user, null, 2)}</pre>+```++For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work in a server environment, you need to use the `withAuth` helper to check if the user is authenticated. The helper extends the event with `session` and `getSupabaseClient()`:++```ts title="src/routes/profile/+page.ts"+import type { PageLoad } from './$types';+import { withAuth } from '@supabase/auth-helpers-sveltekit';+import { redirect } from '@sveltejs/kit';++interface TestTable {+ id: string;+ created_at: string;+}++export const load: PageLoad = withAuth(async ({ getSupabaseClient, session }) => {+ if (!session.user) {+ throw redirect(303, '/');+ }+ const { data: tableData } = await getSupabaseClient()+ .from<TestTable>('test')+ .select('*');++ return {+ user: session.user,+ tableData+ };+);+```++**Caution:**++Always use the instance returned by `getSupabaseClient()` directly!++```ts+// Bad+const supabaseClient = getSupabaseClient()++await supabaseClient.from('table1').select()+await supabaseClient.from('table2').select()++// Good+await getSupabaseClient().from('table1').select()+await getSupabaseClient().from('table2').select()+```++## Protecting API routes++Wrap an API Route to check that the user has a valid session. If they're not logged in the session is `null`.++```ts title="src/routes/api/protected-route/+server.ts"+import type { RequestHandler } from './$types';+import { withAuth } from '@supabase/auth-helpers-sveltekit';+import { json, redirect } from '@sveltejs/kit';++interface TestTable {+ id: string;+ created_at: string;+}++export const GET: RequestHandler = withAuth(async ({ session, getSupabaseClient }) => {+ if (!session.user) {+ throw redirect(303, '/');+ }+ const { data } = await getSupabaseClient()+ .from<TestTable>('test')+ .select('*');++ return json({ data });+);+```++If you visit `/api/protected-route` without a valid session cookie, you will get a 303 response.++## Protecting Actions++Wrap an Action to check that the user has a valid session. If they're not logged in, the session is `null`.++```ts title="src/routes/posts/+page.server.ts"+import type { Actions } from './$types'+import { withAuth } from '@supabase/auth-helpers-sveltekit'+import { error, invalid } from '@sveltejs/kit'++export const actions: Actions = {+ createPost: withAuth(async ({ session, getSupabaseClient, request }) => {+ if (!session.user) {+ // the user is not signed in+ throw error(403, { message: 'Unauthorized' })+ }+ // we are save, let the user create the post+ const formData = await request.formData()+ const content = formData.get('content')++ const { error: createPostError, data: newPost } = await getSupabaseClient()+ .from('posts')+ .insert({ content })++ if (createPostError) {+ return invalid(500, {+ supabaseErrorMessage: createPostError.message,+ })+ }+ return {+ newPost,+ }+ }),+}+```++If you try to submit a form with the action `?/createPost` without a valid session cookie, you will get a 403 error response.++## Saving and deleting the session++Use `saveSession` to save the session cookies:++```ts+import type { Actions } from './$types'+import { supabaseClient } from '$lib/db'+import { invalid, redirect } from '@sveltejs/kit'+import { saveSession } from '@supabase/auth-helpers-sveltekit/server'++export const actions: Actions = {+ async signin({ request, cookies, url }) {+ const formData = await request.formData()++ const email = formData.get('email') as string+ const password = formData.get('password') as string++ const { data, error } = await supabaseClient.auth.api.signInWithEmail(+ email,+ password,+ {+ redirectTo: `${url.origin}/logging-in`,+ }+ )++ if (error || !data) {+ if (error?.status === 400) {+ return invalid(400, {+ error: 'Invalid credentials',+ values: {+ email,+ },+ })+ }+ return invalid(500, {+ error: 'Server error. Try again later.',+ values: {+ email,+ },+ })+ }++ saveSession(cookies, data)+ throw redirect(303, '/dashboard')+ },+}+```++Use `deleteSession` to delete the session cookies:++```ts+import type { Actions } from './$types'+import { deleteSession } from '@supabase/auth-helpers-sveltekit/server'+import { redirect } from '@sveltejs/kit'++export const actions: Actions = {+ async logout({ cookies }) {+ deleteSession(cookies)+ throw redirect(303, '/')+ },+}+```++## Custom session namespace++If you want to use something other than `locals.session` and `$page.data.session`, update the types and create three helper functions:++```ts title="src/app.d.ts"+declare namespace App {+ interface Locals {+ mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }+ interface PageData {+ mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }+}+```++```ts title="src/hooks.server.ts"+setupSupabaseServer({+ supabaseClient,+ cookieOptions: {+ secure: !dev,+ },+ // --- change location within locals ---+ getSessionFromLocals: (locals) => locals.mySupabaseSession,+ setSessionToLocals: (locals, session) => (locals.mySupabaseSession = session),+})+```++```ts title="src/lib/db.ts"+setupSupabaseClient({+ supabaseClient,+ // --- change location within pageData ---+ getSessionFromPageData: (data) => data.mySupabaseSession,+})+```++## Migrate from 0.6.11 and below to 0.7.0 {#migration}++There are numerous breaking changes in the latest 0.7.0 version of this library.++### Environment variable prefix++The environment variable prefix is now `PUBLIC_` instead of `VITE_` (e.g., `VITE_SUPABASE_URL` is now `PUBLIC_SUPABASE_URL`).++### Set up the Supabase client {#migration-set-up-supabase-client}++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```js title="src/lib/db.ts"+import { createSupabaseClient } from '@supabase/auth-helpers-sveltekit';++const { supabaseClient } = createSupabaseClient(+ import.meta.env.VITE_SUPABASE_URL as string,+ import.meta.env.VITE_SUPABASE_ANON_KEY as string+);++export { supabaseClient };+```++</TabItem>++<TabItem value="latest">++```js title="src/lib/db.ts"+import { createClient } from '@supabase/supabase-js'+import { setupSupabaseHelpers } from '@supabase/auth-helpers-sveltekit'+import { dev } from '$app/environment'+import { env } from '$env/dynamic/public'+// or use the static env++// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';++export const supabaseClient = createClient(+ env.PUBLIC_SUPABASE_URL,+ env.PUBLIC_SUPABASE_ANON_KEY,+ {+ persistSession: false,+ autoRefreshToken: false,+ }+)++setupSupabaseHelpers({+ supabaseClient,+ cookieOptions: {+ secure: !dev,+ },+})+```++</TabItem>+</Tabs>++### Initialize the client {#migration-initialize-client}++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```html title="src/routes/__layout.svelte"+<script>+ import { session } from '$app/stores'+ import { supabaseClient } from '$lib/db'+ import { SupaAuthHelper } from '@supabase/auth-helpers-svelte'+</script>++<SupaAuthHelper {supabaseClient} {session}>+ <slot />+</SupaAuthHelper>+```++</TabItem>++<TabItem value="latest">++The `@supabase/auth-helpers-svelte` library is no longer required as the `@supabase/auth-helpers-sveltekit` library handles all the client-side code.++```html title="src/routes/+layout.svelte"+<script lang="ts">+ // make sure the supabase instance is initialized on the client+ import '$lib/db'+ import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit'+ import { page } from '$app/stores'+ import { invalidateAll } from '$app/navigation'++ // this sets up automatic token refreshing+ startSupabaseSessionSync({+ page,+ handleRefresh: () => invalidateAll(),+ })+</script>++<slot />+```++</TabItem>+</Tabs>++### Set up hooks {#migration-set-up-hooks}++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```ts title="src/hooks.ts"+import { handleAuth } from '@supabase/auth-helpers-sveltekit'+import type { GetSession, Handle } from '@sveltejs/kit'+import { sequence } from '@sveltejs/kit/hooks'++export const handle: Handle = sequence(...handleAuth())++export const getSession: GetSession = async (event) => {+ const { user, accessToken, error } = event.locals+ return {+ user,+ accessToken,+ error,+ }+}+```++</TabItem>++<TabItem value="latest">++```ts title="src/hooks.server.ts"+// make sure the supabase instance is initialized on the server+import '$lib/db'+import { dev } from '$app/environment'+import { auth } from '@supabase/auth-helpers-sveltekit/server'++export const handle = auth()+```++**Optional** _if using additional handle methods_++```ts title="src/hooks.server.ts"+// make sure the supabase instance is initialized on the server+import '$lib/db'+import { dev } from '$app/environment'+import { auth } from '@supabase/auth-helpers-sveltekit/server'+import { sequence } from '@sveltejs/kit/hooks'++export const handle = sequence(auth(), yourHandler)+```++</TabItem>+</Tabs>++### Typings {#migration-typings}++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```ts title="src/app.d.ts"+/// <reference types="@sveltejs/kit" />+// See https://kit.svelte.dev/docs/types#app+// for information about these interfaces+declare namespace App {+ interface UserSession {+ user: import('@supabase/supabase-js').User+ accessToken?: string+ }++ interface Locals extends UserSession {+ error: import('@supabase/supabase-js').ApiError+ }++ interface Session extends UserSession {}++ // interface Platform {}+ // interface Stuff {}+}+```++</TabItem>++<TabItem value="latest">++```ts title="src/app.d.ts"+/// <reference types="@sveltejs/kit" />++// See https://kit.svelte.dev/docs/types#app+// for information about these interfaces+// and what to do when importing types+declare namespace App {+ interface Locals {+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }++ interface PageData {+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession+ }++ // interface Error {}+ // interface Platform {}+}+```++</TabItem>+</Tabs>++### Check the user on the client++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```html title="src/routes/index.svelte"+<script>+ import { session } from '$app/stores'+</script>++{#if !$session.user}+<h1>I am not logged in</h1>+{:else}+<h1>Welcome {$session.user.email}</h1>+<p>I am logged in!</p>+{/if}+```++</TabItem>++<TabItem value="latest">++```html title="src/routes/+page.svelte"+<script>+ import { page } from '$app/stores'+</script>++{#if !$page.data.session.user}+<h1>I am not logged in</h1>+{:else}+<h1>Welcome {$page.data.session.user.email}</h1>+<p>I am logged in!</p>+{/if}+```++</TabItem>+</Tabs>++### withPageAuth++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```html title="src/routes/protected-route.svelte"+<script lang="ts" context="module">+ import {+ supabaseServerClient,+ withPageAuth,+ } from '@supabase/auth-helpers-sveltekit'+ import type { Load } from './__types/protected-page'++ export const load: Load = async ({ session }) =>+ withPageAuth(+ {+ redirectTo: '/',+ user: session.user,+ },+ async () => {+ const { data } = await supabaseServerClient(session.accessToken)+ .from('test')+ .select('*')+ return { props: { data, user: session.user } }+ }+ )+</script>++<script>+ export let data+ export let user+</script>++<div>Protected content for {user.email}</div>+<p>server-side fetched data with RLS:</p>+<pre>{JSON.stringify(data, null, 2)}</pre>+<p>user:</p>+<pre>{JSON.stringify(user, null, 2)}</pre>+```++</TabItem>++<TabItem value="latest">++```html title="src/routes/protected-route/+page.svelte"+<script lang="ts">+ import type { PageData } from './$types'++ export let data: PageData+ $: ({ tableData, user } = data)+</script>++<div>Protected content for {user.email}</div>+<p>server-side fetched data with RLS:</p>+<pre>{JSON.stringify(tableData, null, 2)}</pre>+<p>user:</p>+<pre>{JSON.stringify(user, null, 2)}</pre>+```++```ts title="src/routes/protected-route/+page.ts"+import { withAuth } from '@supabase/auth-helpers-sveltekit'+import { redirect } from '@sveltejs/kit'+import type { PageLoad } from './$types'++export const load: PageLoad = withAuth(+ async ({ session, getSupabaseClient }) => {+ if (!session.user) {+ throw redirect(303, '/')+ }++ const { data: tableData } = await getSupabaseClient()+ .from('test')+ .select('*')+ return { tableData, user: session.user }+ }+)+```++</TabItem>+</Tabs>++### withApiAuth++<Tabs+ groupId="version"+ values={[+ {label: '0.6.11 and below', value: 'older'},+ {label: '0.7.0', value: 'latest'},+ ]}>++<TabItem value="older">++```ts title="src/routes/api/protected-route.ts"+import {+ supabaseServerClient,+ withApiAuth,+} from '@supabase/auth-helpers-sveltekit'+import type { RequestHandler } from './__types/protected-route'++interface TestTable {+ id: string+ created_at: string+}++interface GetOutput {+ data: TestTable[]+}++export const GET: RequestHandler<GetOutput> = async ({ locals, request }) =>+ withApiAuth({ user: locals.user }, async () => {+ // Run queries with RLS on the server+ const { data } = await supabaseServerClient(request)+ .from('test')+ .select('*')++ return {+ status: 200,+ body: { data },+ }+ })+```++</TabItem>++<TabItem value="latest">++```ts title="src/routes/api/protected-route/+server.ts"+import type { RequestHandler } from './$types';+import { withAuth } from '@supabase/auth-helpers-sveltekit';+import { json, redirect } from '@sveltejs/kit';++interface TestTable {+ id: string;+ created_at: string;+}++export const GET: RequestHandler = withAuth(async ({ session, getSupabaseClient }) => {+ if (!session.user) {+ throw redirect(303, '/');+ }++ const { data } = await getSupabaseClient()+ .from<TestTable>('test')+ .select('*');++ return json({ data });+);+```++</TabItem>+</Tabs>++## Additional Links++- [Auth Helpers Source code](https://github.com/supabase/auth-helpers)+- [SvelteKit example](https://github.com/supabase/auth-helpers/tree/main/examples/sveltekit)+- [SvelteKit Email/Password example](https://github.com/supabase/auth-helpers/tree/main/examples/sveltekit-email-password)+- [SvelteKit Magiclink example](https://github.com/supabase/auth-helpers/tree/main/examples/sveltekit-magic-link)diff --git a/apps/temp-docs/docs/guides/auth/auth-keycloak.mdx b/apps/temp-docs/docs/guides/auth/auth-keycloak.mdxnew file mode 100644index 00000000000..76e536063c3--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-keycloak.mdx@@ -0,0 +1,86 @@+---+id: auth-keycloak+title: 'Login with Keycloak'+description: Add Keycloak OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable Keycloak Auth for your project, you need to set up an Keycloak OAuth application and add the application credentials to your Supabase Dashboard.++## Overview++To get started with Keycloak, you can run it in a docker container with: `docker run -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -p 8080:8080 jboss/keycloak:latest`++This guide will be assuming that you are running keycloak in a docker container as described in the command above.++Keycloak OAuth consists of five broad steps:++- Create a new client in your specified keycloak realm.+- Obtain the `issuer` from the "OpenID Endpoint Configuration". This will be used as the `Keycloak URL`.+- Ensure that the new client has the "Client Protocol" set to "openid-connect" and the "Access Type" is set to "confidential".+- The `Client ID` of the client created will be used as the `client id`.+- Obtain the `Secret` from the credentials tab which will be used as the `client secret`.+- Add the callback url of your application to your allowlist.++## Access your Keycloak Admin console++- Login by visiting [`http://localhost:8080`](http://localhost:8080) and clicking on "Administration Console".++## Create a Keycloak Realm++- Once you've logged in to the Keycloak console, you can add a realm from the side panel. The default realm should be named "Master".+- After you've added a new realm, you can retrieve the `issuer` from the "OpenID Endpoint Configuration" endpoint. The `issuer` will be used as the `Keycloak URL`.+- You can find this endpoint from the realm settings under the "General Tab" or visit [`http://localhost:8080/realms/my_realm_name/.well-known/openid-configuration`](http://localhost:8080/realms/my_realm_name/.well-known/openid-configuration)++++## Create a Keycloak Client++The "Client ID" of the created client will serve as the `client_id` when you make API calls to authenticate the user.++++## Client Settings++After you've created the client successfully, ensure that you set the following settings:++1. The "Client Protocol" should be set to "openid-connect".+2. The "Access Type" should be set to "confidential".+3. The "Valid Redirect URIs" should be set to: `https://<project-ref>.supabase.co/auth/v1/callback`.+++++## Obtain the Client Secret++This will serve as the `client_secret` when you make API calls to authenticate the user.+Under the "Credentials" tab, the `Secret` value will be used as the `client secret`.++++## Add login code to your client app++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `keycloak` as the `provider`:++```js+async function signInWithKeycloak() {+ const { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'keycloak',+ })+}+```++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- You can find the keycloak openid endpoint configuration under the realm settings.+ diff --git a/apps/temp-docs/docs/guides/auth/auth-linkedin.mdx b/apps/temp-docs/docs/guides/auth/auth-linkedin.mdxnew file mode 100644index 00000000000..207d19c0439--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-linkedin.mdx@@ -0,0 +1,93 @@+---+id: auth-linkedin+title: 'Login with LinkedIn'+description: Add LinkedIn OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable LinkedIn Auth for your project, you need to set up a LinkedIn OAuth application and add the application credentials to your Supabase Dashboard.++## Overview++Setting up LinkedIn logins for your application consists of 3 parts:++- Create and configure a LinkedIn Project and App on the [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps).+- Add your LinkedIn `client_id` and `client_secret` to your [Supabase Project](https://app.supabase.com).+- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js).++## Access your LinkedIn Developer account++- Go to [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps).+- Log in (if necessary.)++++## Find your callback URL++The next step requires a callback URL, which looks like this:++`https://<project-ref>.supabase.co/auth/v1/callback`++- Go to your [Supabase Project Dashboard](https://app.supabase.com).+- Click on the `Settings` icon at the bottom of the left sidebar.+- Click on `API` in the list.+- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.+- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Create a LinkedIn OAuth app++- Go to [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps).+- Click on `Create App` at the top right+- Enter your `LinkedIn Page` and `App Logo`+- Save your app+- Click `Auth` from the top menu+- Add your `Redirect URL` to the `Authorized Redirect URLs for your app` section+- Copy and save your newly-generated `Client ID`+- Copy and save your newly-generated `Client Secret`++## Enter your LinkedIn credentials into your Supabase Project++- Go to your [Supabase Project Dashboard](https://app.supabase.com).+- In the left sidebar, click the `Authentication` icon (near the top).+- Click `Settings` from the list to go to the `Authentication Settings` page.+- Enter the final (hosted) URL of your app under `Site URL` (this is important).+- Under `External OAuth Providers` turn `LinkedIn Enabled` to ON.+- Enter your `client_id` and `client_secret` saved in the previous step.+- Click `Save`.++## Add login code to your client app++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `linkedin` as the `provider`:++```js+async function signInWithLinkedIn() {+ const { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'linkedin',+ })+}+```++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- [Supabase Account - Free Tier OK](https://supabase.com)+- [Supabase JS Client](https://github.com/supabase/supabase-js)+- [LinkedIn Developer Dashboard](https://api.LinkedIn.com/apps)diff --git a/apps/temp-docs/docs/guides/auth/auth-magic-link.mdx b/apps/temp-docs/docs/guides/auth/auth-magic-link.mdxindex aa836989a82..3d09f2e726b 100644--- a/apps/temp-docs/docs/guides/auth/auth-magic-link.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-magic-link.mdx@@ -1,108 +1,73 @@---id: auth-magic-linktitle: 'Login With Magic Link'-description: Use Supabase to Authenticate and Authorize your users using Magic Link.+description: Use Supabase to authenticate and authorize your users using magic links.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'-By default, if no password is provided, the user will be sent a "magic link" to their email address, which they can click to open your application with a valid session. By default, a given user can only request a Magic Link once every 60 seconds.+Magic links are a form of passwordless logins where users click on a link sent to their email address to log in to their accounts.+Magic links only work with email addresses. By default, a user can only request a magic link once every 60 seconds.## OverviewSetting up Magic Link logins for your Supabase application.- Add Magic Link authenticator to your [Supabase Project](https://app.supabase.com)-- Add the login code to your application - [Javascript](https://github.com/supabase/supabase-js) | [Dart](https://github.com/supabase/supabase-dart)+- Add the login code to your application - [JavaScript](https://github.com/supabase/supabase-js) | [Flutter](https://github.com/supabase/supabase-flutter)## Add Magic Link into your Supabase Project-- Go to your [Supabase Project Dashboard](https://app.supabase.com)-- In the left sidebar, click the `Authentication` icon (near the top)-- Click `Settings` from the list to go to the `Authentication Settings` page-- Enter the final (hosted) URL of your app under `Site URL` (this is important)-- Under `Email Auth` turn `Enable Email Signup` to ON-- Click `Save`+1. Go to the [Authentication Settings](https://app.supabase.com/project/_/auth/settings) page in the Dashboard.+1. For **Site URL**, enter the final (hosted) URL of your app.+1. Under Auth Providers, **enable email provider**.-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)+## Add login code to your client app<Tabs- defaultActiveId="js"+ defaultValue="js"groupId="guides/auth"values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}>-<TabsPanel id="js" label="js">--```js-const { user, error } = await supabase.auth.signIn({- email: '[email protected]',-})-```--</TabsPanel>--<TabsPanel id="dart" label="dart">+<TabItem value="js">-```dart-final res = await supabase.auth.signIn(- email: '[email protected]'-);--final user = res.data?.user;-final error = res.error;-```--</TabsPanel>--</Tabs>--Add this function which you can call from a button, link, or UI element.--<Tabs- defaultActiveId="js"- groupId="guides/auth"- values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}->--<TabsPanel id="js" label="js">+When your user signs in, call [signInWithOtp()](/docs/reference/javascript/auth-signinwithotp) with their email address:```jsasync function signInWithEmail() {- const { user, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOtp({email: '[email protected]',})}```-</TabsPanel>+</TabItem>++<TabItem value="dart">-<TabsPanel id="dart" label="dart">+When your user signs in, call [signIn()](/docs/reference/dart/auth-signinwithotp) with their email address:```dart-function SignInWithEmail() {- await supabase.auth.signIn(- email: '[email protected]'- );+Future<void> signInWithEmail() async {+ final AuthResponse res = await supabase.auth.signinwithotp(email: '[email protected]');}```-</TabsPanel>+</TabItem></Tabs>-To log out:-<Tabs- defaultActiveId="js"+ defaultValue="js"groupId="guides/auth"values={[{ label: 'JavaScript', value: 'js' }, { label: 'Dart', value: 'dart' }]}>-<TabsPanel id="js" label="js">+<TabItem value="js">++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signOut() {@@ -110,17 +75,19 @@ async function signOut() {}```-</TabsPanel>+</TabItem>++<TabItem value="dart">-<TabsPanel id="dart" label="dart">+When your user signs out, call [signOut()](/docs/reference/dart/auth-signout) to remove them from the browser session and any objects from localStorage:```dart-function SignOut() {+Future<void> signOut() async {await supabase.auth.signOut();}```-</TabsPanel>+</TabItem></Tabs>@@ -128,4 +95,4 @@ function SignOut() {- [Supabase Account - Free Tier OK](https://supabase.com)- [Supabase JS Client](https://github.com/supabase/supabase-js)-- [Supabase Dart Client](https://github.com/supabase/supabase-dart)+- [Supabase Flutter Client](https://github.com/supabase/supabase-flutter)diff --git a/apps/temp-docs/docs/guides/auth/auth-messagebird.mdx b/apps/temp-docs/docs/guides/auth/auth-messagebird.mdxindex b67178e2aea..9c7c2bb2756 100644--- a/apps/temp-docs/docs/guides/auth/auth-messagebird.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-messagebird.mdx@@ -5,7 +5,7 @@ description: How to set up and use Mobile OTP with MessageBird and Supabase.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'## Overview@@ -36,14 +36,14 @@ Start by logging into your MessageBird account and verify the mobile number you'This is the number that will be receiving the SMS OTPs.-+-+Navigate to the [dashboard settings](https://dashboard.messagebird.com/en/settings/sms) to set the default originator. The messagebird originator is the name or number from which the message is sent.For more information, you can refer to the messagebird article on choosing an originator [here](https://support.messagebird.com/hc/en-us/articles/115002628665-Choosing-an-originator)-+You will need the following values to get started:@@ -54,7 +54,7 @@ Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabaYou should see an option to enable Phone Signup.-+Toggle it on, and copy the 2 values over from the messagebird dashboard. Click save.@@ -82,12 +82,12 @@ In this use scenario we'll be using the user's mobile phone number as an alternaUsing supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { user, error } = await supabase.auth.signUp({@@ -96,8 +96,8 @@ let { user, error } = await supabase.auth.signUp({})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \@@ -109,7 +109,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \}'```-</TabsPanel>+</TabItem></Tabs>The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account.@@ -117,12 +117,12 @@ The user will now receive an SMS with a 6-digit pin that you will need to receivYou should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { session, error } = await supabase.auth.verifyOTP({@@ -131,8 +131,8 @@ let { session, error } = await supabase.auth.verifyOTP({})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \@@ -145,7 +145,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \}'```-</TabsPanel>+</TabItem></Tabs>If successful the user will now be logged in and you should receive a valid session like:@@ -164,22 +164,22 @@ The access token can be sent in the Authorization header as a Bearer token for aAlso now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```js-let { user, error } = await supabase.auth.signIn({+let { user, error } = await supabase.auth.signInWithPassword({phone: '+13334445555',password: 'some-password',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=password' \@@ -191,7 +191,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=}'```-</TabsPanel>+</TabItem></Tabs>### Using OTP as a passwordless sign-in mechanism@@ -201,21 +201,21 @@ In this scenario you are granting your user's the ability to login to their accoIn javascript we can use the `signIn` method with a single parameter: `phone`<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```js-let { user, error } = await supabase.auth.signIn({+let { user, error } = await supabase.auth.signInWithOtp({phone: '+13334445555',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \@@ -226,18 +226,18 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \}'```-</TabsPanel>+</TabItem></Tabs>The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { session, error } = await supabase.auth.verifyOTP({@@ -246,8 +246,8 @@ let { session, error } = await supabase.auth.verifyOTP({})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \@@ -260,7 +260,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \}'```-</TabsPanel>+</TabItem></Tabs>and the response should also be the same as above:diff --git a/apps/temp-docs/docs/guides/auth/auth-mfa.mdx b/apps/temp-docs/docs/guides/auth/auth-mfa.mdxnew file mode 100644index 00000000000..ed52db81718--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-mfa.mdx@@ -0,0 +1,625 @@+---+id: auth-mfa+title: 'Multi-Factor Authentication'+description: Add an additional layer of security to your apps with Supabase Auth multi-factor authentication.+---++import { Mermaid } from 'mdx-mermaid/Mermaid';++:::note+Multi-Factor Authentication is in early access preview only. Although we+believe it is production ready, APIs and some behavior may change based on+feedback we receive in the preview period.+:::++Multi-factor authentication (MFA), sometimes called two-factor+authentication (2FA), adds an additional layer of security to your+application by verifying their identity through+additional verification steps.++It is considered a best practice to use MFA for your applications.++Users with weak passwords or compromised social login accounts are+prone to malicious account takeovers. These can be prevented with+MFA because they require the user to provide proof of+both of these:++- Something they know.+Password, or access to a social-login account.+- Something they have.+Access to an authenticator app (a.k.a. TOTP), mobile phone or recovery code.++## Overview++Supabase Auth implements only Time-based One Time Factor(TOTP) multi-factor authentication. This type of+multi-factor authentication uses a timed one-time password generated from an+authenticator app in the control of users.++Applications using MFA require two important flows:++1. **Enrollment flow.**+This lets users set up and control MFA in your app.+2. **Authentication flow.**+This lets users sign in using any factors after the conventional login step.++Supabase Auth provides:+- **Enrollment API** - build rich user interfaces for adding and removing factors.+- **Challenge and Verify APIs** - securely verify that the user has access to a factor.+- **List Factors API** - build rich user interfaces for signing in with additional factors.++Below is a flow chart illustrating how these APIs work together to enable MFA+features in your app.++<Mermaid chart={`+graph TD;+ InitS((Setup flow)) --> SAAL1[/Session is AAL1/] --> Enroll[Enroll API] --> ShowQR[Show QR code] --> Scan([User: Scan QR code in authenticator]) --> Enter([User: Enter code]) --> Verify[Challenge + Verify API] --> Check{{Is code correct?}}+ Check -->|Yes| AAL2[/Upgrade to AAL2/] --> Done((Done))+ Check -->|No| Enter+ InitA((Login flow)) --> SignIn([User: Sign-in]) --> AAL1[/Upgrade to AAL1/] --> ListFactors[List Factors API]+ ListFactors -->|1 or more factors| OpenAuth([User: Open authenticator]) --> Enter+ ListFactors -->|0 factors| Setup[[Setup flow]]+`} />++These sets of APIs let you control the MFA experience that works for you. You+can create flows where MFA is optional, mandatory for all or only specific+groups of users.++Once users have enrolled or signed-in with a factor, Supabase Auth adds+additional metadata to the user's access token (JWT) that your application can+use to allow or deny access.++This information is represented by an [Authenticator Assurance+Level](https://pages.nist.gov/800-63-3-Implementation-Resources/63B/AAL/), a+standard measure about the assurance Supabase Auth has of the user's identity+for that particular session. There are two levels recognized today:++1. **Assurance Level 1: `aal1`**+Means that the user's identity was verified using a conventional login method+such as email+password, magic link, one-time password, phone auth or social+login.+2. **Assurance Level 2: `aal2`**+Means that the user's identity was additionally verified using at least one+second factor, such as a TOTP code.++This assurance level is encoded in the `aal` claim in the JWT associated with+the user. By decoding this value you can create custom authorization rules in+your frontend, backend and database that will enforce the MFA policy that works+for your application. JWTs without an `aal` claim are at the `aal1` level.++## Adding to your app++Adding MFA to your app involves these three steps:++1. **Add enrollment flow.**+You need to provide a UI within your app that your users will be able to set-up+MFA in. You can add this right after sign-up, or as part of a separate flow in+the settings portion of your app.+2. **Add challenge step to login.**+If a user has set-up MFA, your app's login flow needs to present a challenge+screen to the user asking them to prove they have access to the additional+factor.+3. **Enforce rules for MFA logins.**+Once your users have a way to enroll and log in with MFA, you need to enforce+authorization rules across your app: on the frontend, backend, API servers or+Row-Level Security policies.++### Add enrollment flow++An enrollment flow provides a UI for users to set up additional authentication factors.+Most applications add the enrollment flow in two places within their app:++1. Right after login or sign up.+This lets users quickly set up MFA immediately after they log in or create an+account. We recommend encouraging all users to set up MFA if that makes sense+for your application. Many applications offer this as an opt-in step in an+effort to reduce onboarding friction.+2. From within a settings page.+Allows users to set up, disable or modify their MFA settings.++We recommend building one generic flow that you can reuse in both cases with+minor modifications.++Enrolling a factor for use with MFA takes three steps:++1. Call `supabase.auth.mfa.enroll()`.+This method returns a QR code and a secret. Display the QR+code to the user and ask them to scan it with their authenticator application.+If they are unable to scan the QR code, show the secret in plain text which+they can type or paste into their authenticator app.+2. Calling the `supabase.auth.mfa.challenge()` API.+This prepares Supabase Auth to accept a verification code from the user+and returns a challenge ID.+3. Calling the `supabase.auth.mfa.verify()` API.+This verifies that the user has indeed added the secret from step (1) into+their app and is working correctly. If the verification succeeds, the factor+immediately becomes active for the user account. If not, you should repeat+steps 2 and 3.++#### Example: React++Below is an example that creates a new `EnrollMFA` component that illustrates+the important pieces of the MFA enrollment flow.++- When the component appears on screen, the `supabase.auth.mfa.enroll()` API is+ called once to start the process of enrolling a new factor for the current+user.+- This API returns a QR code in the SVG format, which is shown on screen using+ a normal `<img>` tag by encoding the SVG as a data URL.+- Once the user has scanned the QR code with their authenticator app, they+ should enter the verification code within the `verifyCode` input field and+click on `Enable`.+- A challenge is created using the `supabase.auth.mfa.challenge()` API and the+ code from the user is submitted for verification using the+`supabase.auth.mfa.verify()` challenge.+- `onEnabled` is a callback that notifies the other components that enrollment+ has completed.+- `onCancelled` is a callback that notifies the other components that the user+ has clicked the `Cancel` button.++```tsx+/**+ * EnrollMFA shows a simple enrollment dialog. When shown on screen it calls+ * the `enroll` API. Each time a user clicks the Enable button it calls the+ * `challenge` and `verify` APIs to check if the code provided by the user is+ * valid.+ * When enrollment is successful, it calls `onEnrolled`. When the user clicks+ * Cancel the `onCancelled` callback is called.+ */+export function EnrollMFA({+ onEnrolled,+ onCancelled,+}: {+ onEnrolled: () => void;+ onCancelled: () => void;+}) {+ const [factorId, setFactorId] = useState("");+ const [qr, setQR] = useState(""); // holds the QR code image SVG+ const [verifyCode, setVerifyCode] = useState(""); // contains the code entered by the user+ const [error, setError] = useState(""); // holds an error message++ const onEnableClicked = () => {+ setError("");++ (async () => {+ const challenge = await supabase.auth.mfa.challenge({ factorId });+ if (challenge.error) {+ setError(challenge.error.message);+ throw challenge.error;+ }++ const challengeId = challenge.data.id;++ const verify = await supabase.auth.mfa.verify({+ factorId,+ challengeId,+ code: verifyCode,+ });+ if (verify.error) {+ setError(verify.error.message);+ throw verify.error;+ }++ onEnrolled();+ })();+ };++ useEffect(() => {+ (async () => {+ const { data, error } = await supabase.auth.mfa.enroll({+ factorType: "totp",+ });+ if (error) {+ throw error;+ }++ setFactorId(data.id);++ // Supabase Auth returns an SVG QR code which you can convert into a data+ // URL that you can place in an <img> tag.+ setQR(data.totp.qr_code);+ })();+ }, []);++ return (+ <>+ {error && <div className="error">{error}</div>}+ <img src={qr} />+ <input+ type="text"+ value={verifyCode}+ onChange={(e) => setVerifyCode(e.target.value.trim())}+ />+ <input type="button" value="Enable" onClick={onEnableClicked} />+ <input type="button" value="Cancel" onClick={onCancelled} />+ </>+ );+}+```++### Add challenge step to login++Once a user has logged in via their first factor (email+password, magic link,+one time password, social login...) you need to perform a check if any+additional factors need to be verified.++This can be done by using the+`supabase.auth.mfa.getAuthenticatorAssuranceLevel()` API. When the user signs+in and is redirected back to your app, you should call this method to extract+the user's current and next authenticator assurance level (AAL).++Therefore if you receive a `currentLevel` which is `aal1` but a `nextLevel`+of `aal2`, the user should be given the option to go through MFA.++Below is a table that explains the combined meaning.++| Current Level | Next Level | Meaning |+| -------------:|:---------- |:------------------------------------------ |+| `aal1` | `aal1` | User does not have MFA enrolled. |+| `aal1` | `aal2` | User has an MFA factor enrolled but has not verified it. |+| `aal2` | `aal2` | User has verified their MFA factor. |+| `aal2` | `aal1` | User has disabled their MFA factor. (Stale JWT.) |++#### Example: React++Adding the challenge step to login depends heavily on the architecture of your+app. However, a fairly common way to structure React apps is to have a large+component (often named `App`) which contains most of the authenticated+application logic.++This example will wrap this component with logic that will show an MFA+challenge screen if necessary, before showing the full application. This is+illustrated in the `AppWithMFA` example below.++```tsx+function AppWithMFA() {+ const [readyToShow, setReadyToShow] = useState(false);+ const [showMFAScreen, setShowMFAScreen] = useState(false);++ useEffect(() => {+ (async () => {+ try {+ const { data, error } =+ await supabase.auth.mfa.getAuthenticatorAssuranceLevel();+ if (error) {+ throw error;+ }++ console.log(data);++ if (data.nextLevel === "aal2" && data.nextLevel !== data.currentLevel) {+ setShowMFAScreen(true);+ }+ } finally {+ setReadyToShow(true);+ }+ })();+ }, []);++ if (readyToShow) {+ if (showMFAScreen) {+ return <AuthMFA />;+ }++ return <App />;+ }++ return <></>;+}+```++- `supabase.auth.mfa.getAuthenticatorAssuranceLevel()` does return a promise.+ Don't worry, this is a very fast method (microseconds) as it rarely uses the+network.+- `readyToShow` only makes sure the AAL check completes before showing any+ application UI to the user.+- If the current level can be upgraded to the next one, the MFA screen is+ shown.+- Once the challenge is successful, the `App` component is finally rendered on+ screen.++Below is the component that implements the challenge and verify logic.++```tsx+function AuthMFA() {+ const [verifyCode, setVerifyCode] = useState("");+ const [error, setError] = useState("");++ const onSubmitClicked = () => {+ setError("");++ (async () => {+ const factors = await supabase.auth.mfa.listFactors();+ if (factors.error) {+ throw factors.error;+ }++ const totpFactor = factors.data.totp[0];++ if (!totpFactor) {+ throw new Error("No TOTP factors found!");+ }++ const factorId = totpFactor.id;++ const challenge = await supabase.auth.mfa.challenge({ factorId });+ if (challenge.error) {+ setError(challenge.error.message);+ throw challenge.error;+ }++ const challengeId = challenge.data.id;++ const verify = await supabase.auth.mfa.verify({+ factorId,+ challengeId,+ code: verifyCode,+ });+ if (verify.error) {+ setError(verify.error.message);+ throw verify.error;+ }+ })();+ };++ return (+ <>+ <div>Please enter the code from your authenticator app.</div>+ {error && <div className="error">{error}</div>}+ <input+ type="text"+ value={verifyCode}+ onChange={(e) => setVerifyCode(e.target.value.trim())}+ />+ <input type="button" value="Submit" onClick={onSubmitClicked} />+ </>+ );+}+```++- You can extract the available MFA factors for the user by calling+ `supabase.auth.mfa.listFactors()`. Don't worry this method is also very quick+and rarely uses the network.+- If `listFactors()` returns more than one factor (or of a different type) you+ should present the user with a choice. For simplicity this is not shown in+the example.+- Each time the user presses the "Submit" button a new challenge is created for+ the chosen factor (in this case the first one) and it is immediately+verified. Any errors are displayed to the user.+- On successful verification, the client library will refresh the session in+ the background automatically and finally call the `onSuccess` callback, which+will show the authenticated `App` component on screen.++### Enforce rules for MFA logins++Adding MFA to your app's UI does not in-and-of-itself offer a higher level of+security to your users. You also need to enforce the MFA rules in your+application's database, APIs and server-side rendering.++Depending on your application's needs, there are three ways you can choose to+enforce MFA.++1. **Enforce for all users (new and existing).**+Any user account will have to enroll MFA to continue using your app.+The application will not allow access without going through MFA first.+2. **Enforce for new users only.**+Only new users will be forced to enroll MFA, while old users will be encouraged+to do so.+The application will not allow access for new users without going through MFA+first.+3. **Enforce only for users that have opted-in.**+Users that want MFA can enroll in it and the application will not allow access+without going through MFA first.++#### Database++Your app should sufficiently deny or allow access to tables or rows based on+the user's current and possible authenticator levels.++:::warning+PostgreSQL has two types of policies: permissive and restrictive. This guide+uses restrictive policies. Make sure you don't omit the `as restrictive`+clause.+:::++##### Enforce for all users (new and existing)++If your app falls under this case, this is a template Row Level Security policy+you can apply to all your tables:++```sql+create policy "Policy name."+ on table_name+ as restrictive+ to authenticated+ using (auth.jwt()->>'aal' = 'aal2');+```++- Here the policy will not accept any JWTs with an `aal` claim other than+ `aal2`, which is the highest authenticator assurance level.+- **Using `as restrictive` ensures this policy will restrict all commands on the+ table regardless of other policies!**++##### Enforce for new users only++If your app falls under this case, the rules get more complex. User accounts+created past a certain timestamp must have a `aal2` level to access the+database.++```sql+create policy "Policy name."+ on table_name+ as restrictive -- very important!+ to authenticated+ using+ (array[auth.jwt()->>'aal'] <@ (+ select+ case+ when created_at >= '2022-12-12T00:00:00Z' then array['aal2']+ else array['aal1', 'aal2', NULL]+ end as aal+ from auth.users+ where auth.uid() = id));+```++- The policy will accept both `aal1` and `aal2` for users with a `created_at`+ timestamp prior to 12th December 2022 at 00:00 UTC, but will only accept+`aal2` for all other timestamps.+- The `<@` operator is PostgreSQL's ["contained in"+ operator.](https://www.postgresql.org/docs/current/functions-array.html)+- `NULL` appears because some JWTs originating from prior to the introduction+ of MFA in Supabase Auth will not contain an `aal` claim.+- **Using `as restrictive` ensures this policy will restrict all commands on the+ table regardless of other policies!**++##### Enforce only for users that have opted-in++Users that have enrolled MFA on their account are expecting that your+application only works for them if they've gone through MFA.++```sql+create policy "Policy name."+ on table_name+ as restrictive -- very important!+ to authenticated+ using (+ array[auth.jwt()->>'aal'] <@ (+ select+ case+ when count(id) > 0 then array['aal2']+ else array['aal1', 'aal2', NULL]+ end as aal+ from auth.mfa_factors+ where auth.uid() = user_id and status = 'verified'+ ));+```++- The policy will only accept only `aal2` when the user has at least one MFA+ factor verified.+- Otherwise, it will accept both `aal1` and `aal2`.+- The `<@` operator is PostgreSQL's ["contained in"+ operator.](https://www.postgresql.org/docs/current/functions-array.html)+- `NULL` appears because some JWTs originating from prior to the introduction+ of MFA in Supabase Auth will not contain an `aal` claim.+- **Using `as restrictive` ensures this policy will restrict all commands on the+ table regardless of other policies!**++### Server-Side Rendering++:::tip+When using the Supabase JavaScript library in a server-side rendering context,+make sure you always create a new object for each request! This will prevent+you from accidentally rendering and serving content belonging to different+users.+:::++It is possible to enforce MFA on the Server-Side Rendering level. However, this+can be tricky do to well.++You can use the `supabase.auth.mfa.getAuthenticatorAssuranceLevel()` and+`supabase.auth.mfa.listFactors()` APIs to identify the AAL level of the session+and any factors that are enabled for a user, similar to how you would use these+on the browser.++However, encountering a different AAL level on the server may not actually be a+security problem. Consider these likely scenarios:++1. User signed-in with a conventional method but closed their tab on the MFA+flow.+2. User forgot a tab open for a very long time. (This happens more often than+you might imagine.)+3. User has lost their authenticator device and is confused about the next+steps.++We thus recommend you redirect users to a page where they can authenticate+using their additional factor, instead of rendering a HTTP 401 Unauthorized or+HTTP 403 Forbidden content.++### APIs++If your application uses the Supabase Database, Storage or Edge Functions, just+using Row Level Security policies will give you sufficient protection. In the+event that you have other APIs that you wish to protect, follow these general+guidelines:++1. **Use a good JWT verification and parsing library for your language.**+This will let you securely parse JWTs and extract their claims.+2. **Retrieve the `aal` claim from the JWT and compare its value according to+your needs.**+If you've encountered an AAL level that can be increased, ask the user to+continue the login process instead of logging them out.+3. **Use the `https://<project-ref>.supabase.co/rest/v1/auth/factors` REST+endpoint to identify if the user has enrolled any MFA factors.**+Only `verified` factors should be acted upon.++## Frequently asked questions++### Why is there a challenge and verify API when challenge does not do much?++TOTP is not going to be the only MFA factor Supabase Auth is going to support+in the future. By separating out the challenge and verify steps, we're making+the library forward compatible with new factors we may add in the future --+such as SMS or WebAuthn. For example, for SMS the `challenge` endpoint would+actually send out the SMS with the authentication code.++### What's inside the QR code?++The TOTP QR code encodes a URI with the `otpauth` scheme. It was [initially+introduced by Google+Authenticator](https://github.com/google/google-authenticator/wiki/Key-Uri-Format)+but is now universally accepted by all authenticator apps.++### How do I check _when_ a user went through MFA?++Access tokens issued by Supabase Auth contain an `amr` (Authentication Methods+Reference) claim. It is an array of objects that indicate what authentication+methods the user has used so far.++For example, the following structure describes a user that first signed in with+a password-based method, and then went through TOTP MFA 2 minutes and 12+seconds later. The entries are ordered most recent method first!++```json+{+ "amr": [+ {+ "method": "mfa/totp",+ "timestamp": 1666086056+ },+ {+ "method": "password",+ "timestamp": 1666085924+ }+ ]+}+```++Use the `supabase.auth.getAuthenticatorAssuranceLevel()` method to get easy+access to this information in your browser app.++You can use this PostgreSQL snippet in RLS policies, too:++```sql+json_query_path(auth.jwt(), '$.amr[0]')+```++- [`json_query_path(json,+ path)`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE)+is a function that allows access to elements in a JSON object according to a+[SQL/JSON+path](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-SQLJSON-PATH).+- `$.amr[0]` is a SQL/JSON path expression that fetches the most recent+ authentication method in the JWT.++Once you have extracted the most recent entry in the array, you can compare the+`method` and `timestamp` to enforce stricter rules.++Currently recognized methods are:++- `password` - any password based sign in.+- `otp` - any one-time password based sign in (email code, SMS code, magic+ link).+- `oauth` - any OAuth based sign in (social login).+- `mfa/totp` - a TOTP additional factor.++This list will expand in the future.+diff --git a/apps/temp-docs/docs/guides/auth/auth-notion.mdx b/apps/temp-docs/docs/guides/auth/auth-notion.mdxnew file mode 100644index 00000000000..31b5d76e778--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-notion.mdx@@ -0,0 +1,97 @@+---+id: auth-notion+title: 'Login with Notion'+description: Add Notion OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable Notion Auth for your project, you need to set up a Notion Application and add the Application OAuth credentials to your Supabase Dashboard.++## Overview++Setting up Notion logins for your application consists of 3 parts:++- Create and configure a Notion Application [Notion Developer Portal](https://www.notion.so/my-integrations)+- Retrieve your OAuth client ID and OAuth client secret and add them to your [Supabase Project](https://app.supabase.com)+- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)++## Create your notion integration++- Go to [developers.notion.com](https://developers.notion.com/).+- Click "View my integrations" and login.++++- Once logged in, go to [notion.so/my-integrations](https://notion.so/my-integrations) and create a new integration.+- When creating your integration, ensure that you select "Public integration" under "Integration type" and "Read user information including email addresses" under "Capabilities".+- You will need to add a redirect uri, see [Add the redirect uri](#add-the-redirect-uri)+- Once you've filled in the necessary fields, click "Submit" to finish creating the integration.++++## Add the redirect URI++- After selecting "Public integration", you should see an option to add "Redirect URIs".++++You can retrieve the redirect uri with the following steps:++- Go to your [Supabase Project Dashboard](https://app.supabase.com).+- Click on the `Settings` icon at the bottom of the left sidebar.+- Click on `API` in the list.+- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.+- Add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.++Your redirect uri should look like the following: `https://<project-ref>.supabase.co/auth/v1/callback`++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Add your Notion credentials into your Supabase Project++- Once you've created your notion integration, you should be able to retrieve the "OAuth client ID" and "OAuth client secret" from the "OAuth Domain and URIs" tab.++++- Go to your [Supabase Project Dashboard](https://app.supabase.com)+- In the left sidebar, click the `Authentication` icon (near the top)+- Click `Settings` from the list to go to the `Authentication Settings` page+- Under `External OAuth Providers` turn `Notion Enabled` to ON+- Enter the "OAuth client ID" and "OAuth client secret" obtained in the `client id` and `client secret` fields.+- Click `Save`++## Add login code to your client app++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `notion` as the `provider`:++```js+async function signInWithNotion() {+ const { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'notion',+ })+}+```++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- [Supabase Account - Free Tier OK](https://supabase.com)+- [Supabase JS Client](https://github.com/supabase/supabase-js)+- [Notion Account](https://notion.so)+- [Notion Developer Portal](https://www.notion.so/my-integrations)diff --git a/apps/temp-docs/docs/guides/auth/auth-slack.mdx b/apps/temp-docs/docs/guides/auth/auth-slack.mdxindex cecc8ad6cd7..c00e377747b 100644--- a/apps/temp-docs/docs/guides/auth/auth-slack.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-slack.mdx@@ -5,7 +5,7 @@ description: Add Slack OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Slack Auth for your project, you need to set up a Slack OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,35 +14,38 @@ To enable Slack Auth for your project, you need to set up a Slack OAuth applicatSetting up Slack logins for your application consists of 3 parts:- Create and configure a Slack Project and App on the [Slack Developer Dashboard](https://api.slack.com/apps).-- Add your Slack `API Key` and `API Secret Key` to your [Supabase Project](https://supabase.com).+- Add your Slack `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com).- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js).-## Steps--### Access your Slack Developer account+## Access your Slack Developer account- Go to [api.slack.com](https://api.slack.com/apps).- Click on `Your Apps` at the top right to log in.-+-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Slack OAuth app+## Create a Slack OAuth app- Go to [api.slack.com](https://api.slack.com/apps).- Click on `Create an App`@@ -66,37 +69,29 @@ Under `Redirect URLs`:- Paste your `Callback URL` then click `Add`- Click `Save URLs`-### Enter your Slack credentials into your Supabase Project+## Enter your Slack credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- In the left sidebar, click the `Authentication` icon (near the top).- Click `Settings` from the list to go to the `Authentication Settings` page.- Enter the final (hosted) URL of your app under `Site URL` (this is important).- Under `External OAuth Providers` turn `Slack Enabled` to ON.-- Enter your `API Key` (`client_id`) and `API Secret Key` (`client_secret`) saved in the previous step.+- Enter your `Client ID` (`client_id`) and `Client Secret` (`client_secret`) saved in the previous step.- Click `Save`.-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers).--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'slack',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `slack` as the `provider`:```jsasync function signInWithSlack() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'slack',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-spotify.mdx b/apps/temp-docs/docs/guides/auth/auth-spotify.mdxindex 9b4a4642bc4..cf282bea973 100644--- a/apps/temp-docs/docs/guides/auth/auth-spotify.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-spotify.mdx@@ -5,7 +5,7 @@ description: Add Spotify OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Spotify Auth for your project, you need to set up a Spotify OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,35 +14,38 @@ To enable Spotify Auth for your project, you need to set up a Spotify OAuth applSetting up Spotify logins for your application consists of 3 parts:- Create and configure a Spotify Project and App on the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/).-- Add your Spotify `API Key` and `API Secret Key` to your [Supabase Project](https://supabase.com).+- Add your Spotify `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com).- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js).-## Steps--### Access your Spotify Developer account+## Access your Spotify Developer account- Log into [Spotify](https://spotify.com)- Access the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard)-+-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Spotify OAuth app+## Create a Spotify OAuth app- Log into [Spotify](https://spotify.com).- Go to the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard)@@ -61,37 +64,29 @@ Under `Redirect URIs`:- Click `Add`- Click `Save` at the bottom-### Enter your Spotify credentials into your Supabase Project+## Enter your Spotify credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- In the left sidebar, click the `Authentication` icon (near the top).- Click `Settings` from the list to go to the `Authentication Settings` page.- Enter the final (hosted) URL of your app under `Site URL` (this is important).- Under `External OAuth Providers` turn `Spotify Enabled` to ON.-- Enter your `API Key` (`client_id`) and `API Secret Key` (`client_secret`) saved in the previous step.+- Enter your `Client ID` (`client_id`) and `Client Secret` (`client_secret`) saved in the previous step.- Click `Save`.-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers).--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'spotify',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `spotify` as the `provider`:```jsasync function signInWithSpotify() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'spotify',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-twilio.mdx b/apps/temp-docs/docs/guides/auth/auth-twilio.mdxindex d61e17d75c0..f5c0e53cb0a 100644--- a/apps/temp-docs/docs/guides/auth/auth-twilio.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-twilio.mdx@@ -5,16 +5,16 @@ description: How to set up and use Mobile OTP with Twilio and Supabase.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'## Overview-In this guide we'll show you how to authenticate your users with SMS based OTP (One-Time Password) tokens.+In this guide we'll show you how to authenticate your users with SMS based One-Time Password (OTP) tokens.There are two reasons to use Supabase SMS OTP tokens:-- You want users to log in with mobile + password, and the mobile should be verified via SMS-- You want users to log in with mobile ONLY (i.e. passwordless login)+- You want users to log in with mobile number + password, and the mobile number should be verified via SMS+- You want users to log in with mobile number ONLY (i.e. passwordless login)We'll cover:@@ -24,21 +24,20 @@ We'll cover:What you'll need:-- A twilio account (sign up here: https://www.twilio.com/try-twilio)+- A Twilio account (sign up here: https://www.twilio.com/try-twilio)- A Supabase project (create one here: https://app.supabase.com)- A mobile phone capable of receiving SMS## Video-<iframe- className="video-with-border w-full"- width="640"- height="385"- src="https://www.youtube-nocookie.com/embed/akScoPO01bc"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen-></iframe>+<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/akScoPO01bc"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>## Steps@@ -48,18 +47,18 @@ Start by logging into your Twilio account and starting a new project: https://wwGive your project a name and verify the mobile number you'll be using to test with. This is the number that will be receiving the SMS OTPs.--++Select 'SMS', 'Identity & Verification', and 'With code' as options on the welcome form.-+-When you're back on the https://www.twilio.com/console screen, you need to scroll down and click 'Get a trial phone number' - this is the number that you'll be sending SMSs from.+When you're back on the [Twilio console screen](https://www.twilio.com/console), you need to scroll down and click 'Get a trial phone number' - this is the number that you'll be sending SMSs from.-+-+You should now be able to see all three values you'll need to get started:@@ -67,19 +66,19 @@ You should now be able to see all three values you'll need to get started:- Auth Token- Sender Phone Number-+Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/settings).-You should see an option to enable Phone Signup.+You should see an option to enable Phone Signup:-+Toggle it on, and copy the 3 values over from the twilio dashboard. Click save.Note: for "Twilio Message Service SID" you can use the Sender Phone Number generated above.-+Now the backend should be setup, we can proceed to add our client-side code!@@ -89,21 +88,23 @@ The SMS message sent to a phone containing an OTP code can be customized. This iGo to Auth > Templates page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/templates).-Use the variable `.Code` in the template to display the code.+Use the variable `.Code` in the template to display the OTP code. Here's an example in the SMS template.++### Using OTP with password based logins-In this use scenario we'll be using the user's mobile phone number as an alternative to an email address when signing up along with a password. You may want to think hard about the permanency of this however. It is not uncommon for mobile phone numbers to be recycled by phone networks when users cancel their phone contracts or move countries, therefore granting access to the user's account to whoever takes over the phone number in the future. Soon we'll add multi-factor auth, which will mitigate this risk, but for now you may want to give some thought to allowing your users to recover their account by some other means in an emergency.+In this scenario we'll be using the user's mobile phone number and a corresponding password as an alternative to signing up with an email address. Note: please thoroughly consider potential security implications when signing up with a combination of phone number and password. Phone numbers are sometimes recycled by phone networks when users cancel their phone contracts or move countries, thereby granting access to the user's account to the subsequent owner of the phone number. In the near future Supabase will support multifactor authentication, which will mitigate this risk, but for now you may want to consider allowing your users to recover their account by some other means in an emergency.Using supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { user, error } = await supabase.auth.signUp({@@ -112,8 +113,8 @@ let { user, error } = await supabase.auth.signUp({})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \@@ -125,7 +126,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \}'```-</TabsPanel>+</TabItem></Tabs>The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account.@@ -133,22 +134,23 @@ The user will now receive an SMS with a 6-digit pin that you will need to receivYou should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { session, error } = await supabase.auth.verifyOTP({phone: '+13334445555',token: '123456',+ type: 'sms',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \@@ -161,7 +163,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \}'```-</TabsPanel>+</TabItem></Tabs>If successful the user will now be logged in and you should receive a valid session like:@@ -180,22 +182,22 @@ The access token can be sent in the Authorization header as a Bearer token for aAlso now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```js-let { user, error } = await supabase.auth.signIn({+let { user, error } = await supabase.auth.signInWithPassword({phone: '+13334445555',password: 'some-password',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=password' \@@ -207,7 +209,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=}'```-</TabsPanel>+</TabItem></Tabs>### Using OTP as a passwordless sign-in mechanism@@ -217,21 +219,21 @@ In this scenario you are granting your user's the ability to login to their accoIn javascript we can use the `signIn` method with a single parameter: `phone`<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```js-let { user, error } = await supabase.auth.signIn({+let { user, error } = await supabase.auth.signInWithOtp({phone: '+13334445555',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \@@ -242,28 +244,29 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \}'```-</TabsPanel>+</TabItem></Tabs>The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method:<Tabs-defaultActiveId="JS"+defaultValue="JS"values={[- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'HTTP', value: 'HTTP'},]}>-<TabsPanel id="JS" label="JS">+<TabItem value="JS">```jslet { session, error } = await supabase.auth.verifyOTP({phone: '+13334445555',token: '123456',+ type: 'sms',})```-</TabsPanel>-<TabsPanel id="HTTP" label="HTTP">+</TabItem>+<TabItem value="HTTP">```bashcurl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \@@ -276,7 +279,7 @@ curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \}'```-</TabsPanel>+</TabItem></Tabs>and the response should also be the same as above:diff --git a/apps/temp-docs/docs/guides/auth/auth-twitch.mdx b/apps/temp-docs/docs/guides/auth/auth-twitch.mdxindex c2071c3c22d..56a67e6c82c 100644--- a/apps/temp-docs/docs/guides/auth/auth-twitch.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-twitch.mdx@@ -5,7 +5,7 @@ description: Add Twitch OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Twitch Auth for your project, you need to set up a Twitch Application and add the Application OAuth credentials to your Supabase Dashboard.@@ -14,67 +14,70 @@ To enable Twitch Auth for your project, you need to set up a Twitch ApplicationSetting up Twitch logins for your application consists of 3 parts:- Create and configure a Twitch Application [Twitch Developer Console](https://dev.twitch.tv/console)-- Add your Twitch OAuth Consumer keys to your [Supabase Project](https://supabase.com)+- Add your Twitch OAuth Consumer keys to your [Supabase Project](https://app.supabase.com)- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)-## Steps--### Access your Twitch Developer account+## Access your Twitch Developer account- Go to [dev.twitch.tv](https://dev.twitch.tv).- Click on `Log in with Twitch` at the top right to log in.- If you have not already enabled 2-Factor Authentication for your Twitch Account, you will need to do that at [Twitch Security Settings](https://www.twitch.tv/settings/security) before you can continue.-+- Once logged in, go to the [Twitch Developer Console](https://dev.twitch.tv/console).-+-### Find your callback URL+## Find your callback URLIn the next step you require a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Twitch Application+## Create a Twitch Application-+- Click on `+ Register Your Application` at the top right.-+- Enter the name of your application.- Type or paste your `OAuth Redirect URL` (the callback URL from the previous step.)- Select a category for your app.- Check the Captcha box and click `Create`.-### Retrieve your Twitch OAuth Client ID and Client Secret+## Retrieve your Twitch OAuth Client ID and Client Secret- Click `Manage` at the right of your application entry in the list.-+- Copy your Client ID.- Click `New Secret` to create a new Client Secret.- Copy your Client Secret.-+-### Add your Twitch credentials into your Supabase Project+## Add your Twitch credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com)+- Go to your [Supabase Project Dashboard](https://app.supabase.com)- In the left sidebar, click the `Authentication` icon (near the top)- Click `Settings` from the list to go to the `Authentication Settings` page- Enter the final (hosted) URL of your app under `Site URL` (this is important)@@ -82,27 +85,19 @@ In the next step you require a callback URL, which looks like this:- Enter your `client_id` and `client_secret` saved in the previous step- Click `Save`-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers)--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'twitch',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `twitch` as the `provider`:```jsasync function signInWithTwitch() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'twitch',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-twitter.mdx b/apps/temp-docs/docs/guides/auth/auth-twitter.mdxindex 7be907d29e0..88448a12eeb 100644--- a/apps/temp-docs/docs/guides/auth/auth-twitter.mdx+++ b/apps/temp-docs/docs/guides/auth/auth-twitter.mdx@@ -5,7 +5,7 @@ description: Add Twitter OAuth to your Supabase project---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'To enable Twitter Auth for your project, you need to set up a Twitter OAuth application and add the application credentials to your Supabase Dashboard.@@ -14,35 +14,38 @@ To enable Twitter Auth for your project, you need to set up a Twitter OAuth applSetting up Twitter logins for your application consists of 3 parts:- Create and configure a Twitter Project and App on the [Twitter Developer Dashboard](https://developer.twitter.com/en/portal/dashboard).-- Add your Twitter `API Key` and `API Secret Key` to your [Supabase Project](https://supabase.com).+- Add your Twitter `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com).- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js).-## Steps--### Access your Twitter Developer account+## Access your Twitter Developer account- Go to [developer.twitter.com](https://developer.twitter.com).- Click on `Sign in` at the top right to log in.-+-### Find your callback URL+## Find your callback URLThe next step requires a callback URL, which looks like this:`https://<project-ref>.supabase.co/auth/v1/callback`-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- Click on the `Settings` icon at the bottom of the left sidebar.- Click on `API` in the list.- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-### Create a Twitter OAuth app+## Create a Twitter OAuth app- Click `+ Create Project`.- Enter your project name, click `Next`.@@ -62,9 +65,9 @@ The next step requires a callback URL, which looks like this:- Enter your `Privacy policy URL`.- Click `Save`.-### Enter your Twitter credentials into your Supabase Project+## Enter your Twitter credentials into your Supabase Project-- Go to your [Supabase Project Dashboard](https://supabase.com).+- Go to your [Supabase Project Dashboard](https://app.supabase.com).- In the left sidebar, click the `Authentication` icon (near the top).- Click `Settings` from the list to go to the `Authentication Settings` page.- Enter the final (hosted) URL of your app under `Site URL` (this is important).@@ -72,27 +75,19 @@ The next step requires a callback URL, which looks like this:- Enter your `API Key` (`client_id`) and `API Secret Key` (`client_secret`) saved in the previous step.- Click `Save`.-### Add login code to your client app--The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers).--```js-const { user, session, error } = await supabase.auth.signIn({- provider: 'twitter',-})-```+## Add login code to your client app-Add this function which you can call from a button, link, or UI element.+When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `twitter` as the `provider`:```jsasync function signInWithTwitter() {- const { user, session, error } = await supabase.auth.signIn({+ const { data, error } = await supabase.auth.signInWithOAuth({provider: 'twitter',})}```-To log out:+When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:```jsasync function signout() {diff --git a/apps/temp-docs/docs/guides/auth/auth-vonage.mdx b/apps/temp-docs/docs/guides/auth/auth-vonage.mdxnew file mode 100644index 00000000000..10fa9378c0c--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-vonage.mdx@@ -0,0 +1,274 @@+---+id: auth-vonage+title: Phone Auth with Vonage+description: How to set up and use Mobile OTP with Vonage and Supabase.+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++## Overview++In this guide we'll show you how to authenticate your users with SMS based OTP (One-Time Password) tokens.++There are two reasons to use Supabase SMS OTP tokens:++- You want users to log in with mobile + password, and the mobile should be verified via SMS+- You want users to log in with mobile ONLY (i.e. passwordless login)++We'll cover:++- [Getting your Vonage API Key](#finding-your-vonage-api-key)+- [Using OTP with password based logins](#using-otp-with-password-based-logins)+- [Using OTP as a passwordless sign-in mechanism](#using-otp-as-a-passwordless-sign-in-mechanism)++What you'll need:++- A Vonage account (sign up here: https://dashboard.nexmo.com/sign-up)+- A Supabase project (create one here: https://app.supabase.com)+- A mobile phone capable of receiving SMS++## Steps++### Getting your Vonage credentials++Start by logging into your Vonage Dashboard at https://dashboard.nexmo.com/++You will see you API Key and API Secret here, which is actually all you need to get started.++In most countries, a phone number is actually optional and you can also use any Alphanumeric Sender ID of up to 11 characters length (8 for India) as a Sender ID (from). This means you do not need a number to test with in most cases.++To find out more about supported countries for Alphanumeric Sender ID, check this overview: https://help.nexmo.com/hc/en-us/articles/115011781468-SMS-Features-Overview-Outbound-only-++Hint: Some countries might need a Sender ID Registration to allow sending with an Alphanumeric Sender ID. You can find this information in the help article as well. If Alpha Sender IDs are not supported, you will need to buy a phone number.++### Getting a phone number (optional)++If you want a phone number to send SMS from, you can buy one from the Vonage Dashboard under Numbers > Buy Numbers (https://dashboard.nexmo.com/buy-numbers).++Select the country you want a number for. You will need a mobile phone number with SMS or SMS+Voice capability. After you have bought the number, you will be able to send SMS from it.++### Configure Supabase++Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/settings).++You should see an option to enable Phone Signup.++Toggle it on, and copy the api key, api secret and optionally phone number values over from the Vonage dashboard. Click save.++Now the backend should be setup, we can proceed to add our client-side code!++#### SMS custom template++The SMS message sent to a phone containing an OTP code can be customized. This is useful if you need to mention a brand name or display a website address.++Go to Auth > Templates page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/templates).++Use the variable `.Code` in the template to display the code.++### Using OTP with password based logins++In this use scenario we'll be using the user's mobile phone number as an alternative to an email address when signing up along with a password. You may want to think hard about the permanency of this however. It is not uncommon for mobile phone numbers to be recycled by phone networks when users cancel their phone contracts or move countries, therefore granting access to the user's account to whoever takes over the phone number in the future.++Using supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`:++<Tabs+defaultValue="JS"+values={[+ {label: 'JavaScript', value: 'JS'},+ {label: 'HTTP', value: 'HTTP'},+]}>+<TabItem value="JS">++```js+let { user, error } = await supabase.auth.signUp({+ phone: '491512223334444',+ password: 'some-password',+})+```++</TabItem>+<TabItem value="HTTP">++```bash+curl -X POST 'https://xxx.supabase.co/auth/v1/signup' \+-H "apikey: SUPABASE_KEY" \+-H "Content-Type: application/json" \+-d '{+ "phone": "491512223334444",+ "password": "some-password"+}'+```++</TabItem>+</Tabs>++The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account.++You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`:++<Tabs+defaultValue="JS"+values={[+ {label: 'JavaScript', value: 'JS'},+ {label: 'HTTP', value: 'HTTP'},+]}>+<TabItem value="JS">++```js+let { session, error } = await supabase.auth.verifyOTP({+ phone: '491512223334444',+ token: '123456',+})+```++</TabItem>+<TabItem value="HTTP">++```bash+curl -X POST 'https://xxx.supabase.co/auth/v1/verify' \+-H "apikey: SUPABASE_KEY" \+-H "Content-Type: application/json" \+-d '{+ "type": "sms",+ "phone": "491512223334444",+ "token": "123456"+}'+```++</TabItem>+</Tabs>++If successful the user will now be logged in and you should receive a valid session like:++```json+{+ "access_token": "eyJxxx...",+ "token_type": "bearer",+ "expires_in": 3600,+ "refresh_token": "yyy..."+}+```++The access token can be sent in the Authorization header as a Bearer token for any CRUD operations on supabase-js. See our guide on [Row Level Security](/docs/guides/auth#row-level-security) for more info on restricting access on a user basis.++Also now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time:++<Tabs+defaultValue="JS"+values={[+ {label: 'JavaScript', value: 'JS'},+ {label: 'HTTP', value: 'HTTP'},+]}>+<TabItem value="JS">++```js+let { user, error } = await supabase.auth.signInWithPassword({+ phone: '491512223334444',+ password: 'some-password',+})+```++</TabItem>+<TabItem value="HTTP">++```bash+curl -X POST 'https://xxx.supabase.co/auth/v1/token?grant_type=password' \+-H "apikey: SUPABASE_KEY" \+-H "Content-Type: application/json" \+-d '{+ "phone": "491512223334444",+ "password": "some-password"+}'+```++</TabItem>+</Tabs>++### Using OTP as a passwordless sign-in mechanism++In this scenario you are granting your user's the ability to login to their account without needing to set a password on their account, all they have to do to log in is verify their mobile each time using the OTP.++In javascript we can use the `signIn` method with a single parameter: `phone`++<Tabs+defaultValue="JS"+values={[+ {label: 'JavaScript', value: 'JS'},+ {label: 'HTTP', value: 'HTTP'},+]}>+<TabItem value="JS">++```js+let { user, error } = await supabase.auth.signInWithOtp({+ phone: '491512223334444',+})+```++</TabItem>+<TabItem value="HTTP">++```bash+curl -X POST 'https://xxx.supabase.co/auth/v1/otp' \+-H "apikey: SUPABASE_KEY" \+-H "Content-Type: application/json" \+-d '{+ "phone": "491512223334444"+}'+```++</TabItem>+</Tabs>++The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method:++<Tabs+defaultValue="JS"+values={[+ {label: 'JavaScript', value: 'JS'},+ {label: 'HTTP', value: 'HTTP'},+]}>+<TabItem value="JS">++```js+let { session, error } = await supabase.auth.verifyOTP({+ phone: '491512223334444',+ token: '123456',+})+```++</TabItem>+<TabItem value="HTTP">++```bash+curl -X POST 'https://xxx.supabase.co/auth/v1/verify' \+-H "apikey: SUPABASE_KEY" \+-H "Content-Type: application/json" \+-d '{+ "type": "sms",+ "phone": "491512223334444",+ "token": "123456"+}'+```++</TabItem>+</Tabs>++and the response should also be the same as above:++```json+{+ "access_token": "eyJxxx...",+ "token_type": "bearer",+ "expires_in": 3600,+ "refresh_token": "yyy..."+}+```++The user does not have a password therefore will need to sign in via this method each time they want to access your service.++## Resources++- [Vonage Signup](https://dashboard.nexmo.com/sign-up)+- [Supabase Dashboard](https://app.supabase.com)+- [Supabase Row Level Security](/docs/guides/auth#row-level-security)diff --git a/apps/temp-docs/docs/guides/auth/auth-workos.mdx b/apps/temp-docs/docs/guides/auth/auth-workos.mdxnew file mode 100644index 00000000000..422666106ad--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-workos.mdx@@ -0,0 +1,92 @@+---+id: auth-workos+title: 'Login with WorkOS'+description: Add WorkOS OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable WorkOS Auth for your project, you need to set up WorkOS OAuth application and add the application credentials to your Supabase Dashboard.++## Overview++In this guide, we will cover how to use Supabase OAuth with WorkOS to implement Single-Sign-On(SSO).++The procedure consists of five broad steps:++- Create a new organization from your WorkOS Dashboard.+- Obtain the `Client ID` from the Configuration tab and configure redirect URI.+- Obtain the `WorkOS Secret` from the credentials tab.+- Connect a WorkOS Supported Identity Provider+- Add your WorkOS credentials into your Supabase project++## Create a WorkOS Organization++Log in to the dashboard and hop over to the Organizations tab to create and organization+++## Obtain the Client ID and configure Redirect URI++Head over to the Configuration tab and configure the redirect URI.The redirect URI should look like `https://<project-ref>.supabase.co/auth/v1/callback`+Note that this is distinct from the redirect URI referred to in the Supabase dashboard++++## Obtain the WorkOS Secret++Head over to the API Keys page and obtain the secret key.++++## Connect a WorkOS Supported Identity Provider++Set up the identity provider by visiting the setup link.++++You can pick between any one of the many identity providers that WorkOS supports.++## Add your WorkOS credentials into your Supabase Project++- Go to your [Supabase Project Dashboard](https://app.supabase.com)+- In the left sidebar, click the `Authentication` icon (near the top)+- Click `Settings` from the list to go to the `Authentication Settings` page+- Under `External OAuth Providers` turn `WorkOS Enabled` to ON+- Enter the `Client ID`, `Secret`, and `WorkOS URL` saved in the previous steps. The ``WorkOS URL` setting should be set to https://api.workos.com/+- Click `Save`++## Add login code to your client app++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `workos` as the `provider`:++```js+async function signInWithWorkOS() {+ const { data, error } = await supabase.auth.signInWithOAuth(+ {+ provider: 'workos',+ options: {+ queryParams: {+ connection: '<your_connection>',+ organization: '<your_organization',+ provider: '<your_provider>',+ }+ }+ },+ )+}+```++Refer to the [WorkOS Documentation](https://workos.com/docs/reference/sso/authorize/) to learn more about the different methods.++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- [WorkOS Documentation](https://workos.com/docs/sso/guide)diff --git a/apps/temp-docs/docs/guides/auth/auth-zoom.mdx b/apps/temp-docs/docs/guides/auth/auth-zoom.mdxnew file mode 100644index 00000000000..98763329bc8--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/auth-zoom.mdx@@ -0,0 +1,102 @@+---+id: auth-zoom+title: 'Login with Zoom'+description: Add Zoom OAuth to your Supabase project+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++To enable Zoom Auth for your project, you need to set up a Zoom OAuth application and add the application credentials to your Supabase Dashboard.++## Overview++Setting up Zoom logins for your application consists of 3 parts:++- Create and configure a Zoom OAuth App on [Zoom App Marketplace](https://marketplace.zoom.us/)+- Add your Zoom OAuth keys to your [Supabase Project](https://app.supabase.com)+- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js)++## Access your Zoom Developer account++- Go to [marketplace.zoom.us](https://marketplace.zoom.us/).+- Click on `Sign In` at the top right to log in.++++## Find your callback URL++The next step requires a callback URL, which looks like this:++`https://<project-ref>.supabase.co/auth/v1/callback`++- Go to your [Supabase Project Dashboard](https://app.supabase.com).+- Click on the `Settings` icon at the bottom of the left sidebar.+- Click on `API` in the list.+- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard.+- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Create a Zoom Oauth App++- Go to [marketplace.zoom.us](https://marketplace.zoom.us/).+- Click on `Sign In` at the top right to log in.+- Click `Build App` (from the dropdown Develop)+- In the OAuth card, click `Create`+- Type the name of your app+- Choose app type+- Click `Create`++Under `App credentials`++- Copy and save your `Client ID`.+- Copy and save your `Client secret`.++Under `Redirect URL for OAuth`++- Paste your `Callback URL`+- Click `Continue`++## Enter your Zoom credentials into your Supabase Project++- Go to your [Supabase Project Dashboard](https://app.supabase.com)+- In the left sidebar, click the `Authentication` icon (near the top)+- Click `Settings` from the list to go to the `Authentication Settings` page+- Enter the final (hosted) URL of your app under `Site URL` (this is important)+- Under `External OAuth Providers` turn `Zoom Enabled` to ON+- Enter your `Zoom Client ID` and `Zoom Client Secret` saved in the previous step+- Click `Save`++## Add login code to your client app++When your user signs in, call [signInWithOAuth()](/docs/reference/javascript/auth-signinwithoauth) with `zoom` as the `provider`:++```js+async function signInWithZoom() {+ const { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'zoom',+ })+}+```++When your user signs out, call [signOut()](/docs/reference/javascript/auth-signout) to remove them from the browser session and any objects from localStorage:++```js+async function signout() {+ const { error } = await supabase.auth.signOut()+}+```++## Resources++- [Supabase Account - Free Tier OK](https://supabase.com)+- [Supabase JS Client](https://github.com/supabase/supabase-js)+- [Zoom App Marketplace](https://marketplace.zoom.us/)diff --git a/apps/temp-docs/docs/guides/auth/intro.mdx b/apps/temp-docs/docs/guides/auth/intro.mdxdeleted file mode 100644index a4b0dabf47a..00000000000--- a/apps/temp-docs/docs/guides/auth/intro.mdx+++ /dev/null@@ -1,50 +0,0 @@-----id: intro-title: Supabase Auth-sidebar_label: Introduction-description: Use Supabase to Authenticate and Authorize your users.-# hide_table_of_contents: true-------<iframe- className="w-full video-with-border"- width="640"- height="385"- src="https://www.youtube-nocookie.com/embed/6ow_jW4epf8"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen-></iframe>--## Introduction--Supabase Auth is designed to work with Postgres. There are two parts to every Auth system:--- **Authentication:** should this person be allowed in? If yes, who are they?-- **Authorization:** once they are in, what are they allowed to do?--## Authentication--You can authenticate your users in several ways:--- Email & password.-- Magic links (one-click logins).-- Social providers.-- Phone logins.--<div class="container" style={{ padding: 0 }}>- <div class="row is-multiline">- <AuthProviders />- </div>-</div>---## Authorization---When you need granular authorization rules, nothing beats PostgreSQL's Row Level Security (RLS).--Policies are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.--Get started with our [Row Level Security Guides](/docs/guides/auth/row-level-security).diff --git a/apps/temp-docs/docs/guides/auth/managing-user-data.mdx b/apps/temp-docs/docs/guides/auth/managing-user-data.mdxindex d0affd2a189..ee6461042f6 100644--- a/apps/temp-docs/docs/guides/auth/managing-user-data.mdx+++ b/apps/temp-docs/docs/guides/auth/managing-user-data.mdx@@ -4,7 +4,7 @@ title: Managing User Datadescription: Securing your user data with Row Level Security.----For security purposes, the `auth` schema is not exposed on the auto-generated API.+For security purposes, the `auth` schema is not exposed on the auto-generated API.Even though Supabase provides an `auth.users` table, it can be helpful to create tables in the `public` schema for storing user data that you want to access via the API.@@ -26,10 +26,9 @@ create table public.profiles (alter table public.profiles enable row level security;```-## Public access-Since Row Level Security is enabled, this table is accessible via the API but no data will be returned unless we set up some Policies.+Since Row Level Security is enabled, this table is accessible via the API but no data will be returned unless we set up some Policies.If we wanted the data to be _readable_ by everyone but only allow logged-in users to update their own data, the Policies would look like this:```sql@@ -64,7 +63,7 @@ const { data } = await supabase.from('profiles').select('id, username, avatar_url, website')-// After the user is logged in, this will only return+// After the user is logged in, this will only return// the logged-in user's data - in this case a single rowconst { error } = await supabase.auth.signIn({ email })const { data: profile } = await supabase@@ -72,27 +71,26 @@ const { data: profile } = await supabase.select('id, username, avatar_url, website')```-## Bypassing Row Level Security+## Bypassing Row Level Security-If you need to fetch a full list of user profiles, we supply a `service_key` which you can use with your API and Client Libraries to bypass Row Level Security.+If you need to fetch a full list of user profiles, we supply a `service_key` which you can use with your API and Client Libraries to bypass Row Level Security.Make sure you _NEVER_ expose this publicly. But it can be used on the server-side to fetch all of the profiles.-## Advanced techniques### Using triggers-If you want to add a row to your `public.profiles` table every time a user signs up, you can use triggers.+If you want to add a row to your `public.profiles` table every time a user signs up, you can use triggers.If the trigger fails however, it could block the user sign ups - so make sure that the code is well-tested.For example:```sql-- inserts a row into public.users-create function public.handle_new_user()-returns trigger-language plpgsql+create function public.handle_new_user()+returns trigger+language plpgsqlsecurity definer set search_path = publicas $$begindiff --git a/apps/temp-docs/docs/guides/auth/row-level-security.mdx b/apps/temp-docs/docs/guides/auth/row-level-security.mdxindex 5ee6a1a7ff0..a103c6a676e 100644--- a/apps/temp-docs/docs/guides/auth/row-level-security.mdx+++ b/apps/temp-docs/docs/guides/auth/row-level-security.mdx@@ -4,12 +4,18 @@ title: Row Level Securitydescription: Secure your data using Postgres Row Level Security.----When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).+When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.-<iframe className="w-full video-with-border" width="640" height="385" src="https://www.youtube-nocookie.com/embed/Ow_Uzedfohk" frameBorder="1" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>-+<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/Ow_Uzedfohk"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>## Policies@@ -18,8 +24,8 @@ every time a table is accessed.You can just think of them as adding a `WHERE` clause to every query. For example a policy like this ...```sql-create policy "Individuals can view their own todos."- on todos for select+create policy "Individuals can view their own todos."+ on todos for selectusing ( auth.uid() = user_id );```@@ -31,26 +37,57 @@ from todoswhere auth.uid() = todos.user_id; -- Policy is implicitly added.```-## Helper Functions+## Helper FunctionsSupabase provides you with a few easy functions that you can use with your policies.--### `auth.uid()`+### `auth.uid()`Returns the ID of the user making the request.+### `auth.jwt()`++Returns the JWT of the user making the request.+### `auth.role()`-Returns the role of the user making the request. In most cases this is either `authenticated` or `anon`.+:::caution++Deprecated++:::++The `auth.role()` function has been deprecated in favour of using the `TO` field, natively supported within Postgres.++```sql+-- DEPRECATED+create policy "Public profiles are viewable by everyone."+on profiles for select using (+ auth.role() = 'authenticated' or auth.role() = 'anon'+);++-- RECOMMENDED+create policy "Public profiles are viewable by everyone."+on profiles for select+to authenticated, anon+using (+ true+);+```### `auth.email()`+:::caution++Deprecated. Use `auth.jwt() ->> 'email'` instead.++:::+Returns the email of the user making the request.## Examples-Here are some examples to show you the power of PostgreSQL's RLS.+Here are some examples to show you the power of PostgreSQL's RLS.### Allow read access@@ -100,6 +137,19 @@ create policy "Users can update their own profiles."2. Enables RLS.3. Creates a policy which allows logged in users to update their own data.+### Only anon or authenticated access++You can add a Postgres role++```sql+create policy "Public profiles are viewable by everyone."+on profiles for select+to authenticated, anon+using (+ true+);+```+### Policies with joinsPolicies can even include table joins. This example shows how you can query "external" tables to build more advanced rules.@@ -188,7 +238,7 @@ alter table leaderboardcreate policy "Only Blizzard staff can update leaderboard"on leaderboardfor update using (- right(auth.email(), 13) = '@blizzard.com'+ right(auth.jwt() ->> 'email', 13) = '@blizzard.com');```@@ -267,17 +317,18 @@ using ();```-## Tips-### Disable realtime for private tables+### Enable Realtime for database tables-Our realtime server doesn't provide per-user security. Until we build a more robust auth system for WebSockets, you can disable realtime functionality for any private tables. To do this, you can manage the underlying Postgres replication publication:+Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies.+We recommend that you enable row level security and set row security policies on tables that you add to the publication.+However, you may choose to disable RLS on a table and have changes broadcast to all connected clients.```sql/*** REALTIME SUBSCRIPTIONS- * Only allow realtime listening on public tables.+ * Realtime enables listening to any table in your public schema.*/begin;@@ -295,21 +346,18 @@ alter publication supabase_realtime add table products;alter publication supabase_realtime add table posts;```-We're in the process of building [enhanced realtime security](https://github.com/supabase/walrus).--### You don't have to use policies+### You don't have to use policiesYou can also put your authorization rules in your middleware, similar to how you would create security rules with any other `backend <-> middleware <-> frontend` architecture.Policies are a tool. In the case of "serverless/Jamstack" setups, they are especially effective because you don't have to deploy any middleware at all.-However, if you want to use another authorization method for your applications, that's also fine. Supabase is "just Postgres", so if your application-works with Postgres, then it also works with Supabase.+However, if you want to use another authorization method for your applications, that's also fine. Supabase is "just Postgres", so if your application+works with Postgres, then it also works with Supabase.Tip: Make sure to enable RLS for all your tables, so that your tables are inaccessible. Then use the "Service" which we provide, which is designed to bypass RLS.-### Never use a service key on the client-Supabase provides special "Service" keys, which can be used to bypass all RLS.+Supabase provides special "Service" keys, which can be used to bypass all RLS.These should never be used in the browser or exposed to customers, but they are useful for administrative tasks.diff --git a/apps/temp-docs/docs/guides/auth/server-side-rendering.mdx b/apps/temp-docs/docs/guides/auth/server-side-rendering.mdxnew file mode 100644index 00000000000..1c1e3818b78--- /dev/null+++ b/apps/temp-docs/docs/guides/auth/server-side-rendering.mdx@@ -0,0 +1,202 @@+---+id: server-side-rendering+title: Server-Side Rendering+description: Render pages with user information on the server.+---++Single-page apps with server-side rendering (SSR) is a popular way to optimize rendering+performance and leverage advanced caching strategies.++Supabase Auth supports server-side rendering when you need access to user+information, or your server needs to authorize API requests on behalf of your+user to render content.++When a user authenticates with Supabase Auth, two pieces of information are+issued by the server:++1. **Access token** in the form of a JWT.+2. **Refresh token** which is a randomly generated string.++Most Supabase projects have their auth server listening on+`<project-ref>.supabase.co/auth/v1`, thus the access token and refresh token are+set as `sb-access-token` and `sb-refresh-token` cookies on the+`<project-ref>.supabase.co` domain.++:::note+These cookie names are for internal Supabase use only and may change without+warning. They are included in this guide for illustration purposes only.+:::++Web browsers limit access to cookies across domains, consistent with the+[Same-Origin Policy+(SOP)](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).++Your web application cannot access these cookies,+nor will these cookies be sent to your application's server.++## Understanding the authentication flow++When you call one of the `signIn` methods, the client library running in the+browser sends the request to the Supabase Auth server. The Auth server determines+whether to verify a phone number, email and password combination, a Magic Link,+or use a social login (if you have any setup in your project).++Upon successful verification of the identity of the user, the Supabase Auth+server redirects the user back to your single-page app.++:::tip+You can configure [redirects URLs](https://app.supabase.com/project/_/auth/settings) in the Supabase Dashboard. You can use wildcard match patterns+like `*` and `**` to allow redirects to different forms of URLs.+:::++These redirect URLs have the following structure:++```+https://yourapp.com/...#access_token=<...>&refresh_token=<...>&...+```++The first access and refresh tokens after a successful verification are+contained in the URL fragment (anything after the `#` sign) of the redirect+location. This is intentional and not configurable.++The client libraries are designed to listen for this type of URL, extract+the access token, refresh token and some extra information from it, and finally+persist it in local storage for further use by the library and your app.++:::info+Web browsers do not send the URL fragment to the server they're making the+request to. Since you may not be hosting the single-page app on a server under+your direct control (such as on GitHub Pages or other freemium hosting+providers), we want to prevent hosting services from getting access to your+user's authorization credentials by default. Even if the server is under your+direct control, `GET` requests and their full URLs are often logged. This+approach also avoids leaking credentials in request or access logs.+:::++## Bringing it together++As seen from the authentication flow, the initial request after successful+login made by the browser to your app's server after user login **does not+contain any information about the user**. This is because first the client-side+JavaScript library must run before it makes the access and refresh token+available to your server.++It is very important to make sure that the redirect route right after login+works without any server-side rendering. Other routes requiring authorization+do not have the same limitation, provided you send the access and refresh+tokens to your server.++This is traditionally done by setting cookies. Here's an example you+can add to the root of your application:++```typescript+supabase.auth.onAuthStateChange((event, session) => {+ if (event === "SIGNED_OUT" || event === "USER_DELETED") {+ // delete cookies on sign out+ const expires = new Date(0).toUTCString();+ document.cookie = `my-access-token=; path=/; expires=${expires}; SameSite=Lax; secure`;+ document.cookie = `my-refresh-token=; path=/; expires=${expires}; SameSite=Lax; secure`;+ } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {+ const maxAge = 100 * 365 * 24 * 60 * 60; // 100 years, never expires+ document.cookie = `my-access-token=${session.access_token}; path=/; max-age=${maxAge}; SameSite=Lax; secure`;+ document.cookie = `my-refresh-token=${session.refresh_token}; path=/; max-age=${maxAge}; SameSite=Lax; secure`;+ }+})+```++This uses the standard+[`document.cookie` API](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)+to set cookies on all paths of your app's domain. All subsequent requests+made by the browser to your app's server include the `my-access-token` and+`my-refresh-token` cookies (the names of the cookies and additional+parameters can be changed).++In your server-side rendering code you can now access user and session+information:+++```typescript+const refreshToken = req.cookies['my-refresh-token'];+const accessToken = req.cookies['my-access-token'];++if (refreshToken && accessToken) {+ await supabase.auth.setSession({+ refresh_token: refreshToken,+ access_token: accessToken+ });+} else {+ // make sure you handle this case!+ throw new Error("User is not authenticated.")+}++// returns user information+await supabase.auth.getUser();+```++Use `setSession({ access_token, refresh_token })` instead of+`setSession(refreshToken)` or `getUser(accessToken)` as refresh tokens or access tokens alone do not properly identify a user session.++Access tokens are valid only for a short amount of time.++Even though refresh tokens are long-lived, there is no guarantee that a user+has an active session. They may have logged out and your application failed to+remove the `my-refresh-token` cookie, or some other failure occurred that left+a stale refresh token in the browser. Furthermore, a refresh token can only be+used a few seconds after it was first used. Only use a refresh token if the+access token is about to expire, which will avoid the introduction of difficult+to diagnose logout bugs in your app.++A good practice is to handle unauthorized errors by deferring rendering the+page in the browser instead of in the server. Some user information is+contained in the access token though, so in certain cases, you may be able to+use this potentially stale information to render a page.++## Frequently Asked Questions++### How do I make the cookies `HttpOnly`?++This is not necessary. Both the access token and refresh token are designed to+be passed around to different components in your application. The browser-based+side of your application needs access to the refresh token to properly maintain+a browser session anyway.++### My server is getting invalid refresh token errors. What's going on?++It is likely that the refresh token sent from the browser to your server is+stale. Make sure the `onAuthStateChange` listener callback is free of bugs and+is registered relatively early in your application's lifetime.++When you receive this error on the server-side, try to defer+rendering to the browser where the client library can access an up-to-date+refresh token and present the user with a better experience.++### Should I set a shorter `Max-Age` parameter on the cookies?++The `Max-Age` or `Expires` cookie parameters only control whether the browser+sends the value to the server. Since a refresh token represents the+long-lived authentication session of the user on that browser, setting a short+`Max-Age` or `Expires` parameter on the cookies only results in a degraded+user experience.++The only way to ensure that a user has logged out or their session has ended+is to get the user's details with `getUser()`.++### What should I use for the `SameSite` property?++Make sure you [understand the behavior of the property in different+situations](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite)+as some properties can degrade the user experience.++A good default is to use `Lax` which sends cookies when users are+navigating to your site. Cookies typically require the `Secure` attribute,+which only sends them over HTTPS. However, this can be a problem when+developing on `localhost`.++### Can I use server-side rendering with a CDN or cache?++Yes, but you need to be careful to include at least the refresh token cookie+value in the cache key. Otherwise you may be accidentally serving pages with+data belonging to different users!++Also be sure you set proper cache control headers. We recommend invalidating+cache keys every hour or less.diff --git a/apps/temp-docs/docs/guides/cli.mdx b/apps/temp-docs/docs/guides/cli.mdxnew file mode 100644index 00000000000..ef486ee6854--- /dev/null+++ b/apps/temp-docs/docs/guides/cli.mdx@@ -0,0 +1,110 @@+---+id: cli+title: Supabase CLI+description: The Supabase CLI provides tools to develop your project locally and deploy to the Supabase Platform.+sidebar_label: Overview+toc_max_heading_level: 2+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++The Supabase CLI provides tools to develop your project locally and deploy to the Supabase Platform.+You can also use the CLI to manage your Supabase projects, handle database migrations and CI/CD workflows, and generate types directly from your database schema.++## Installation++<Tabs+ groupId="platform"+ defaultValue="macos"+ values={[+ {label: 'macOS', value: 'macos'},+ {label: 'Windows', value: 'windows'},+ {label: 'Linux', value: 'linux'},+ ]}>+<TabItem value="macos">++Install the CLI with [Homebrew](https://brew.sh):++```sh+brew install supabase/tap/supabase+```++</TabItem>++<TabItem value="windows">++Install the CLI with [Scoop](https://scoop.sh):++```powershell+scoop bucket add supabase https://github.com/supabase/scoop-bucket.git+scoop install supabase+```++</TabItem>++<TabItem value="linux">++The CLI is available through [Homebrew](https://brew.sh) and Linux packages.++### Homebrew++```sh+brew install supabase/tap/supabase+```++### Linux packages++Linux packages are provided in [Releases](https://github.com/supabase/cli/releases).+To install, download the `.apk`/`.deb`/`.rpm` file depending on your package manager+and run one of the following:++- `sudo apk add --allow-untrusted <...>.apk`+- `sudo dpkg -i <...>.deb`+- `sudo rpm -i <...>.rpm`++</TabItem>+</Tabs>++## Updates++When a new [version](https://github.com/supabase/cli/releases) is released, you can update the CLI using the same methods.++<Tabs+ groupId="platform"+ defaultValue="macos"+ values={[+ {label: 'macOS', value: 'macos'},+ {label: 'Windows', value: 'windows'},+ {label: 'Linux', value: 'linux'},+ ]}>+<TabItem value="macos">++```sh+brew upgrade supabase+```++</TabItem>++<TabItem value="windows">++```powershell+scoop update supabase+```++</TabItem>++<TabItem value="linux">++```sh+brew upgrade supabase+```++</TabItem>+</Tabs>++## See also++- [Supabase CLI Reference](/docs/reference/cli/usage)+- [Local Development](/docs/guides/cli/local-development)+- [Managing Environments](/docs/guides/cli/managing-environments)diff --git a/apps/temp-docs/docs/guides/cli/environments.mdx b/apps/temp-docs/docs/guides/cli/environments.mdxnew file mode 100644index 00000000000..b79386d5311--- /dev/null+++ b/apps/temp-docs/docs/guides/cli/environments.mdx@@ -0,0 +1,417 @@+---+id: managing-environments+title: Managing Environments+description: How to deploy Supabase schema changes with a CI / CD pipeline.+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++## Overview++The Supabase CLI provides the tools you need to manage multiple environments.+This guide shows you how to set up your local Supabase development environment that integrates with GitHub Actions to automatically+test and release schema changes to staging and production Supabase projects.++To get started:++- [Install the Supabase CLI](/docs/guides/cli)+- Create a [Supabase project](https://app.supabase.com) or use an existing one+- Initialize a local Git repository++## Set up a local environment++The first step is to set up your local repository with the Supabase CLI:++```bash+supabase init+```++You should see a new `supabase` directory. Then you need to link your local repository with your Supabase project:++```bash+supabase login+supabase link --project-ref $PROJECT_ID+```++You can get your `$PROJECT_ID` from your project's dashboard URL:++```+https://app.supabase.com/project/<project-id>+```++If you're using an existing Supabase project, you might have made schema changes through the Dashboard.+Run the following command to pull these changes before making local schema changes from the CLI:++```sql+supabase db remote commit+```++This command creates a new migration in `supabase/migrations/<timestamp>_remote_commit.sql` which reflects the schema changes you have made previously.++Now commit your local changes to Git and run the local development setup:++```bash+git add .+git commit -m "init supabase"+supabase start+```++You are now ready to develop schema changes locally and create your first migration.++## Create a new migration++There are two ways to make schema changes:++1. Manual migration: Write DDL statements manually into a migration file+1. Auto schema diff: Make changes through Studio UI and auto generate a schema diff++### Manual migration++<!--  -->++Create a new migration script by running:++```bash+supabase migration new new_employee+```++You should see a new file created: `supabase/migrations/<timestamp>_new_employee.sql`. You can then write SQL statements in this script using a text editor:++```sql+create table public.employees (+ id integer primary key generated always as identity,+ name text+);+```++Apply the new migration to your local database:++```bash+supabase db reset+```++This command recreates your local database from scratch and applies all migration scripts under `supabase/migrations` directory. Now your local database is up to date.++:::tip++The new migration command also supports stdin as input.+This allows you to pipe in an existing script from another file or stdout:++`supabase migration new new_employee < create_employees_table.sql`+:::++### Auto schema diff++Unlike manual migrations, auto schema diff creates a new migration script from changes **already** applied to your local database.++<!--  -->++Create an `employees` table under the `public` schema using Studio UI, accessible at [localhost:54323](http://localhost:54323/) by default.++Next, generate a schema diff by running the following command:++```bash+supabase db diff -f new_employee+```++You should see that a new file `supabase/migrations/<timestamp>_new_employee.sql` is created. Open the file and verify that the generated DDL statements are the same as below.++```sql+-- This script was generated by the Schema Diff utility in pgAdmin 4+-- For the circular dependencies, the order in which Schema Diff writes the objects is not very sophisticated+-- and may require manual changes to the script to ensure changes are applied in the correct order.+-- Please report an issue for any failure with the reproduction steps.++CREATE TABLE IF NOT EXISTS public.employees+(+ id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),+ name text COLLATE pg_catalog."default",+ CONSTRAINT employees_pkey PRIMARY KEY (id)+)++TABLESPACE pg_default;++ALTER TABLE IF EXISTS public.employees+ OWNER to postgres;++GRANT ALL ON TABLE public.employees TO anon;++GRANT ALL ON TABLE public.employees TO authenticated;++GRANT ALL ON TABLE public.employees TO postgres;++GRANT ALL ON TABLE public.employees TO service_role;+```++You may notice that the auto-generated migration script is more verbose than the manually written one.+This is because the default schema diff tool does not account for default privileges added by the initial schema.++Commit the new migration script to git and you are ready to deploy.++:::tip++Alternatively, you may pass in the `--use-migra` experimental flag to generate a more concise migration using [migra](https://github.com/djrobstep/migra).+Without the `-f` file flag, the output is written to stdout by default.++`supabase db diff --use-migra`++:::++## Deploy a migration++In a production environment, we recommend using a CI/CD pipeline to deploy new migrations with GitHub Actions rather than deploying from your local machine.++++This example uses two Supabase projects, one for production and one for staging.++Prepare your environments by:++- Creating separate Supabase projects for staging and production+- Pushing your git repository to GitHub and enabling GitHub Actions++:::caution++You need a _new_ project for staging. A project which has already been modified to reflect the production project's schema can't be used because the CLI would reapply these changes.++:::++### Configure GitHub Actions++The Supabase CLI requires a few environment variables to run in non-interactive mode.++- `SUPABASE_ACCESS_TOKEN` is your personal access token+- `SUPABASE_DB_PASSWORD` is your project specific database password++We recommend adding these as [encrypted secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) to your GitHub Actions runners.++Create the following files inside the `.github/workflows` directory:++<Tabs+ defaultValue="CI"+ values={[+ {label: 'ci.yaml', value: 'CI'},+ {label: 'staging.yaml', value: 'STAGING'},+ {label: 'production.yaml', value: 'PRODUCTION'},+ ]}>+<TabItem value="CI">++```yaml title=".github/workflows/ci.yml"+name: CI++on:+ pull_request:+ workflow_dispatch:++jobs:+ test:+ runs-on: ubuntu-22.04+ steps:+ - uses: actions/checkout@v3++ - uses: supabase/setup-cli@v1+ with:+ version: 1.0.0++ - name: Start Supabase local development setup+ run: supabase start++ - name: Verify generated types are up-to-date+ run: |+ supabase gen types typescript --local > types.ts+ if [ "$(git diff --ignore-space-at-eol types.ts | wc -l)" -gt "0" ]; then+ echo "Detected uncommitted changes after build. See status below:"+ git diff+ exit 1+ fi+```++</TabItem>+<TabItem value="STAGING">++```yaml title=".github/workflows/staging.yml"+name: Deploy Migrations to Staging++on:+ push:+ branches:+ - develop+ workflow_dispatch:++jobs:+ deploy:+ runs-on: ubuntu-22.04++ env:+ SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}+ SUPABASE_DB_PASSWORD: ${{ secrets.STAGING_DB_PASSWORD }}+ STAGING_PROJECT_ID: abcdefghijklmnopqrst++ steps:+ - uses: actions/checkout@v3++ - uses: supabase/setup-cli@v1+ with:+ version: 1.0.0++ - run: |+ supabase link --project-ref $STAGING_PROJECT_ID+ supabase db push+```++</TabItem>+<TabItem value="PRODUCTION">++```yaml title=".github/workflows/production.yml"+name: Deploy Migrations to Production++on:+ push:+ branches:+ - main+ workflow_dispatch:++jobs:+ deploy:+ runs-on: ubuntu-22.04++ env:+ SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}+ SUPABASE_DB_PASSWORD: ${{ secrets.PRODUCTION_DB_PASSWORD }}+ PRODUCTION_PROJECT_ID: abcdefghijklmnopqrst++ steps:+ - uses: actions/checkout@v3++ - uses: supabase/setup-cli@v1+ with:+ version: 1.0.0++ - run: |+ supabase link --project-ref $PRODUCTION_PROJECT_ID+ supabase db push+```++</TabItem>+</Tabs>++The full example code is available in the [demo repository](https://github.com/supabase/supabase-action-example).++Commit these files to git and push to your `main` branch on GitHub. Update these environment variables to match your Supabase projects:++- `SUPABASE_ACCESS_TOKEN`+- `PRODUCTION_PROJECT_ID`+- `PRODUCTION_DB_PASSWORD`+- `STAGING_PROJECT_ID`+- `STAGING_DB_PASSWORD`++When configured correctly, your repository will have CI and Release workflows that trigger on new commits pushed to `main` and `develop` branches.++++### Open a PR with new migration++Follow the [migration steps](#create-a-new-migration) to create a `supabase/migrations/<timestamp>_new_employee.sql` file.++Checkout a new branch `feat/employee` from `develop` , commit the migration file, and push to GitHub.++```bash+git checkout -b feat/employee+git add supabase/migrations/<timestamp>_new_employee.sql+git commit -m "Add employee table"+git push --set-upstream origin feat/employee+```++Open a PR from `feat/employee` to the `develop` branch to see that the CI workflow has been triggered.++Once the test error is resolved, merge this PR and watch the deployment in action.++### Release to production++After verifying your staging project has successfully migrated, create another PR from `develop` to `main` and merge it to deploy the migration to the production project.++<!--  -->++The `release` job applies all new migration scripts merged in `supabase/migrations` directory to a linked Supabase project. You can control which project the job links to via `PROJECT_ID` environment variable.++## Troubleshooting++### Sync production project to staging++When setting up a new staging project, you might need to sync the initial schema with migrations previously applied to the production project.++One way is to leverage the Release workflow:++- Create a new branch `develop` and choose `main` as the branch source+- Push the `develop` branch to GitHub++The GitHub Actions runner will deploy your existing migrations to the staging project.++Alternatively, you can also apply migrations through your local CLI to a linked remote database.++```sql+supabase db push+```++Once pushed, check that the migration version is up to date for both local and remote databases.++```sql+supabase migration list+```++### Permission denied on db remote commit++If you have been using Supabase hosted projects for a long time, you might encounter the following permission error when executing `db remote commit`.++```bash+Error: Error running pg_dump on remote database: pg_dump: error: query failed: ERROR: permission denied for table _type++pg_dump: error: query was: LOCK TABLE "graphql"."_type" IN ACCESS SHARE MODE+```++To resolve this error, you need to grant `postgres` role permissions to `graphql` schema. You can do that by running the following query from Supabase dashboard's SQL Editor.++```sql+grant all on all tables in schema graphql to postgres, anon, authenticated, service_role;+grant all on all functions in schema graphql to postgres, anon, authenticated, service_role;+grant all on all sequences in schema graphql to postgres, anon, authenticated, service_role;+```++### Permission denied on db push++If you created a table through Supabase dashboard, and your new migration script contains `ALTER TABLE` statements, you might run into permission error when applying them on staging or production databases.++```bash+ERROR: must be owner of table employees (SQLSTATE 42501); while executing migration <timestamp>+```++This is because tables created through Supabase dashboard are owned by `supabase_admin` role while the migration scripts executed through CLI are under `postgres` role.++One way to solve this is to reassign the owner of those tables to `postgres` role. For example, if your table is named `users` in the public schema, you can run the following command to reassign owner.++```sql+ALTER TABLE users OWNER TO postgres;+```++Apart from tables, you also need to reassign owner of other entities using their respective commands, including [types](https://www.postgresql.org/docs/current/sql-alterschema.html), [functions](https://www.postgresql.org/docs/current/sql-alterroutine.html), and [schemas](https://www.postgresql.org/docs/current/sql-altertype.html).++### Rebasing new migrations++Sometimes your teammate may merge a new migration file to git main branch, and now you need to rebase your local schema changes on top.++<!--  -->++We can handle this scenario gracefully by renaming your old migration file with a new timestamp.++```bash+git pull+supabase migration new dev_A+# Assume the new file is: supabase/migrations/<t+2>_dev_A.sql+mv <time>_dev_A.sql <t+2>_dev_A.sql+supabase db reset+```++In case [`reset`](/reference/cli/usage#supabase-db-reset) fails, you can manually resolve conflicts by editing `<t+2>_dev_A.sql` file.++Once validated locally, commit your changes to Git and push to GitHub.diff --git a/apps/temp-docs/docs/guides/local-development.mdx b/apps/temp-docs/docs/guides/cli/local-development.mdxsimilarity index 88%rename from apps/temp-docs/docs/guides/local-development.mdxrename to apps/temp-docs/docs/guides/cli/local-development.mdxindex ccded0a92b6..a4d7d7fc38e 100644--- a/apps/temp-docs/docs/guides/local-development.mdx+++ b/apps/temp-docs/docs/guides/cli/local-development.mdx@@ -4,24 +4,11 @@ title: Local Developmentdescription: How to use Supabase on your local development machine.----## Local Development--// import Tabs from '@theme/Tabs'-// import TabItem from '@theme/TabItem'+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Learn how to use the Supabase CLI to develop your project locally and deploy to the Supabase Platform.-{/* This is just my experimentation to use the Tabs component from the UI library but looks odd */}--<Tabs scrollable size="small" type="underlined" listClassNames="px-8 pt-4" defaultActiveId="kong">- <TabPanel id="postgres" label="Postgres">- Hello- </TabPanel>- <TabPanel id="kong" label="API Gateway">- World- </TabPanel>-</Tabs>-## PrerequisitesMake sure you have these installed on your local machine:@@ -36,15 +23,6 @@ Make sure you have these installed on your local machine:supabase login```-<Alert withIcon variant="warning" title="Successfully generated a new token!">- <div className="w-full space-y-2">- <p className="text-sm">- To access the database from an edge function in your local Supabase setup, replace `localhost`- with `host.docker.internal`.- </p>- </div>-</Alert>-## Initialize your projectCreate a new folder for your project and start a new git repository:@@ -60,12 +38,6 @@ cd your-projectgit init```-```js-function create() {- console.log('hay')-}-```-## Start Supabase services[Initialize](/reference/cli/usage#supabase-init) Supabase to set up the configuration for developing your project locally:diff --git a/apps/temp-docs/docs/guides/client-libraries.mdx b/apps/temp-docs/docs/guides/client-libraries.mdxdeleted file mode 100755index 4e55bcff624..00000000000--- a/apps/temp-docs/docs/guides/client-libraries.mdx+++ /dev/null@@ -1,483 +0,0 @@-----id: client-libraries-title: Client Libraries-description: 'Supabase provides client libraries in several languages.'------import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'--The [Supabase Client](/docs/reference/javascript/installing) makes it simple for developers to build secure and scalable products.--## Auth--Create new users using [`signUp()`](/docs/reference/javascript/auth-signup). By default, the user will need to verify their email address before logging in.<br/>-If confirmations are disabled the response will contain an access token and also a confirmed_at value, otherwise it will just contain a confirmation_sent_at attribute.--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { error, data } = await supabase.auth.signUp({- email: '[email protected]',- password: 'example-password',-})-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-import os-from supabase_py import create_client, Client--url: str = os.environ.get("SUPABASE_TEST_URL")-key: str = os.environ.get("SUPABASE_TEST_KEY")-supabase: Client = create_client(url, key)-user = supabase.auth.sign_up(- email='[email protected]',- password='example-password',-)-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Sign up user with email and password- final response = await client- .auth- .signUp('[email protected]', 'example-password');-}-```--</TabsPanel>--</Tabs>--Existing users can log in using [`signIn()`](/docs/reference/javascript/auth-signin).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { error, data } = await supabase.auth.signIn({- email: '[email protected]',- password: 'example-password',-})-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-import os-from supabase_py import create_client, Client--url: str = os.environ.get("SUPABASE_TEST_URL")-key: str = os.environ.get("SUPABASE_TEST_KEY")-supabase: Client = create_client(url, key)-user = supabase.auth.sign_in(- email='[email protected]',- password='example-password'-)-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Sign in user with email and password- final response = await client- .auth- .signIn(email: '[email protected]', password: 'example-password');-}-```--</TabsPanel>--</Tabs>--If there is an email, but no password passed to [`signIn()`](/docs/reference/javascript/auth-signin), the user will receive a magic link.--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { error, data } = await supabase.auth.signIn({- email: '[email protected]',-})-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-import os-from supabase_py import create_client, Client--url: str = os.environ.get("SUPABASE_TEST_URL")-key: str = os.environ.get("SUPABASE_TEST_KEY")-supabase: Client = create_client(url, key)-user = supabase.auth.sign_in(- email='[email protected]'-)-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Sign in user with email and magic link- final response = await client- .auth- .signIn(email: '[email protected]');-}-```--</TabsPanel>--</Tabs>--Third party logins are also handled through [`signIn()`](/docs/reference/javascript/auth-signin).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { user, error } = await supabase.auth.signIn({- // provider can be 'github', 'google', 'gitlab', or 'bitbucket'- provider: 'github',-})-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-# Not yet implemented-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- final response = await client- .auth- .signIn(provider: Provider.github);-}-```--</TabsPanel>--</Tabs>--## Managing data--Since Postgres is a Relational database, the client makes it simple to query tables and fetch related data in one round-trip, using [`select()`](/docs/reference/javascript/select).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { data, error } = await supabase.from('countries').select(`- name,- cities (- name- )- `)-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-import os-from supabase_py import create_client, Client--url: str = os.environ.get("SUPABASE_TEST_URL")-key: str = os.environ.get("SUPABASE_TEST_KEY")-supabase: Client = create_client(url, key)--data = supabase.table('countries').select('name').execute()-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Query tables and fetch related data in one round-trip, using select()- final response = await client- .from('countries')- .select('name')- .execute();-}-```--</TabsPanel>--</Tabs>--You can do advanced [filtering](/docs/reference/javascript/using-filters) to extract only the data that you need.--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { data, error } = await supabase- .from('cities')- .select('name, country_id')- .lt('country_id', 100)- .limit(10)-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-data = supabase.table('cities').select('name, country_id').eq('name', 'Germany').execute()-# Assert we pulled real data.-assert len(data.get("data", [])) > 0-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // When fetching data, use advanced filtering to only extract data, that you need.- final response = await client- .from('cities')- .select('name,country_id')- .lt('country_id', 100)- .limit(10)- .execute();-}-```--</TabsPanel>--</Tabs>--You can create data easily using [`insert()`](/docs/reference/javascript/insert).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const { data, error } = await supabase.from('cities').insert([- { name: 'The Shire', country_id: 554 },- { name: 'Rohan', country_id: 555 },-])-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-data = supabase.table('cities').insert({'name': 'Gotham', 'country_id': 556 }).execute()-# assert if insert response is a success-assert data.get("status_code") in (200, 201)--# bulk insert-data = supabase.table('cities').insert([-{'name': 'Gotham', 'country_id': 556 },-{'name': 'The Shire', 'country_id': 557 }-]).execute()--```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Create data easily, using insert()- final response = await client- .from('cities')- .insert([- { 'name': 'The Shire', 'country_id': 554 },- { 'name': 'Rohan', 'country_id': 555 },- ])- .execute();-}-```--</TabsPanel>--</Tabs>--## Realtime Changes--The Supabase client makes it simple to listen to realtime database changes, using [`subscribe()`](/docs/reference/javascript/subscribe).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const mySubscription = supabase- .from('countries')- .on('*', (payload) => {- console.log('Change received!', payload)- })- .subscribe()-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-# Not yet implemented-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // Listen to realtime database changes, using subscribe()- final response = await client- .from('countries')- .on(SupabaseEventTypes.all, (payload) {- print('Something happened: ${payload.eventType}');- })- .subscribe((String event, {String? errorMsg}) {- print('event: $event error: $errorMsg');- });-}-```--</TabsPanel>--</Tabs>--You can even [listen to Row Level changes](/docs/reference/javascript/subscribe#listening-to-row-level-changes).--<Tabs- groupId="libraries"- defaultActiveId="js"- values={[{ label: 'JavaScript', value: 'js' },{ label: 'Python', value: 'py' },{ label: 'Dart', value: 'dart'}]}>--<TabsPanel id="js" label="js">--```js-const mySubscription = supabase- .from('countries:id.eq.200')- .on('UPDATE', handleRecordUpdated)- .subscribe()-```--</TabsPanel>-<TabsPanel id="py" label="py">--```py-# Not yet implemented-```--</TabsPanel>--<TabsPanel id="dart" label="dart">--```dart-import 'package:supabase/supabase.dart';--void main() async {- final client = SupabaseClient('supabaseUrl', 'supabaseKey');-- // You can even listen to Row Level changes- final response = await client- .from('countries:id.eq.200')- .on(SupabaseEventTypes.update, (payload) {- print('Something happened: ${payload.eventType}');- })- .subscribe((String event, {String? errorMsg}) {- print('event: $event error: $errorMsg');- });-}-```--</TabsPanel>--</Tabs>--## Next steps--- View the [Client Docs](/docs/reference/javascript/installing)-- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/database.mdx b/apps/temp-docs/docs/guides/database.mdxold mode 100755new mode 100644index 71dc23d8546..ee4234bd43c--- a/apps/temp-docs/docs/guides/database.mdx+++ b/apps/temp-docs/docs/guides/database.mdx@@ -1,11 +1,23 @@----title: 'Database'-description: 'Supabase is built on top of Postgres, an extremely scalable Relational Database.'+id: database+title: Database+description: Use Supabase to manage your data.+sidebar_label: Overview----# Database+Every Supabase project comes with a full [Postgres](https://www.postgresql.org/) database, a free and open source+database which is considered one of the world's most stable and advanced databases.-Supabase is built on top of Postgres, an extremely scalable Relational Database.+## Postgres or PostgreSQL?++PostgreSQL the database was derived from the POSTGRES Project, a package written at the University of California at Berkeley in 1986.+This package included a query language called "PostQUEL".++In 1994, Postgres95 was built on top of POSTGRES code, adding an SQL language interpreter as a replacement for PostQUEL.+Eventually, Postgres95 was renamed to PostgreSQL to reflect the SQL query capability.++After this, many people referred to it as Postgres since it's less prone to confusion. Supabase is all about+simplicity, so we also refer to it as Postgres.## Features@@ -13,168 +25,69 @@ Supabase is built on top of Postgres, an extremely scalable Relational Database.You don't have to be a database expert to start using Supabase. Our table view makes Postgres as easy to use as a spreadsheet.-+### RelationshipsDig into the relationships within your data.-<video width="99%" playsinline controls>- <source src="/videos/relational-drilldown-zoom.mp4" type="video/mp4" playsInline />+<video width="99%" loop="" muted="" playsInline="" controls="true">+ <source src="/docs/videos/relational-drilldown-zoom.mp4" type="video/mp4" /></video>### Clone tablesYou can duplicate your tables, just like you would inside a spreadsheet.-<video width="99%" playsinline controls>- <source src="/videos/duplicate-tables.mp4" type="video/mp4" playsInline />+<video width="99%" muted playsInline controls={true}>+ <source+ src="/docs/videos/duplicate-tables.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>### The SQL EditorSupabase comes with a SQL Editor. You can also save your favorite queries to run later!-<video width="99%" playsinline controls>- <source src="/videos/favorites.mp4" type="video/mp4" playsInline />+<video width="99%" muted playsInline controls={true}>+ <source src="/docs/videos/favorites.mp4" type="video/mp4" muted playsInline /></video>### Additional features- Supabase extends Postgres with realtime functionality using our [Realtime Server](https://github.com/supabase/realtime).-- Every project is a full Postgres database, with postgres level access.-- Managed backups - Supabase handles all your database [backups](https://supabase.com/docs/guides/database#fn-backups).backups-- Data imports - import directly from a CSV or excel spreadsheet.+- Every project is a full Postgres database, with `postgres` level access.+- Supabase manages your database backups.+- Import data directly from a CSV or excel spreadsheet.-Database backups do NOT include objects stored via the Storage API, as the database only includes metadata about these objects. Restoring an old backup will not restore objects that have been deleted since then.+:::info+Database backups **do not** include objects stored via the Storage API, as the database only includes metadata about these objects. Restoring an old backup does not restore objects that have been deleted since then.+:::### Extensions-To expand the functionality of your Postgres database, you can use extensions. You can enable Postgres extensions with the click of a button within the Supabase dashboard.+To expand the functionality of your Postgres database, you can use extensions.+You can enable Postgres extensions with the click of a button within the Supabase dashboard.-<video width="99%" playsinline controls>- <source src="/videos/toggle-extensions.mp4" type="video/mp4" playsInline />+<video width="99%" muted playsInline controls={true}>+ <source+ src="/docs/videos/toggle-extensions.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-## Tips--### Realtime--Supabase provides a realtime engine on top of Postgres, so that you can listen to changes as they happen. Our realtime engine uses the built-in replication functionality of Postgres.--Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies. We recommend that you enable row level security and set row security policies on tables that you add to the publication. However, you may choose to disable RLS on a table and have changes broadcast to all connected clients.--You can manage the realtime system, simply by [updating](https://supabase.com/docs/guides/database/replication) the `supabase_realtime` publication.--For example to enable realtime only for individual tables:--```sql-begin;- -- remove the realtime publication- drop publication if exists supabase_realtime;-- -- re-create the publication but don't enable it for any tables- create publication supabase_realtime;-commit;---- add a table to the publication-alter publication supabase_realtime add table products;---- add other tables to the publication-alter publication supabase_realtime add table posts;-```--By default only "new" values are sent, but if you want to receive the old record (previous values) whenever you update or delete a record, you can update the replica identity of your tables, setting it to `full`:--```sql-alter table your_table replica identity full;-```--### Migrating between projects#--If you have an existing Supabase Project and you want to migrate it into a new (fresh) Project, you can simply follow these steps:--**Before you begin**--- Make sure Realtime is disabled. This will improve the performance of inserts on your new database.-- Make sure you have psql installed on your computer so that you can run pg_dump.--**Migrate the database**-First we want to grab the database structure only:+[Learn more](/docs/guides/database/extensions) about all the extensions provided on Supabase.-```bash-pg_dump \--h db.PROJECT_REF.supabase.co \--U postgres \---clean \---schema-only \-> supabase_schema.sql-```--This command creates a file on your computer called `supabase_schema.sql`.--After creating a new Supabase project we can use it to restore the database structure:--```bash-psql \--h db.NEW_PROJECT_REF.supabase.co \--U postgres \-< supabase_schema.sql-```--You may see some errors - the restore will attempt to drop any tables if they are present, and if they aren't present then an error will be displayed. These errors are informative only and nothing to worry about.--**(Optionally) Migrate the data**--We can migrate everything in our database, however we don't want to migrate the data in our storage schema because the files exist outside of the database. For now, we can just get all the data inside the public and auth schemas:--```bash-pg_dump \--h db.PROJECT_REF.supabase.co \--U postgres \---data-only \--n public \--n auth \-> supabase_data.sql-```--This command creates a file on your computer called supabase_data.sql. We can use this file to restore the data in our new database:--```bash-psql \--h db.NEW_PROJECT_REF.supabase.co \--U postgres \-< supabase_data.sql-```--### Resetting your project password--When you create a new project in Supabase we ask for a password. You can use this password to connect directly to your Postgres database.--If you forget your password, you can reset it from the Dashboard SQL editor:--For example:--```sql-alter user postgres-with password 'new_password';-```--Read more in [Database Configuration](https://supabase.com/docs/guides/database/managing-passwords).--###Changing the timezone of your server.--Your database is initialized with the UTC timezone. We recommend keeping it this way, as it is helpful for time calculations. If, however, you want to update the timezone, you can do so using any of the [database timezones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).--For example:--```sql-alter database postgres set timezone to 'America/New_York';-```+## Tips-Read more in [Database Configuration](https://supabase.com/docs/guides/database/managing-timezones).+Read about resetting your database password [here](/docs/guides/database/managing-passwords) and changing the timezone of your server [here](/docs/guides/database/managing-timezones).## Next steps-- Read more about [Postgres](https://supabase.com/docs/postgres/server/about)-- Sign in: [app.supabase.com](https://app.supabase.com/)+- Read more about [Postgres](/docs/postgres/server/about)+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/database/arrays.mdx b/apps/temp-docs/docs/guides/database/arrays.mdxindex dc83d8b48e4..51d7f7474fd 100644--- a/apps/temp-docs/docs/guides/database/arrays.mdx+++ b/apps/temp-docs/docs/guides/database/arrays.mdx@@ -5,81 +5,71 @@ description: How to use arrays in PostgreSQL and the Supabase API.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'-PostgreSQL supports flexible [array types](https://www.postgresql.org/docs/12/arrays.html).-These arrays are also supported in the Supabase dashboard and in the Javascript API.+PostgreSQL supports flexible [array types](https://www.postgresql.org/docs/12/arrays.html). These arrays are also supported in the Supabase Dashboard and in the JavaScript API.-## Steps--### Create a table with an array column+## Create a table with an array columnCreate a test table with a text array (an array of strings):<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>--<TabsPanel id="UI" label="UI">--```bash-1. Got the Table Editor-2. Create a New Table-3. Create a new table named `arraytest` and save the table- - New Column- - Name the new column `textarray`- - Make it type `text`- - Check the box labelled `Define as array`- - Save the new column-```+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">-</TabsPanel>+1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+1. Click **New Table** and create a table with the name `arraytest`.+1. Click **Save**.+1. Click **New Column** and create a column with the name `textarray`, type `text`, and select **Define as array**.+1. Click **Save**.-<TabsPanel id="SQL" label="SQL">+</TabItem>++<TabItem value="sql">```sqlCREATE TABLE arraytest (id integer NOT NULL, textarray text ARRAY);```-</TabsPanel>+</TabItem></Tabs>-### Insert a record with an array value+## Insert a record with an array value<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},- {label: 'JS', value: 'JavaScript'},-]}>--<TabsPanel id="UI" label="UI">--```bash-- Table Editor-- Select `arraytest`-- Insert Row- - In the `textarray` field input, paste:- - `["Harry", "Larry", "Moe"]`- - Save the new row-```+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ ]}>-</TabsPanel>+<TabItem value="dashboard">-<TabsPanel id="SQL" label="SQL">+1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+1. Select the `arraytest` table.+1. Click **Insert row** and add `["Harry", "Larry", "Moe"]`.+1. Click **Save.**++</TabItem>++<TabItem value="sql">```sqlINSERT INTO arraytest (id, textarray) VALUES (1, ARRAY['Harry', 'Larry', 'Moe']);```-</TabsPanel>+</TabItem>-<TabsPanel id="JavaScript" label="JavaScript">-To insert a record from the Javascript client:+<TabItem value="javascript">+Insert a record from the JavaScript client:```jsconst { data, error } = await supabase@@ -87,60 +77,60 @@ const { data, error } = await supabase.insert([{ id: 2, textarray: ['one', 'two', 'three', 'four'] }])```-</TabsPanel>+</TabItem></Tabs>-### View the results+## View the results<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>-<TabsPanel id="UI" label="UI">+<TabItem value="dashboard">-```bash-- Table Editor-- Select `arraytest`-```+1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+1. Select the `arraytest` table.-Your first array data!+You should see:| id | textarray || --- | ----------------------- || 1 | ["Harry","Larry","Moe"] |-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+</TabItem>+<TabItem value="sql">```sqlSELECT * FROM arraytest;```-Your first array data!+You should see:| id | textarray || --- | ----------------------- || 1 | ["Harry","Larry","Moe"] |-</TabsPanel>+</TabItem></Tabs>-### Query Array Data+## Query array data-To query an array, PostgreSQL uses 1-based arrays, so be careful, since you're probably used to 0-based arrays in Javascript.+PostgreSQL uses 1-based indexing (e.g., `textarray[1]` is the first item in the array).<Tabs-defaultActiveId="SQL"-values={[- {label: 'SQL', value: 'SQL'},- {label: 'JS', value: 'JavaScript'},-]}>+ groupId="dashboard-or-sql"+ defaultValue="sql"+ values={[+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ ]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="sql">To select the first item from the array and get the total length of the array:@@ -154,8 +144,9 @@ returns:| --------- | ------------ || Harry | 3 |-</TabsPanel>-<TabsPanel id="JavaScript" label="JavaScript">+</TabItem>++<TabItem value="javascript">This returns the entire array field:@@ -174,8 +165,7 @@ returns:]```-</TabsPanel>-+</TabItem></Tabs>## Resourcesdiff --git a/apps/temp-docs/docs/guides/database/connecting-to-postgres.mdx b/apps/temp-docs/docs/guides/database/connecting-to-postgres.mdxnew file mode 100644index 00000000000..b059d3dbc67--- /dev/null+++ b/apps/temp-docs/docs/guides/database/connecting-to-postgres.mdx@@ -0,0 +1,150 @@+---+id: connecting-to-postgres+title: 'Database Connections'+description: There are various ways to connect to your Postgres database.+---++Supabase provides several options for programmatically connecting to your Postgres database:++## Types of Connection++- HTTP connections using the API.+- Direct connections using Postgres' standard connection system.+- Connection pooling using PgBouncer.++### Direct vs Pooling vs API++- A "direct connection" is when a connection is made to the database using Postgres' native connection implementation. You should use this for tools which are always alive - usually installed on a long-running server.+- A "connection pool" is a system (external to Postgres) which keeps connections "open". You should use this for serverless functions and tools which disconnect from the database frequently.+- The API is an auto-generated REST interface. You should use this for all browser and application interactions. The API server internally handles a connection pool.++Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of _temporary_ connections.+You can use these simple questions to determine which connection method to use:++- Are you connecting to a database and _maintaining_ a connection? If yes, use a direct connection.+- Are you connecting to your database and then _disconnecting_ immediately (e.g. a serverless environment)? If yes, use a connection pool.++## API++Supabase provides an auto-updating [API](/docs/guides/api). This is the easiest way to get started if you are managing data (fetching, inserting, updating).++### Interfaces++We provides several types of API to suit your preferences and use-case:++- [REST](/docs/guides/api#rest-api): interact with your database through a REST interface.+- [GraphQL](/docs/guides/api#graphql-api): interact with your database through a GraphQL interface.+- [Realtime](/docs/guides/api#realtime-api): listen to database changes over websockets.++You cannot manage the database schema via the API (for security reasons). To do that you can use the dashboard or connect directly to your database.++### API URL and Keys++You can find the API URL and Keys in the [Dashboard](https://app.supabase.com/project/_/settings/api).++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Direct connections++Every Supabase project provides a full Postgres database. You can connect to the database using any tool which supports Postgres.++### Finding your connection string++1. Go to the `Settings` section.+2. Click `Database`.+3. Find your Connection Info and Connection String. Direct connections are on port `5432`.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/postgres-connection.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Connection Pool++Connection pools are useful for managing a large number of _temporary_ connections. For example, if you are using [Prisma](/docs/guides/integrations/prisma) deployed to a Serverless environment.++### How connection pooling works++A "connection pool" is a system (external to Postgres) which manages connections, rather than PostgreSQL's native system. Supabase uses [PgBouncer](https://www.pgbouncer.org/) for connection pooling.++When a client makes a request, PgBouncer "allocates" an available connection to the client.+When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client.++++### Pool modes++Pool Mode determines how PgBouncer handles a connection.++#### Session++When a new client connects, a connection is assigned to the client until it disconnects. Afterward, the connection is returned back to the pool.++All PostgreSQL features can be used with this option.++#### Transaction++This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client+could be executed over two different connections.++Some session-based PostgreSQL features such as prepared statements are not available with this option.+A comprehensive list of incompatible features can be found [here](https://www.pgbouncer.org/features.html).++#### Statement++This is the most granular option. Connections are returned to the pool after every statement. Transactions with multiple statements are not allowed. This is best used when `AUTOCOMMIT` is in use.++### Finding the connection pool config++1. Go to the `Settings` section.+2. Click `Database`.+3. Find your Connection Info and Connection String. Connection pooling is on port `6543`.++<video width="99%" muted playsInline controls="true">+ <source+ src="/docs/videos/connection-pool-config.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Connecting with SSL++Use this when connecting to your database to prevent snooping and man-in-the-middle attacks.++Obtain your connection info and Server root certificate from your application’s dashboard.+++Assuming you’ve downloaded your certificate and it’s located at `$HOME/Downloads/prod-ca-2021.cer`, and your Host address is `db.abcdefghijklm.supabase.co` you can connect to the DB with+SSL enabled as illustrated below:++1. With `psql`++```+psql "sslmode=verify-full sslrootcert=$HOME/Downloads/prod-ca-2021.cer host=db.abcdefghijklm.supabase.co dbname=postgres user=postgres"+```++2. With `pgAdmin`+ a. Register a new Postgres server+ ++ b. Name your server to your liking and add the connection info.+ + ++3. Navigate to the SSL tab and change the SSL mode to Require. Next navigate to the Root certificate input, it will open up a+ file-picker modal. Select the certificate you downloaded from your Supabase dashboard and save the server details. PgAdmin+ should now be able to connect to your Postgres via SSL.+ diff --git a/apps/temp-docs/docs/guides/database/connecting/connecting-to-postgres.mdx b/apps/temp-docs/docs/guides/database/connecting/connecting-to-postgres.mdxdeleted file mode 100644index b7fa505608e..00000000000--- a/apps/temp-docs/docs/guides/database/connecting/connecting-to-postgres.mdx+++ /dev/null@@ -1,37 +0,0 @@-----id: connecting-to-postgres-title: "Overview"-description: There are various ways to connect to your Postgres database.------# Overview--Supabase provides several options for connection to your Postgres database:--- HTTP connections using the API.-- Direct connections using Postgres' standard connection system.-- Connection pooling using PgBouncer.--## HTTP--Supabase provides an auto-updating API. This is the easiest way to get started if you are managing data (fetching, inserting, updating). However you cannot manage the database schema-via the API (for security reasons). To do that you can either use the dashboard we provide or connect directly to your database.--## Direct vs Connection Pooling--A "direct connection" is when a connection is made to the database using Postgres' native connection implementation.--A "connection pool" is a system (external to Postgres)-which manage connections, rather than Postgres' native system.--Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of _temporary_ connections.-You can use these simple questions to determine which connection method to use:--- Are you connecting to a database and _maintaining_ a connection? If yes, use a direct connection.-- Are you connecting to your database and then _disconnecting_ immediately (e.g. a serverless environment)? If yes, use a connection pool.--## Resources--- [Direct Connections](/docs/guides/database/connecting/direct-connections).-- [Connection Pooling](/docs/guides/database/connecting/connection-pooling).-diff --git a/apps/temp-docs/docs/guides/database/connecting/connection-pooling.mdx b/apps/temp-docs/docs/guides/database/connecting/connection-pooling.mdxdeleted file mode 100644index 7b67315f0a5..00000000000--- a/apps/temp-docs/docs/guides/database/connecting/connection-pooling.mdx+++ /dev/null@@ -1,67 +0,0 @@-----id: connection-pooling-title: "Connection Pooling"-description: Connecting to your Supabase database using PgBouncer.------Connection pools are useful for managing a large number of _temporary_ connections.--## How connection pooling works--A "connection pool" is a system (external to Postgres) which manage connections, rather than PostgreSQL's native system. Supabase uses [PgBouncer](https://www.pgbouncer.org/) for connection pooling.--When a client makes a request, PgBouncer "allocates" and available connection to the client.-When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client.------## Pool modes--Pool Mode determines how PgBouncer handles a connection.--### Session--When a new client connects, a connection is assigned to the client until it disconnects. Afterward, the connection is returned back to the pool.--All PostgreSQL features can be used with this option.--### Transaction--This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client-could be executed over two different connections.--Some session-based PostgreSQL features such as prepared statements are not available with this option.-A comprehensive list of incompatible features can be found [here](https://www.pgbouncer.org/features.html).--### Statement--This is the most granular option. Connections are returned to the pool after every statement. Transactions with multiple statements are not allowed. This is best used when `AUTOCOMMIT` is in use.--## Finding your connection string--<Tabs-defaultActiveId="UI"->-<TabPanel id="UI" label="UI">--```sh-1. Go to the "Database" section.-2. Click "Connection Pooling".-3. Find your Connection Info and Connection String.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/pgbouncer-connection.mp4" type="video/mp4" muted playsInline />-</video>--</TabPanel>-</Tabs>----## Resources--- [Direct Connections](/docs/guides/database/connecting/direct-connections).-- [Connection Pooling](/docs/guides/database/connecting/connection-pooling).diff --git a/apps/temp-docs/docs/guides/database/connecting/direct-connections.mdx b/apps/temp-docs/docs/guides/database/connecting/direct-connections.mdxdeleted file mode 100644index 55916996d6a..00000000000--- a/apps/temp-docs/docs/guides/database/connecting/direct-connections.mdx+++ /dev/null@@ -1,36 +0,0 @@-----id: direct-connections-title: "Direct Connections"-description: Connecting to your Supabase database.------# Direct Connections--Every Supabase project provides a full Postgres database. You can connect to the database using any tool which supports Postgres.--## Finding your connection string--<Tabs-defaultActiveId="UI"->-<TabPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "Database".-3. Find your Connection Info and Connection String.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/postgres-connection.mp4" type="video/mp4" muted playsInline />-</video>--</TabPanel>-</Tabs>--## Resources--- [Direct Connections](/docs/guides/database/connecting/direct-connections).-- [Connection Pooling](/docs/guides/database/connecting/connection-pooling).--diff --git a/apps/temp-docs/docs/guides/database/extensions.mdx b/apps/temp-docs/docs/guides/database/extensions.mdxindex d8c7fe258c2..6a4bb750105 100644--- a/apps/temp-docs/docs/guides/database/extensions.mdx+++ b/apps/temp-docs/docs/guides/database/extensions.mdx@@ -5,62 +5,61 @@ description: Using Postgres extensions.---import ExtensionsComponent from '@site/src/components/Extensions'-import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Extensions are exactly as they sound - they "extend" the database with functionality which isn't part of the Postgres core.Supabase has pre-installed some of the most useful open source extensions.-### Enable and disable extensions--<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>-<TabsPanel id="UI" label="UI">--```sh-1. Go to the Database page-2. Click on "Extensions" in the sidebar-3. Find the extension you would like to enable/disable-4. Click the toggle.-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">+1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click **Extensions** in the sidebar.+3. Enable or disable an extension.<video width="99%" muted playsInline controls={true}>-<source src="/docs/videos/toggle-extensions.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/toggle-extensions.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>+</TabItem>+<TabItem value="sql">-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+```sql+-- Example: enable the "pgtap" extension and ensure it is installed+create extension pgtap with schema extensions;-```sql---- Example: enable the "pgtap" extension-create extension pgtap;---- Example: disable the "pgtap" extension+-- Example: disable the "pgtap" extensiondrop extension pgtap;-```-Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".-To disable an extension you can call `drop extension`.+Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".+To disable an extension call `drop extension`.-</TabsPanel>+:::caution+Enabling some extensions with `create extension <extension-name> with schema extensions` may lead to permission issues (e.g., `dblink`, `http`, `pg_cron`).+:::-</Tabs>+</TabItem>+</Tabs>### Full list of extensions-Supabase is pre-configured with over 50 extensions. You can also install your own SQL extensions directly into the database through our SQL editor.+Supabase is pre-configured with over 50 extensions. You can also install your own SQL extensions directly in the database through our SQL editor.<ExtensionsComponent />diff --git a/apps/temp-docs/docs/guides/database/extensions/http.mdx b/apps/temp-docs/docs/guides/database/extensions/http.mdxindex 7ab2d07aefe..c2ff431efc2 100644--- a/apps/temp-docs/docs/guides/database/extensions/http.mdx+++ b/apps/temp-docs/docs/guides/database/extensions/http.mdx@@ -1,13 +1,25 @@---id: http-title: "http: RESTful Client"+title: 'http: RESTful Client'description: An HTTP Client for PostgreSQL Functions.----# http: RESTful Client+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'The `http` extension allows you to call RESTful endpoints within Postgres.+## Quick demo++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/rARgrELRCwY"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>+## OverviewLet's cover some basic concepts:@@ -21,45 +33,40 @@ Let's cover some basic concepts:You can use the `http` extension to make these network requests from Postgres.-## Usage--### Enabling+### Enable the extension<Tabs-defaultActiveId="UI"->-<TabPanel id="UI" label="UI">--```sh-1. Go to the Database page.-2. Click on "Extensions" in the sidebar.-3. Search for "http".-4. Click the toggle.-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>+<TabItem value="dashboard">+1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Extensions** in the sidebar.+3. Search for "http" and enable the extension.-</TabPanel>-<TabPanel id="SQL" label="SQL">+</TabItem>+<TabItem value="sql">-```sql---- Example: enable the "http" extension+```sql+-- Example: enable the "http" extensioncreate extension http with schema extensions;--- Example: disable the "http" extension+-- Example: disable the "http" extensiondrop extension if exists http;-```-Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".-To disable an extension you can call `drop extension`.+Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".+To disable an extension, call `drop extension`.It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean.-</TabPanel>+</TabItem></Tabs>@@ -71,11 +78,11 @@ While the main usage is simply `http('http_request')`, there are 5 wrapper funct- `http_post()`- `http_put()`- `http_delete()`-- `http_head()`+- `http_head()`-### Returned values+### Returned values-A successful call to a web URL from the `http` extension returns a record with the following fields:+A successful call to a web URL from the `http` extension returns a record with the following fields:- `status`: integer- `content_type`: character varying@@ -87,19 +94,18 @@ A successful call to a web URL from the `http` extension returns a record with t### Simple `GET` example```sql-select+select"status", "content"::jsonb-from+fromhttp_get('https://jsonplaceholder.typicode.com/todos/1');```-### Simple `POST` example```sql-select+select"status", "content"::jsonb-from+fromhttp_post('https://jsonplaceholder.typicode.com/posts','{ "title": "foo", "body": "bar", "userId": 1 }',@@ -107,7 +113,6 @@ from);```+## Resources-## Resources--- Official [`http` Github Repository](https://github.com/pramsey/pgsql-http).+- Official [`http` GitHub Repository](https://github.com/pramsey/pgsql-http)diff --git a/apps/temp-docs/docs/guides/database/extensions/pgtap.mdx b/apps/temp-docs/docs/guides/database/extensions/pgtap.mdxindex 3ba365416cf..b80b7171e3c 100644--- a/apps/temp-docs/docs/guides/database/extensions/pgtap.mdx+++ b/apps/temp-docs/docs/guides/database/extensions/pgtap.mdx@@ -1,101 +1,131 @@---id: pgtap-title: "pgTAP: Unit Testing"+title: 'pgTAP: Unit Testing'description: Unit testing in PostgreSQL.----# pgTAP: Unit Testing+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'-`pgTAP` is a unit testing extension for PostgreSQL.+`pgTAP` is a unit testing extension for PostgreSQL.## OverviewLet's cover some basic concepts:- Unit tests: allow you to test small parts of a system (like a database table!).-- TAP: stands for [Test Anything Protocol](http://testanything.org/). It is an framework which aims to simplify the error reporting during testing.--+- TAP: stands for [Test Anything Protocol](http://testanything.org/). It is an framework which aims to simplify the error reporting during testing.## Usage--### Enabling+### Enable the extension<Tabs-defaultActiveId="UI"->-<TabPanel id="UI" label="Dashboad UI">--```sh-1. Go to the Database page.-2. Click on "Extensions" in the sidebar.-3. Search for "pgtap".-4. Click the toggle.-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>-<video width="99%" muted playsInline controls={true}>-<source src="/docs/videos/toggle-extensions.mp4" type="video/mp4" muted playsInline />-</video>+<TabItem value="dashboard">-</TabPanel>-<TabPanel id="SQL" label="SQL">+1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Extensions** in the sidebar.+3. Search for "pgtap" and enable the extension.-```sql+</TabItem>+<TabItem value="sql">--- Enable the "pgtap" extension+```sql+-- Enable the "pgtap" extensioncreate extension pgtap with schema extensions;--- Disable the "pgtap" extension+-- Disable the "pgtap" extensiondrop extension if exists pgtap;-```-Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".+Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".To disable an extension you can call `drop extension`.It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean.-</TabPanel>+</TabItem></Tabs>-### Managing tests--It's a good practice to keep all your tests in a separate schema.+### Testing tables```sql-create schema tests;+begin;+select plan( 1 );++select has_table( 'profiles' );++select * from finish();+rollback;```-### Creating a test+API:+- [`has_table()`](https://pgtap.org/documentation.html#has_table): Tests whether or not a table exists in the database+- [`has_index()`](https://pgtap.org/documentation.html#has_index): Checks for the existence of a named index associated with the named table.+- [`has_relation()`](https://pgtap.org/documentation.html#has_relation): Tests whether or not a relation exists in the database.-@TODO+### Testing columns-- Create a plan-- We should come up with a recommendation on how to run the tests. Via a function? External scripts?-- Eventually this can be done via our CLI+```sql+begin;+select plan( 2 );+select has_column( 'profiles', 'id' ); # test that the "id" column exists in the "profiles" table+select col_is_pk( 'profiles', 'id' ); # test that the "id" column is a primary key-### Running a test+select * from finish();+rollback;+```-@TODO+API:+- [`has_column()`](https://pgtap.org/documentation.html#has_column): Tests whether or not a column exists in a given table, view, materialized view or composite type.+- [`col_is_pk()`](https://pgtap.org/documentation.html#col_is_pk): Tests whether the specified column or columns in a table is/are the primary key for that table.-## Examples+### Testing RLS Policies-Let's look at a few different tests which could be helpful in your project.+```sql+begin;+select plan( 1 );+select policies_are(+ 'public',+ 'profiles',+ ARRAY [+ 'Profiles are public', # Test that there is a policy called "Profiles are public" on the "profiles" table.+ 'Profiles can only be updated by the owner' # Test that there is a policy called "Profiles can only be updated by the owner" on the "profiles" table.+ ]+);-### Testing tables+select * from finish();+rollback;+```++API:++- [`policies_are()`](https://pgtap.org/documentation.html#policies_are): Tests that all of the policies on the named table are only the policies that should be on that table.+- [`policy_roles_are()`](https://pgtap.org/documentation.html#policy_roles_are): Tests whether the roles to which policy applies are only the roles that should be on that policy.+- [`policy_cmd_is()`](https://pgtap.org/documentation.html#policy_cmd_is): Tests whether the command to which policy applies is same as command that is given in function arguments.+You can also use the `results_eq()` method to test that a Policy returns the correct data:```sqlbegin;select plan( 1 );-select has_table( 'profiles' );+select results_eq(+ 'select * from profiles()',+ $$VALUES ( 1, 'Anna'), (2, 'Bruce'), (3, 'Caryn')$$+ 'profiles() should return all users'+);+select * from finish();rollback;@@ -103,17 +133,18 @@ rollback;API:-- [`hasTable()`](https://pgtap.org/documentation.html#has_table)+- [`results_eq()`](https://pgtap.org/documentation.html#results_eq)+- [`results_ne()`](https://pgtap.org/documentation.html#results_ne)--### Testing columns+### Testing Functions```sqlbegin;select plan( 1 );-select has_column( 'profiles', 'id' );-select col_is_pk( 'profiles', 'id' );+select function_returns( 'hello_world', 'text' ); # test if the function "hello_world" returns text+select function_returns( 'is_even', ARRAY['integer'], 'boolean' ); # test if the function "is_even" returns a boolean+select results_eq('select * from hello_world()', 'hello'); # test if the function "hello_world" returns "hello"select * from finish();rollback;@@ -121,9 +152,9 @@ rollback;API:-- [`has_column()`](https://pgtap.org/documentation.html#has_column)-- [`col_is_pk()`](https://pgtap.org/documentation.html#col_is_pk)+- [`function_returns()`](https://pgtap.org/documentation.html#function_returns): Tests that a particular function returns a particular data type+- [`is_definer()`](https://pgtap.org/documentation.html#is_definer): Tests that a function is a security definer (i.e., a “setuid” function).-## Resources+## Resources-- Official [`pgTAP` documentation](https://pgtap.org/).+- Official [`pgTAP` documentation](https://pgtap.org/)diff --git a/apps/temp-docs/docs/guides/database/extensions/plv8.mdx b/apps/temp-docs/docs/guides/database/extensions/plv8.mdxindex 6ffaf6de5c6..927199f8464 100644--- a/apps/temp-docs/docs/guides/database/extensions/plv8.mdx+++ b/apps/temp-docs/docs/guides/database/extensions/plv8.mdx@@ -1,107 +1,104 @@---id: plv8-title: "plv8: Javascript Language"-description: Javascript language for PostgreSQL.+title: 'plv8: JavaScript Language'+description: JavaScript language for PostgreSQL.----# plv8: Javascript Language+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'-The `plv8` extension allows you use Javascript within Postgres.+The `plv8` extension allows you use JavaScript within Postgres.## Overview-While Postgres natively runs SQL, it can also run other "procedural languages".-`plv8` allows you to run Javascript code - specifically any code that runs on the [V8 Javascript engine](https://v8.dev).+While Postgres natively runs SQL, it can also run other "procedural languages".+`plv8` allows you to run JavaScript code - specifically any code that runs on the [V8 JavaScript engine](https://v8.dev).It can be used for database functions, triggers, queries and more.## Usage--### Enabling-+### Enable the extension<Tabs-defaultActiveId="UI"->-<TabPanel id="UI" label="Dashboard UI">--```sh-1. Go to the Database page.-2. Click on "Extensions" in the sidebar.-3. Search for "plv8".-4. Click the toggle.-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>-</TabPanel>-<TabPanel id="SQL" label="SQL">+<TabItem value="dashboard">-```sql+1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Extensions** in the sidebar.+3. Search for "plv8" and enable the extension.--- Example: enable the "plv8" extension+</TabItem>+<TabItem value="sql">++```sql+-- Example: enable the "plv8" extensioncreate extension plv8;--- Example: disable the "plv8" extension+-- Example: disable the "plv8" extensiondrop extension if exists plv8;-```-Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".-To disable an extension you can call `drop extension`.+Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".+To disable an extension, call `drop extension`.Procedural languages are automatically installed within `pg_catalog`, so you don't need to specify a schema.-</TabPanel>+</TabItem></Tabs>-### Creating `plv8` functions+### Create `plv8` functionsFunctions written in `plv8` are written just like any other PostgreSQL functions, onlywith the `language` identifier set to `plv8`.```sql-create or replace function function_name()+create or replace function function_name()returns void as $$- // V8 Javascript+ // V8 JavaScript// code// here$$ language plv8;```-You can call `plv8` functions like any other Postgres function:--+You can call `plv8` functions like any other Postgres function:<Tabs-defaultActiveId="SQL"->-<TabPanel id="SQL" label="SQL">+ defaultValue="sql"+ values={[+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ ]}>+<TabItem value="sql">```sqlselect function_name();```-</TabPanel>-<TabPanel id="JS" label="Javascript">--```js+</TabItem>+<TabItem value="javascript">+```jsconst { data, error } = supabase.rpc('function_name')-```-</TabPanel>+</TabItem></Tabs>## Examples-### Scalar Functions+### Scalar functionsA [scalar function](https://plv8.github.io/#scalar-function-calls) is anything that takes in some user input and returns a single result.```sql-create or replace function hello_world(name text)+create or replace function hello_world(name text)returns text as $$let output = `Hello, ${name}!`;@@ -110,16 +107,16 @@ returns text as $$$$ language plv8;```-### Executing SQL+### Executing SQLYou can execute SQL within `plv8` code using the [`plv8.execute` function](https://plv8.github.io/#plv8-execute).```sql-create or replace function update_user(id bigint, first_name text)+create or replace function update_user(id bigint, first_name text)returns smallint as $$var num_affected = plv8.execute(- 'update profiles set first_name = $1 where id = $2',+ 'update profiles set first_name = $1 where id = $2',[first_name, id]);@@ -127,12 +124,12 @@ returns smallint as $$$$ language plv8;```-### Set-returning Functions+### Set-returning functionsA [set-returning function](https://plv8.github.io/#set-returning-function-calls) is anything that returns a full set of results - for example, rows in a table.```sql-create or replace function get_messages()+create or replace function get_messages()returns setof messages as $$var json_result = plv8.execute(@@ -143,8 +140,7 @@ returns setof messages as $$$$ language plv8;```+## Resources-## Resources--- Official [`plv8` documentation](https://plv8.github.io/).-- [plv8 Github Repository](https://github.com/plv8/plv8).+- Official [`plv8` documentation](https://plv8.github.io/)+- [plv8 GitHub Repository](https://github.com/plv8/plv8)diff --git a/apps/temp-docs/docs/guides/database/extensions/uuid-ossp.mdx b/apps/temp-docs/docs/guides/database/extensions/uuid-ossp.mdxindex 790edf961db..2fe759a5cb6 100644--- a/apps/temp-docs/docs/guides/database/extensions/uuid-ossp.mdx+++ b/apps/temp-docs/docs/guides/database/extensions/uuid-ossp.mdx@@ -1,64 +1,63 @@---id: uuid-ossp-title: "uuid-ossp: Unique Identifiers"+title: 'uuid-ossp: Unique Identifiers'description: A UUID generator for PostgreSQL.----# uuid-ossp: Unique Identifiers--import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'The `uuid-ossp` extension can be used to generate a `UUID`.-## Overview-A `UUID` is a "Universally Unique Identifer" and it is, for practical purposes, unique.+A `UUID` is a "Universally Unique Identifer" and it is, for practical purposes, unique.This makes them particularly well suited as Primary Keys. It is occasionally referred to as a `GUID`, which stands for "Globally Unique Identifer".## Usage-### Enabling+### Enable the extension<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>-<TabsPanel id="UI" label="UI">--```sh-1. Go to the Database page.-2. Click on "Extensions" in the sidebar.-3. Search for "uuid-ossp".-4. Click the toggle.-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Extensions** in the sidebar.+3. Search for "uuid-ossp" and enable the extension.-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+**Note**:+Currently `uuid-ossp` extension is enabled by default and cannot be disabled.-```sql+</TabItem>+<TabItem value="sql">--- Example: enable the "uuid-ossp" extension+```sql+-- Example: enable the "uuid-ossp" extensioncreate extension "uuid-ossp" with schema extensions;--- Example: disable the "uuid-ossp" extension+-- Example: disable the "uuid-ossp" extensiondrop extension if exists "uuid-ossp";-```-Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".-To disable an extension you can call `drop extension`.+Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension".+To disable an extension, call `drop extension`.It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean.-</TabsPanel>+**Note**:+Currently `uuid-ossp` extension is enabled by default and cannot be disabled.++</TabItem></Tabs>-### The `uuid` type+### The `uuid` typeOnce the extension is enabled, you now have access to a `uuid` type.@@ -66,7 +65,7 @@ Once the extension is enabled, you now have access to a `uuid` type.Creates a UUID value based on the combination of computer’s MAC address, current timestamp, and a random value.-### `uuid_generate_v4()`+### `uuid_generate_v4()`Creates UUID values based solely on random numbers.@@ -92,7 +91,6 @@ create table contacts ();```+## Resources-## Resources--- [The Basics Of PostgreSQL `UUID` Data Type](https://www.postgresqltutorial.com/postgresql-uuid/).+- [The Basics Of PostgreSQL `UUID` Data Type](https://www.postgresqltutorial.com/postgresql-uuid/)diff --git a/apps/temp-docs/docs/guides/database/full-text-search.mdx b/apps/temp-docs/docs/guides/database/full-text-search.mdxindex 609eb3ad7b7..83ddd87afd1 100644--- a/apps/temp-docs/docs/guides/database/full-text-search.mdx+++ b/apps/temp-docs/docs/guides/database/full-text-search.mdx@@ -1,29 +1,26 @@---id: full-text-search-title: "Full Text Search"+title: 'Full Text Search'description: How to use full text search in PostgreSQL.----import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';-+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Postgres has built-in functions to handle `Full Text Search` queries. This is like a "search engine" within Postgres.-## PreparationFor this guide we'll use the following example data:-<Tabs-defaultActiveId="Data"+defaultValue="Data"values={[{label: 'Data', value: 'Data'},{label: 'SQL', value: 'SQL'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sqlcreate table books (@@ -33,8 +30,8 @@ create table books (description text);-insert into books (title, author, description)-values+insert into books (title, author, description)+values('The Poky Little Puppy','Janette Sebring Lowrey','Puppy is slower than other, bigger animals.'),('The Tale of Peter Rabbit','Beatrix Potter','Rabbit eats some vegetables.'),('Tootle','Gertrude Crampton','Little toy train has big dreams.'),@@ -42,18 +39,18 @@ values('Harry Potter and the Goblet of Fire','J.K. Rowling','Fourth year of school starts, big drama ensues.');```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description |-| ---- | ---- | ---- | ----------- |-| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |-| 2 | The Tale of Peter Rabbit | Beatrix Potter | Rabbit eats some vegetables. |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |-| 4 | Green Eggs and Ham | Dr. Seuss | Sam has changing food preferences and eats unusually colored food. |-| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. |+| id | title | author | description |+| --- | ----------------------------------- | ---------------------- | ------------------------------------------------------------------ |+| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |+| 2 | The Tale of Peter Rabbit | Beatrix Potter | Rabbit eats some vegetables. |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |+| 4 | Green Eggs and Ham | Dr. Seuss | Sam has changing food preferences and eats unusually colored food. |+| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. |-</TabsPanel>+</TabItem></Tabs>@@ -66,10 +63,10 @@ The functions we'll cover in this guide are:Converts your data into searchable "tokens". `to_tsvector()` stands for "to text search vector". For example:```sql-select to_tsvector("green eggs and ham")+select to_tsvector('green eggs and ham')-- Returns 'egg':2 'green':1 'ham':4-```+```Collectively these tokens are called a "document" which Postgres can use for comparisons.@@ -77,10 +74,9 @@ Collectively these tokens are called a "document" which Postgres can use for comConverts a query string into "tokens" to match. `to_tsquery()` stands for "to text search query".-This conversion step is important because we will want to "fuzzy match" on keywords.+This conversion step is important because we will want to "fuzzy match" on keywords.For example if a user searches for "eggs", and a column has the value "egg", we probably still want to return a match.-### Match: `@@`The `@@` symbol is the "match" symbol for Full Text Search. It returns any matches between a `to_tsvector` result and a `to_tsquery` result.@@ -88,86 +84,85 @@ The `@@` symbol is the "match" symbol for Full Text Search. It returns any matchTake the following example:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select *-from books-where name = 'Harry';+select *+from books+where title = 'Harry';```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase.from('books').select()- .eq('name', 'Harry')+ .eq('title', 'Harry')```-</TabsPanel>+</TabItem>-<TabsPanel id="DART" label="DART">+<TabItem value="DART">```dartfinal result = await client.from('books').select()- .eq('name', 'Harry')+ .eq('title', 'Harry').execute();```-</TabsPanel>+</TabItem></Tabs>--The equality symbol above (`=`) is very "strict" on what it matches. In a full text search context, we might want to find all "Harry Potter" books and so we can rewrite the+The equality symbol above (`=`) is very "strict" on what it matches. In a full text search context, we might want to find all "Harry Potter" books and so we can rewrite theexample above:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select *-from books-where to_tsvector(name) @@ to_tsquery('Harry');+select *+from books+where to_tsvector(title) @@ to_tsquery('Harry');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase.from('books').select()- .textSearch('name', `'Harry'`)+ .textSearch('title', `'Harry'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client.from('books').select()- .textSearch('name', "'Harry'")+ .textSearch('title', "'Harry'").execute();```-</TabsPanel>+</TabItem></Tabs>## Basic Full Text Queries@@ -177,27 +172,27 @@ final result = await clientTo find all `books` where the `description` contain the word `big`:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select- *-from+select+ *+frombooks-where- to_tsvector(description)+where+ to_tsvector(description)@@ to_tsquery('big');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -206,8 +201,8 @@ const { data, error } = await supabase.textSearch('description', `'big'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -217,15 +212,15 @@ final result = await client.execute();```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description |-| -- | ----------------------------------- | ----------------- | ----------------------------------------------- |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |-| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. |+| id | title | author | description |+| --- | ----------------------------------- | ----------------- | ----------------------------------------------- |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |+| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. |-</TabsPanel>+</TabItem></Tabs>### Search multiple columns@@ -233,60 +228,60 @@ final result = await clientTo find all `books` where `description` or `title` contain the word `little`:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select- *-from+select+ *+frombooks-where+whereto_tsvector(description || ' ' || title) -- concat columns, but be sure to include a space to separate them!@@ to_tsquery('little');```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description |-| -- | --------------------- | ---------------------- | ------------------------------------------- |-| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |+| id | title | author | description |+| --- | --------------------- | ---------------------- | ------------------------------------------- |+| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |-</TabsPanel>+</TabItem></Tabs>### Match all search words-To find all `books` where `description` contains BOTH of the words `little` and `big`, we can use the `&` symbol:+To find all `books` where `description` contains BOTH of the words `little` and `big`, we can use the `&` symbol:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select- *-from+select+ *+frombooks-where+whereto_tsvector(description)@@ to_tsquery('little & big'); -- use & for AND in the search query```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -295,8 +290,8 @@ const { data, error } = await supabase.textSearch('description', `'little' & 'big'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -306,14 +301,14 @@ final result = await client.execute();```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description |-| -- | ------ | ----------------- | -------------------------------- |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |+| id | title | author | description |+| --- | ------ | ----------------- | -------------------------------- |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |-</TabsPanel>+</TabItem></Tabs>### Match any search words@@ -321,27 +316,27 @@ final result = await clientTo find all `books` where `description` contain ANY of the words `little` or `big`, use the `|` symbol:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select- *-from+select+ *+frombooks-where- to_tsvector(description)+where+ to_tsvector(description)@@ to_tsquery('little | big'); -- use | for OR in the search query```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -350,8 +345,8 @@ const { data, error } = await supabase.textSearch('description', `'little' | 'big'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -361,64 +356,64 @@ final result = await client.execute();```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description |-| -- | --------------------- | ---------------------- | ------------------------------------------- |-| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |+| id | title | author | description |+| --- | --------------------- | ---------------------- | ------------------------------------------- |+| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. |-</TabsPanel>+</TabItem></Tabs>Notice how searching for `big` includes results with the word `bigger` (or `biggest`, etc).## Creating Indexes-Now that we have Full Text Search working, let's create an `index`. This will allow Postgres to "build" the documents pre-emptively so that they+Now that we have Full Text Search working, let's create an `index`. This will allow Postgres to "build" the documents pre-emptively so that theydon't need to be created at the time we execute the query. This will make our queries much faster.### Searchable columns-Let's create a new column `fts` inside the `books` table to store the searchable index of the `title` and `description` columns.+Let's create a new column `fts` inside the `books` table to store the searchable index of the `title` and `description` columns.-We can use a special feature of Postgres called-[Generated Columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html)+We can use a special feature of Postgres called+[Generated Columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html)to ensure that the index is updated any time the values in the `title` and `description` columns change.<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-alter table- books-add column+alter table+ books+add columnfts tsvector generated always as (to_tsvector('english', description || ' ' || title)) stored;-+create index books_fts on books using gin (fts); -- generate the index-select id, fts+select id, ftsfrom books;```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | fts |-| -- | --------------------------------------------------------------------------------------------------------------- |-| 1 | 'anim':7 'bigger':6 'littl':10 'poki':9 'puppi':1,11 'slower':3 |-| 2 | 'eat':2 'peter':8 'rabbit':1,9 'tale':6 'veget':4 |-| 3 | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 |-| 4 | 'chang':3 'color':9 'eat':7 'egg':12 'food':4,10 'green':11 'ham':14 'prefer':5 'sam':1 'unus':8 |-| 5 | 'big':6 'drama':7 'ensu':8 'fire':15 'fourth':1 'goblet':13 'harri':9 'potter':10 'school':4 'start':5 'year':2 |+| id | fts |+| --- | --------------------------------------------------------------------------------------------------------------- |+| 1 | 'anim':7 'bigger':6 'littl':10 'poki':9 'puppi':1,11 'slower':3 |+| 2 | 'eat':2 'peter':8 'rabbit':1,9 'tale':6 'veget':4 |+| 3 | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 |+| 4 | 'chang':3 'color':9 'eat':7 'egg':12 'food':4,10 'green':11 'ham':14 'prefer':5 'sam':1 'unus':8 |+| 5 | 'big':6 'drama':7 'ensu':8 'fire':15 'fourth':1 'goblet':13 'harri':9 'potter':10 'school':4 'start':5 'year':2 |-</TabsPanel>+</TabItem></Tabs>### Search using the new column@@ -426,26 +421,26 @@ from books;Now that we've created and populated our index, we can search it using the same techniques as before:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},{label: 'Data', value: 'Data'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select- *-from+select+ *+frombooks-where+wherefts @@ to_tsquery('little & big');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -454,8 +449,8 @@ const { data, error } = await supabase.textSearch('fts', `'little' & 'big'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -465,14 +460,14 @@ final result = await client.execute();```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>+<TabItem value="Data">-| id | title | author | description | fts |-| -- | ------ | ----------------- | -------------------------------- | ------------------------------------------------------- |-| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 |+| id | title | author | description | fts |+| --- | ------ | ----------------- | -------------------------------- | ------------------------------------------------------- |+| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 |-</TabsPanel>+</TabItem></Tabs>## Query Operators@@ -485,27 +480,26 @@ to learn about additional query operators you can use to do more advanced `fullThe proximity symbol is useful for searching for terms that are a certain "distance" apart.For example, to find the phrase `big dreams`, where the a match for "big" is followed immediately by a match for "dreams":-<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select+select*-from+frombooks-where+whereto_tsvector(description) @@ to_tsquery('big <-> dreams');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -514,8 +508,8 @@ const { data, error } = await supabase.textSearch('description', `'big' <-> 'dreams'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -525,32 +519,31 @@ final result = await client.execute();```-</TabsPanel>+</TabItem></Tabs>-We can also use the `<->` to find words within a certain distance of eachother. For example to find `year` and `school` within 2 words of each other:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select+select*-from+frombooks-where+whereto_tsvector(description) @@ to_tsquery('year <2> school');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -559,8 +552,8 @@ const { data, error } = await supabase.textSearch('description', `'year' <2> 'school'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -570,35 +563,34 @@ final result = await client.execute();```-</TabsPanel>+</TabItem></Tabs>-### Negation: `!`The negation symbol can be used to find phrases which _don't_ contain a search term.For example, to find records that have the word `big` but not `little`:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},- {label: 'Javascript', value: 'JS'},+ {label: 'JavaScript', value: 'JS'},{label: 'Dart', value: 'DART'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sql-select+select*-from+frombooks-where+whereto_tsvector(description) @@ to_tsquery('big & !little');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">```jsconst { data, error } = await supabase@@ -607,8 +599,8 @@ const { data, error } = await supabase.textSearch('description', `'big' & !'little'`)```-</TabsPanel>-<TabsPanel id="DART" label="DART">+</TabItem>+<TabItem value="DART">```dartfinal result = await client@@ -618,13 +610,9 @@ final result = await client.execute();```-</TabsPanel>+</TabItem></Tabs>-## Resources-* [PostgreSQL: Text Search Functions and Operators](https://www.postgresql.org/docs/12/functions-textsearch.html)---+- [PostgreSQL: Text Search Functions and Operators](https://www.postgresql.org/docs/12/functions-textsearch.html)diff --git a/apps/temp-docs/docs/guides/database/functions.mdx b/apps/temp-docs/docs/guides/database/functions.mdxindex 9065663cb7b..532752d97a5 100644--- a/apps/temp-docs/docs/guides/database/functions.mdx+++ b/apps/temp-docs/docs/guides/database/functions.mdx@@ -1,109 +1,40 @@---id: functions-title: Functions+title: Database Functionsdescription: Creating and using Postgres functions.----import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'--Postgres has built-in support for [SQL functions](https://www.postgresql.org/docs/current/sql-createfunction.html).-These functions live inside your database, and they can be [used with the API](/docs/reference/javascript/rpc).+Postgres has built-in support for [SQL functions](https://www.postgresql.org/docs/current/sql-createfunction.html).+These functions live inside your database, and they can be [used with the API](../../reference/javascript/rpc).## Quick demo-<iframe- className="w-full video-with-border"- width="640"- height="385"- src="https://www.youtube-nocookie.com/embed/MJZCCpCYEqk"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen-></iframe>+<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/MJZCCpCYEqk"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>-## Creating Functions+## Getting started-Supabase provides several options for creating database functions. You can use the Dashboard or create them directly using SQL.-We provide a SQL editor within the Dashboard, or you can [connect](/docs/guides/database/connecting/connecting-to-postgres) to your database+Supabase provides several options for creating database functions. You can use the Dashboard or create them directly using SQL.+We provide a SQL editor within the Dashboard, or you can [connect](../../guides/database/connecting-to-postgres) to your databaseand run the SQL queries yourself.-1. Go to the "SQL editor" section.2. Click "New Query".3. Enter the SQL to create or replace your Database function.4. Click "Run" or cmd+enter (ctrl+enter).-## Examples--### Data set--For this guide we'll use the following example data:+## Simple Functions--<Tabs-defaultActiveId="Data"-values={[- {label: 'Data', value: 'Data'},- {label: 'SQL', value: 'SQL'},-]}>--<TabsPanel id="SQL" label="SQL">--```sql-create table planets (- id serial primary key,- name text-);--insert into planets (id, name)-values- (1, 'Tattoine'),- (2, 'Alderaan'),- (3, 'Kashyyyk');--create table people (- id serial primary key,- name text,- planet_id bigint references planets-);--insert into people (id, name, planet_id)-values- (1, 'Anakin Skywalker', 1),- (2, 'Luke Skywalker', 1),- (3, 'Princess Leia', 2),- (4, 'Chewbacca', 3);-```--</TabsPanel>-<TabsPanel id="Data" label="Data">--<h4>Planets</h4>--| id | name |-| ---- | ---- |-| 1 | Tattoine |-| 2 | Alderaan |-| 3 | Kashyyyk |--<h4>People</h4>--| id | name | planet_id |-| ---- | ---- | ---- |-| 1 | Anakin Skywalker | 1 |-| 2 | Luke Skywalker | 1 |-| 3 | Princess Leia | 2 |-| 4 | Chewbacca | 3 |--</TabsPanel>--</Tabs>--### Basic function--A basic example which returns a string "hello world".+Let's create a basic Database Function which returns a string "hello world".```sqlcreate or replace function hello_world() -- 1@@ -117,66 +48,129 @@ $$; --6<details><summary>Show/Hide Details</summary>-+At it's most basic a function has the following parts:1. `create or replace function hello_world()`: The function declaration, where `hello_world` is the name of the function. You can use either `create` when creating a new function or `replace` when replacing an existing function. Or you can use `create or replace` together to handle either.-2. `returns text`: The type of data that the function returns. If it returns nothing, you can `returns void`.+2. `returns text`: The type of data that the function returns. If it returns nothing, you can `returns void`.3. `language sql`: The language used inside the function body. This can also be a procedural language: `plpgsql`, `plv8`, `plpython`, etc.4. `as $$`: The function wrapper. Anything enclosed inside the `$$` symbols will be part of the function body.5. `select 'hello world';`: A simple function body. The final `select` statement inside a function body will be returned if there are no statements following it.-6. `$$;`: The closing symbols of the funciton wrapper.+6. `$$;`: The closing symbols of the function wrapper.</details>-#### Execute+<br />++After the Function is created, we have several ways of "executing" the function - either directly inside the database using SQL, or with one of the client libraries.<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},{label: 'JS', value: 'JS'},{label: 'Dart', value: 'Dart'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sqlselect hello_world();```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">-```js-const { data, error } = supabase- .rpc('hello_world')+```js+const { data, error } = await supabase.rpc('hello_world')```-Reference: [rpc()](/docs/reference/javascript/rpc)+Reference: [rpc()](../../reference/javascript/rpc)-</TabsPanel>-<TabsPanel id="Dart" label="Dart">+</TabItem>+<TabItem value="Dart">-```dart+```dartfinal res = await supabase.rpc('hello_world').execute();```-Reference: [rpc()](/docs/reference/dart/rpc)+Reference: [rpc()](../../reference/dart/rpc)-</TabsPanel>+</TabItem></Tabs>+## Returning data sets++Database Functions can also return data sets from [Tables](../../guides/database/tables) or Views.++For example, if we had a database with some Star Wars data inside:++<Tabs+defaultValue="Data"+values={[+ {label: 'Data', value: 'Data'},+ {label: 'SQL', value: 'SQL'},+]}>++<TabItem value="SQL">++```sql+create table planets (+ id serial primary key,+ name text+);++insert into planets (id, name)+values+ (1, 'Tattoine'),+ (2, 'Alderaan'),+ (3, 'Kashyyyk');++create table people (+ id serial primary key,+ name text,+ planet_id bigint references planets+);++insert into people (id, name, planet_id)+values+ (1, 'Anakin Skywalker', 1),+ (2, 'Luke Skywalker', 1),+ (3, 'Princess Leia', 2),+ (4, 'Chewbacca', 3);+```++</TabItem>+<TabItem value="Data">-### Return table sets+<h4>Planets</h4>-A basic example which return all the `planets` in our example data set.+| id | name |+| --- | -------- |+| 1 | Tattoine |+| 2 | Alderaan |+| 3 | Kashyyyk |++<h4>People</h4>++| id | name | planet_id |+| --- | ---------------- | --------- |+| 1 | Anakin Skywalker | 1 |+| 2 | Luke Skywalker | 1 |+| 3 | Princess Leia | 2 |+| 4 | Chewbacca | 3 |++</TabItem>++</Tabs>++We could create a function which returns all the planets:```sql-create or replace function get_planets()+create or replace function get_planets()returns setof planetslanguage sqlas $$@@ -184,19 +178,17 @@ as $$$$;```-#### Execute-Because this function returns a table set, we can also apply filters and selectors. For example, if we only wanted the first planet:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},{label: 'JS', value: 'JS'},{label: 'Dart', value: 'Dart'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sqlselect *@@ -204,44 +196,37 @@ from get_planets()where id = 1;```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">-```js-const { data, error } = supabase- .rpc('get_planets')- .eq('id', 1)+```js+const { data, error } = supabase.rpc('get_planets').eq('id', 1)```-Reference: [rpc()](/docs/reference/javascript/rpc)+</TabItem>+<TabItem value="Dart">-</TabsPanel>-<TabsPanel id="Dart" label="Dart">--```dart+```dartfinal res = await supabase.rpc('get_planets').eq('id', 1).execute();```-Reference: [rpc()](/docs/reference/dart/rpc)--</TabsPanel>+</TabItem></Tabs>+## Passing parameters-### With parameters--A basic example which will insert a new planet into the `planets` and return the new ID. Note that this time we're using the `plpgsql` language.+Let's create a Function to insert a new planet into the `planets` table and return the new ID. Note that this time we're using the `plpgsql` language.```sql-create or replace function add_planet(name text)+create or replace function add_planet(name text)returns bigintlanguage plpgsqlas $$-declare+declarenew_row bigint;begininsert into planets(name)@@ -253,51 +238,120 @@ end;$$;```-#### Execute--Because this function returns a table set, we can also apply filters and selectors. For example, if we only wanted the `name` of the first planet:+Once again, you can execute this function either inside your database using a `select` query, or with the client libraries:<Tabs-defaultActiveId="SQL"+defaultValue="SQL"values={[{label: 'SQL', value: 'SQL'},{label: 'JS', value: 'JS'},{label: 'Dart', value: 'Dart'},]}>-<TabsPanel id="SQL" label="SQL">+<TabItem value="SQL">```sqlselect * from add_planet('Jakku');```-</TabsPanel>-<TabsPanel id="JS" label="JS">+</TabItem>+<TabItem value="JS">-```js-const { data, error } = supabase- .rpc('add_planet', { name: 'Jakku' })+```js+const { data, error } = await supabase.rpc('add_planet', { name: 'Jakku' })```-Reference: [rpc()](/docs/reference/javascript/rpc)+</TabItem>+<TabItem value="Dart">-</TabsPanel>-<TabsPanel id="Dart" label="Dart">--```dart+```dartfinal res = await supabase.rpc('add_planet', params: { 'name': 'Jakku' }).execute();```-Reference: [rpc()](/docs/reference/dart/rpc)--</TabsPanel>+</TabItem></Tabs>+## Suggestions++### Database Functions vs Edge Functions++For data-intensive operations, use Database Functions, which are executed within your database+and can be called remotely using the [REST and GraphQL API](../api).++For use-cases which require low-latency, use [Edge Functions](../../guides/functions), which are globally-distributed and can be written in Typescript.++### Security `definer` vs `invoker`++Postgres allows you to specify whether you want the function to be executed as the user _calling_ the function (`invoker`), or as the _creator_ of the function (`definer`). For example:++```sql+create function hello_world()+returns text+language plpgsql+security definer set search_path = public+as $$+begin+ select 'hello world';+end;+$$;+```++It is best practice to use `security invoker` (which is also the default). If you ever use `security definer`, you _must_ set the `search_path`.+This limits the potential damage if you allow access to schemas which the user executing the function should not have.++### Function privileges++By default, database functions can be executed by any role. You can restrict this by altering the default privileges and then choosing which roles can execute functions.++```sql+ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;++-- Choose which roles can execute functions+GRANT EXECUTE ON FUNCTION hello_world TO authenticated;+GRANT EXECUTE ON FUNCTION hello_world TO service_role;+```## Resources+- Official Client libraries: [JavaScript](../../reference/javascript/rpc) and [Flutter](../../reference/dart/rpc)+- Community client libraries: [github.com/supabase-community](https://github.com/supabase-community)- PostgreSQL Official Docs: [Chapter 9. Functions and Operators](https://www.postgresql.org/docs/current/functions.html)- PostgreSQL Reference: [CREATE FUNCTION](https://www.postgresql.org/docs/9.1/sql-createfunction.html)++## Deep Dive++### Create Database Functions++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/MJZCCpCYEqk"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++### Call Database Functions using JavaScript++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/I6nnp9AINJk"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++### Using Database Functions to call an external API++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/rARgrELRCwY"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>diff --git a/apps/temp-docs/docs/guides/database/introduction.mdx b/apps/temp-docs/docs/guides/database/introduction.mdxdeleted file mode 100644index 697a1afa767..00000000000--- a/apps/temp-docs/docs/guides/database/introduction.mdx+++ /dev/null@@ -1,37 +0,0 @@-----id: introduction-title: "Introduction"-slug: introduction------import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';--Every Supabase project comes with a full Postgres database, a free and open source-database which is considered one of the world's most stable and advanced databases.---## Postgres or PostgreSQL?---The database was derived from the POSTGRES Project, a package written at the University of California at Berkeley in 1986.-This package included a query language called "PostQUEL".--In 1994, Postgres95 was built on top of POSTGRES code, adding an SQL language interpreter as a replacement for PostQUEL.-Eventually, Postgres95 was renamed to PostgreSQL to reflect the SQL query capability.--After this, many people referred to it as Postgres since it's less prone to confusion. Supabase is all about-simplicity, so we also refer to it as Postgres.--<!----## Relational--Postgres is a Relational Database.--## SQL---Postgres is a SQL database.---->\ No newline at end of filediff --git a/apps/temp-docs/docs/guides/database/json.mdx b/apps/temp-docs/docs/guides/database/json.mdxindex ab54768fba9..e65429d53de 100644--- a/apps/temp-docs/docs/guides/database/json.mdx+++ b/apps/temp-docs/docs/guides/database/json.mdx@@ -5,26 +5,47 @@ description: Using the JSON data type in PostgreSQL.---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'PostgreSQL supports [JSON functions and operators](https://www.postgresql.org/docs/current/functions-json.html) which gives flexibility when storing data inside a database column.PostgreSQL supports two types of JSON columns: `JSON` and `JSONB`.-The recommended type is `JSONB` for almost all cases.When you use the `JSONB` format, the data is parsed when it's put into the database so it's faster when querying and also it can be indexed.-## Steps--### Create a table with a JSON column.+## Create a table with a JSON column<Tabs-defaultActiveId="SQL"-values={[- {label: 'SQL', value: 'SQL'},- {label: 'UI', value: 'UI'},-]}>-<TabsPanel id="SQL" label="SQL">+ groupId="json"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+2. Click **New Table** and create a table called `books`.+3. Include a primary key with the following properties:+ - Name: `id`+ - Type: `int8`+ - Default value: `Automatically generate as indentity`+4. Click **Save**.+5. Click **New Column** and add 3 columns with the following properties:+ - **title** column+ - Name: `title`+ - Type: `text`+ - **author** column+ - Name: `author`+ - Type: `text`+ - **metadata** column+ - Name: `metadata`+ - Type: `jsonb`++</TabItem>++<TabItem value="sql">```sqlcreate table books (@@ -35,51 +56,25 @@ create table books ();```-</TabsPanel>-<TabsPanel id="UI" label="UI">--```sh-Create the table:--1. Go to the Table Editor-2. Click "New Table"-3. Name the table "books"-4. Include a primary key with the following properties:- - Name: "id"- - Type: "int8"- - Default value: "Automatically generate as indentity"-5. Click "Save"---Click "New Column" and 3 new columns with the following properties:--1. title column:- - Name: "title"- - Type: "text"--2. author column:- - Name: "author"- - Type: "text"--3. metadata column:- - Name: "metadata"- - Type: "jsonb"-```--</TabsPanel>+</TabItem></Tabs>-### Insert data into the table.+## Insert data into the table<Tabs-defaultActiveId="Data"-values={[- {label: 'Data', value: 'Data'},- {label: 'SQL', value: 'SQL'},- {label: 'UI', value: 'UI'},- {label: 'JS', value: 'JavaScript'},-]}>-<TabsPanel id="Data" label="Data">+ groupId="json"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ ]}>++<TabItem value="dashboard">++1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+2. Select the `books` table in the sidebar.+3. Click **+ Insert row** and add 5 rows with the following properties:| id | title | author | metadata || --- | ----------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |@@ -89,8 +84,9 @@ values={[| 4 | Green Eggs and Ham | Dr. Seuss | {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."} || 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."} |-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+</TabItem>++<TabItem value="sql">```sqlinsert into books@@ -123,41 +119,9 @@ values);```-</TabsPanel>-<TabsPanel id="UI" label="UI">--```bash-- click `Table Editor`-- click `books`-- click `+ Insert Row`- - `title`: `The Poky Little Puppy`- - `author`: 'Janette Sebring Lowrey'- - `metadata`: {"description":"Puppy is slower than other, bigger animals.","price":5.95,"ages":[3,6]}- - click `Save`-- click `+ Insert Row`- - `title`: `The Tale of Peter Rabbit`- - `author`: 'Beatrix Potter'- - `metadata`: {"ages":[2,5],"price":4.49,"description":"Rabbit eats some vegetables."}- - click `Save`-- click `+ Insert Row`- - `title`: `Tootle`- - `author`: 'Gertrude Crampton'- - `metadata`: {"ages":[2,5],"price":3.99,"description":"Little toy train has big dreams."}- - click `Save`-- click `+ Insert Row`- - `title`: `Green Eggs and Ham`- - `author`: 'Dr. Seuss'- - `metadata`: {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."}- - click `Save`-- click `+ Insert Row`- - `title`: `Harry Potter and the Goblet of Fire`- - `author`: 'J.K. Rowling'- - `metadata`: {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."}- - click `Save`-```+</TabItem>-</TabsPanel>-<TabsPanel id="JavaScript" label="JavaScript">+<TabItem value="javascript">```jsconst { data, error } = await supabase.from('books').insert([@@ -173,18 +137,27 @@ const { data, error } = await supabase.from('books').insert([{title: 'The Tale of Peter Rabbit',author: 'Beatrix Potter',- metadata: { description: 'Rabbit eats some vegetables.', price: 4.49, ages: [2, 5] },+ metadata: {+ description: 'Rabbit eats some vegetables.',+ price: 4.49,+ ages: [2, 5],+ },},{title: 'Tootle',author: 'Gertrude Crampton',- metadata: { description: 'Little toy train has big dreams.', price: 3.99, ages: [2, 5] },+ metadata: {+ description: 'Little toy train has big dreams.',+ price: 3.99,+ ages: [2, 5],+ },},{title: 'Green Eggs and Ham',author: 'Dr. Seuss',metadata: {- description: 'Sam has changing food preferences and eats unusually colored food.',+ description:+ 'Sam has changing food preferences and eats unusually colored food.',price: 7.49,ages: [4, 8],},@@ -201,35 +174,39 @@ const { data, error } = await supabase.from('books').insert([])```-</TabsPanel>+</TabItem></Tabs>-### View the data.+## View the data<Tabs-defaultActiveId="SQL"-values={[- {label: 'SQL', value: 'SQL'},- {label: 'JS', value: 'JavaScript'},- {label: 'Data', value: 'Data'},-]}>-<TabsPanel id="SQL" label="SQL">+ groupId="json"+ defaultValue="sql"+ values={[+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Result', value: 'result'},+ ]}>++<TabItem value="sql">```sqlselect *from books;```-</TabsPanel>-<TabsPanel id="JavaScript" label="JavaScript">+</TabItem>++<TabItem value="javascript">```jsconst { data, error } = await supabase.from('books').select('*')console.log(JSON.stringify(data, null, 2))```-</TabsPanel>-<TabsPanel id="Data" label="Data">+</TabItem>++<TabItem value="result">| id | title | author | metadata || --- | ----------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |@@ -239,26 +216,25 @@ console.log(JSON.stringify(data, null, 2))| 4 | Green Eggs and Ham | Dr. Seuss | {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."} || 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."} |-NOTICE: The data as it appears here will have the `JSONB` fields in a different order than when we inserted them.-As we said earlier about the differences between the `JSON` and `JSONB` fields:--> When you use the `JSONB` format, the data is parsed when it's put into the database...+The data as it appears here has the `JSONB` fields in a different order than when inserted. As mentioned earlier, data is parsed as its inserted when using the JSONB format.-</TabsPanel>+</TabItem></Tabs>-### Query the `JSONB` data.+## Query the `JSONB` data-#### Select title, description, price, and age range for each book.+Select the title, description, price, and age range for each book.<Tabs-defaultActiveId="SQL"-values={[- {label: 'SQL', value: 'SQL'},- {label: 'JS', value: 'JavaScript'},- {label: 'Results', value: 'Results'}-]}>-<TabsPanel id="SQL" label="SQL">+ groupId="json"+ defaultValue="sql"+ values={[+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Result', value: 'result'}+ ]}>++<TabItem value="sql">```sqlselect@@ -271,8 +247,9 @@ frombooks;```-</TabsPanel>-<TabsPanel id="JavaScript" label="JavaScript">+</TabItem>++<TabItem value="javascript">```jsconst { data, error } = await supabase@@ -283,8 +260,9 @@ const { data, error } = await supabaseconsole.log(JSON.stringify(data, null, 2))```-</TabsPanel>-<TabsPanel id="Results" label="Results">+</TabItem>++<TabItem value="result">| title | description | price | low_age | high_age || ----------------------------------- | ------------------------------------------------------------------ | ----- | ------- | -------- |@@ -294,19 +272,16 @@ console.log(JSON.stringify(data, null, 2))| Green Eggs and Ham | Sam has changing food preferences and eats unusually colored food. | 7.49 | 4 | 8 || Harry Potter and the Goblet of Fire | Fourth year of school starts, big drama ensues. | 24.95 | 10 | 99 |-</TabsPanel>+</TabItem></Tabs>-#### Data Types--One last thing to note: the -> operator returns JSONB data. If you want TEXT/STRING data returned, you need to use the ->> operator.+Note that the `->` operator returns JSONB data. If you want TEXT/STRING data returned, use the `->>` operator.-- metadata -> 'description' (this returns a JSON object)-- metadata ->> 'description' (this returns STRING/TEXT data)+- metadata -> 'description' (returns a JSON object)+- metadata ->> 'description' (returns STRING/TEXT data)## Resources-- [Supabase Account - Free Tier OK](https://supabase.com)- [Supabase JS Client](https://github.com/supabase/supabase-js)- [PostgreSQL: JSON Functions and Operators](https://www.postgresql.org/docs/12/functions-json.html)- [PostgreSQL JSON types](https://www.postgresql.org/docs/12/datatype-json.html)diff --git a/apps/temp-docs/docs/guides/database/managing-passwords.mdx b/apps/temp-docs/docs/guides/database/managing-passwords.mdxindex 3cf0df757ec..b7cba2b6354 100644--- a/apps/temp-docs/docs/guides/database/managing-passwords.mdx+++ b/apps/temp-docs/docs/guides/database/managing-passwords.mdx@@ -1,32 +1,20 @@---id: managing-passwords-title: "Passwords"+title: 'Passwords'description: How to change your PostgreSQL database password.----# Passwords+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Your PostgreSQL database is the core of your Supabase project, so it's important that it has a strong, secure password at all times.If you use special symbols in your postgres password, you must remember to [percent-encode](https://en.wikipedia.org/wiki/Percent-encoding) your password later if using the postgres connection string e.g. `postgresql://postgres:p%[email protected]:5432/postgres`-### Changing your project passwordWhen you created your project you were also asked to enter a password. This is actually the password for your database, specifically for the `postgres` user.-You can update this using SQL:--<Tabs defaultActiveId="SQL">-<TabPanel id="SQL" label="SQL">--```sql-alter user postgres- with password 'new_password';-```--</TabPanel>-</Tabs>-+You can update this from the Dashboard under the [database settings](https://app.supabase.com/project/_/settings/database) page.## Creating a secure password@@ -40,4 +28,3 @@ It's absolutely critical that you store your customers' data safely. Here are so## Resources- [PostgreSQL `ALTER USER` Documentation](https://www.postgresql.org/docs/12/sql-alteruser.html)-diff --git a/apps/temp-docs/docs/guides/database/managing-timezones.mdx b/apps/temp-docs/docs/guides/database/managing-timezones.mdxindex 69047fb060d..8a2f67d9c7b 100644--- a/apps/temp-docs/docs/guides/database/managing-timezones.mdx+++ b/apps/temp-docs/docs/guides/database/managing-timezones.mdx@@ -1,31 +1,31 @@---id: managing-timezones-title: "Timezones"+title: 'Timezones'slug: managing-timezonesdescription: How to change your database timezone.----# Timezones+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Every Supabase database is set to UTC timezone by default. We strongly recommend keeping it this way, even if your users are in a different location.This is because it makes it much easier to calculate differences between timezones if you adopt the mental model that "everything in my database is in UTC time".-### Change timezone+<Tabs+ defaultValue="sql"+ groupId="reference/postgres"+ values={[{ label: 'SQL', value: 'sql' }]}>--<Tabs defaultActiveId="sql">--<TabPanel id="sql" label="SQL">+<TabItem value="sql">```sql-alter database postgres+alter database postgresset timezone to 'America/New_York';```--</TabPanel>+</TabItem></Tabs>@@ -38,19 +38,20 @@ Get a full list of timezones supported by your database. This will return the fo- `utc_offset`: Offset from UTC (positive means east of Greenwich)- `is_dst`: True if currently observing daylight savings+<Tabs+ defaultValue="sql"+ groupId="reference/postgres"+ values={[{ label: 'SQL', value: 'sql' }]}>-<Tabs defaultActiveId="sql">--<TabPanel value="sql">+<TabItem value="sql">```sqlselect name, abbrev, utc_offset, is_dst-from pg_timezone_names()+from pg_timezone_names()order by name;```--</TabPanel>+</TabItem></Tabs>@@ -59,15 +60,18 @@ order by name;Use `ilike` (case insensitive search) to find specific timezones.<Tabs- defaultActiveId="sql">+ defaultValue="sql"+ groupId="reference/postgres"+ values={[{ label: 'SQL', value: 'sql' }]}>-<TabPanel value="sql" label="SQL">+<TabItem value="sql">```sql-select *-from pg_timezone_names()+select *+from pg_timezone_names()where name ilike '%york%';```-</TabPanel>++</TabItem></Tabs>diff --git a/apps/temp-docs/docs/guides/database/migrating-between-projects.mdx b/apps/temp-docs/docs/guides/database/migrating-between-projects.mdxnew file mode 100644index 00000000000..c7a877a0462--- /dev/null+++ b/apps/temp-docs/docs/guides/database/migrating-between-projects.mdx@@ -0,0 +1,118 @@+---+id: migrating-between-projects+title: 'Migrating Between Projects'+description: Migrate data from one project to another+---++Migrating projects can be achieved using standard PostgreSQL tooling. This is particularly useful for older projects (e.g. to use a newer Postgres version).++## Before you begin++- Install [Postgres](https://www.postgresql.org/download/) so you can run `psql` and `pg_dump`.+- Create a new [Supabase project](https://app.supabase.com).+- Store the old project's database URL as `$OLD_DB_URL` and the new project's as `$NEW_DB_URL`.++## Migrate the database++1. Enable [Database Webhooks](https://app.supabase.com/project/_/database/hooks) in your new project if you enabled them in your old project.+2. In your new project, enable all extensions that were enabled in your old project.+3. Run the following command from your terminal:++```sh+set -euo pipefail++pg_dump \+ --clean \+ --if-exists \+ --quote-all-identifiers \+ --exclude-table-data 'storage.objects' \+ --exclude-schema 'extensions|graphql|graphql_public|net|pgbouncer|pgsodium|pgsodium_masks|realtime|supabase_functions|pg_toast|pg_catalog|information_schema' \+ --schema '*' \+ --dbname "$OLD_DB_URL" \+| sed 's/^DROP SCHEMA IF EXISTS "auth";$/-- DROP SCHEMA IF EXISTS "auth";/' \+| sed 's/^DROP SCHEMA IF EXISTS "storage";$/-- DROP SCHEMA IF EXISTS "storage";/' \+| sed 's/^CREATE SCHEMA "auth";$/-- CREATE SCHEMA "auth";/' \+| sed 's/^CREATE SCHEMA "storage";$/-- CREATE SCHEMA "storage";/' \+| sed 's/^ALTER DEFAULT PRIVILEGES FOR ROLE "supabase_admin"/-- ALTER DEFAULT PRIVILEGES FOR ROLE "supabase_admin"/' \+> dump.sql++psql \+ --single-transaction \+ --variable ON_ERROR_STOP=1 \+ --file dump.sql \+ --dbname "$NEW_DB_URL"+```++## Enable publication on tables++Replication for Realtime is disabled for all tables in your new project. On the [Replication](https://app.supabase.com/project/_/database/replication) page in the Dashboard, select your new project and enable replication for tables that were enabled in your old project.++## Migrate Storage objects++The new project has the old project's Storage buckets, but the Storage objects need to be migrated manually. Use this script to move storage objects from one project to another. If you have more than 10k objects, we can move the objects for you. Just contact us at [[email protected]](mailto:[email protected]).++```js+// npm install @supabase/supabase-js@1+const { createClient } = require('@supabase/supabase-js')++const OLD_PROJECT_URL = 'https://xxx.supabase.co'+const OLD_PROJECT_SERVICE_KEY = 'old-project-service-key-xxx'++const NEW_PROJECT_URL = 'https://yyy.supabase.co'+const NEW_PROJECT_SERVICE_KEY = 'new-project-service-key-yyy'++;(async () => {+ const oldSupabaseRestClient = createClient(+ OLD_PROJECT_URL,+ OLD_PROJECT_SERVICE_KEY,+ {+ schema: 'storage',+ }+ )+ const oldSupabaseClient = createClient(+ OLD_PROJECT_URL,+ OLD_PROJECT_SERVICE_KEY+ )+ const newSupabaseClient = createClient(+ NEW_PROJECT_URL,+ NEW_PROJECT_SERVICE_KEY+ )++ // make sure you update max_rows in postgrest settings if you have a lot of objects+ // or paginate here+ const { data: oldObjects, error } = await oldSupabaseRestClient+ .from('objects')+ .select()+ if (error) {+ console.log('error getting objects from old bucket')+ throw error+ }++ for (const objectData of oldObjects) {+ console.log(`moving ${objectData.id}`)+ try {+ const { data, error: downloadObjectError } =+ await oldSupabaseClient.storage+ .from(objectData.bucket_id)+ .download(objectData.name)+ if (downloadObjectError) {+ throw downloadObjectError+ }++ const { _, error: uploadObjectError } = await newSupabaseClient.storage+ .from(objectData.bucket_id)+ .upload(objectData.name, data, {+ upsert: true,+ contentType: objectData.metadata.mimetype,+ cacheControl: objectData.metadata.cacheControl,+ })+ if (uploadObjectError) {+ throw uploadObjectError+ }+ } catch (err) {+ console.log('error moving ', objectData)+ console.log(err)+ }+ }+})()+```diff --git a/apps/temp-docs/docs/guides/database/replication.mdx b/apps/temp-docs/docs/guides/database/replication.mdxindex 5fe1ac12440..e78ec795f81 100644--- a/apps/temp-docs/docs/guides/database/replication.mdx+++ b/apps/temp-docs/docs/guides/database/replication.mdx@@ -1,229 +1,98 @@---id: replication-title: "Replication"+title: 'Replication'slug: replication----# Replication+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'-Replication is technique for copying the data from one database to another. This is useful for:+Replication is a technique for copying the data from one database to another. Supabase uses replication functionality to provide a real-time API. Replication is useful for:-- Spreading out the "load". For example, if your database has a lot of reads, you might want to split it between two databases.+- Spreading out the "load." For example, if your database has a lot of reads, you might want to split it between two databases.- Reducing latency. For example, you may want one database in London to serve your European customers, and one in New York to serve the US.-- In Supabase's case, we use the built-in replication functionality to provide a real-time API.+Replication is done through _publications_, a method of choosing which changes to send to other systems (usually another Postgres database). Publications can be managed in the [Dashboard](https://app.supabase.com) or with SQL.-## Publications+## Manage publications in the Dashboard-Publications are a way of choosing which changes should be sent to other systems (usually another Postgres database).---### Managing Publications--Supabase provides an interface for managing your publications, or you can use SQL.--<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>-<TabPanel id="UI" label="UI">--```sh-1. Go to the "Database" section.-2. Click on "Replication" in the sidebar.-3. Control which database events are sent by toggling the Insert/Update/Delete toggles.-4. Control which tables broadcast changes by clicking into the "Source" and toggling the tables.-```+1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard.+2. Click on **Replication** in the sidebar.+3. Control which database events are sent by toggling **Insert**, **Update**, and **Delete**.+4. Control which tables broadcast changes by selecting **Source** and toggling each table.<video width="99%" muted playsInline controls="true">-<source src="/docs/videos/api/api-realtime.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-realtime.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-</TabPanel>-<TabPanel id="SQL" label="SQL">--```sql-alter publication supabase_realtime add table products;-```+## Create a publication-</TabPanel>-</Tabs>--### Create a Publication--This publication will contain all changes to all tables.---<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+This publication contains changes to all tables.```sql-create publication publication_name+create publication publication_namefor all tables;```--</TabPanel>--</Tabs>--### Create a Publication which listens to individual tables----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Create a publication to listen to individual tables```sql-create publication publication_name+create publication publication_namefor table table_one, table_two;```--</TabPanel>--</Tabs>--### Add tables to an existing publication----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Add tables to an existing publication```sql-alter publication publication_name+alter publication publication_nameadd table table_name;```--</TabPanel>--</Tabs>--### Listen to `insert`----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Listen to `insert````sql-create publication publication_name+create publication publication_namefor all tableswith (publish = 'insert');```--</TabPanel>--</Tabs>--### Listen to `update`----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Listen to `update````sql-create publication publication_name+create publication publication_namefor all tableswith (publish = 'update');```--</TabPanel>--</Tabs>--### Listen to `delete`----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Listen to `delete````sql-create publication publication_name+create publication publication_namefor all tableswith (publish = 'delete');```--</TabPanel>--</Tabs>--### Remove a Publication----<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+## Remove a publication```sqldrop publication if exists publication_name;```+## Recreate a publication-</TabPanel>--</Tabs>--### Recreate a Publication--If you are planning to re-create a publication, it's best to do it in a transaction to ensure the operation succeeds.---<Tabs- defaultActiveId="sql"- groupId="reference/postgres"- values={[{ label: 'SQL', value: 'sql' }]}>--<TabPanel id="sql" label="SQL">+If you're recreating a publication, it's best to do it in a transaction to ensure the operation succeeds.```sql-begin;+begin;-- remove the realtime publication- drop publication if exists publication_name;+ drop publication if exists publication_name;-- re-create the publication but don't enable it for any tables- create publication publication_name;+ create publication publication_name;commit;```---</TabPanel>--</Tabs>diff --git a/apps/temp-docs/docs/guides/database/sql-to-api.mdx b/apps/temp-docs/docs/guides/database/sql-to-api.mdxindex 715d9caabc5..298ece3417d 100644--- a/apps/temp-docs/docs/guides/database/sql-to-api.mdx+++ b/apps/temp-docs/docs/guides/database/sql-to-api.mdx@@ -1,11 +1,11 @@---id: sql-to-api-title: 'Converting SQL to Javascript API'-description: Implementing common SQL patterns in the Javascript API+title: 'Converting SQL to JavaScript API'+description: Implementing common SQL patterns in the JavaScript API---import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'<!-- @TODO: this one is a very daunting read on first attempt. Need to check what is the purpose of it? -->@@ -78,6 +78,6 @@ const { data, error } = await supabase- [Supabase Account - Free Tier OK](https://supabase.com)- [Postgrest Operators](https://postgrest.org/en/stable/api.html#operators)-- [Supabase Javascript API: select](/docs/reference/javascript/select)-- [Supabase Javascript API: modifiers](/docs/reference/javascript/using-modifiers)-- [Supabase Javascript API: filters](/docs/reference/javascript/using-filters)+- [Supabase API: JavaScript select](/docs/reference/javascript/select)+- [Supabase API: JavaScript modifiers](/docs/reference/javascript/using-modifiers)+- [Supabase API: JavaScript filters](/docs/reference/javascript/using-filters)diff --git a/apps/temp-docs/docs/guides/database/tables.mdx b/apps/temp-docs/docs/guides/database/tables.mdxindex c7b79387b11..1f0e0857329 100644--- a/apps/temp-docs/docs/guides/database/tables.mdx+++ b/apps/temp-docs/docs/guides/database/tables.mdx@@ -1,131 +1,518 @@---id: tables-title: Tables+title: Tables and Datadescription: Creating and using Postgres tables.----import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+Tables are where you store your data.-In Postgres, data is stored in "tables".-Tables are similar to excel spreadsheets. They contain columns & rows of data. There are a few key differences from a spreadsheet however:--- Every column is a strict type of data. When you set up a column, you must define the "data type".-- Tables can be "joined" together. For example you can have a `users` table, which is joined to a `teams` table (because users belong to teams).-+Tables are similar to excel spreadsheets. They contain columns and rows.For example, this table has 3 "columns" (`id`, `name`, `description`) and 4 "rows" of data:-| `id` | `name` | `description` |-| ---- | ---- | ----------- |-| 1 | Toy Story | When a new toy called "Forky" joins Woody and the gang, a road trip alongside old and new friends reveals how big the world can be for a toy. |-| 2 | Monsters, Inc. | In order to power the city, monsters have to scare children so that they scream. However, the children are toxic to monsters. |-| 3 | Finding Nemo | After his son is captured in the Great Barrier Reef and taken to Sydney, a timid clownfish sets out on a journey to bring him home. |-| 4 | WALL-E | In the distant future, a small waste-collecting robot inadvertently embarks on a space journey that will ultimately decide the fate of mankind. |+| `id` | `name` | `description` |+| ---- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 1 | The Phantom Menace | Two Jedi escape a hostile blockade to find allies and come across a young boy who may bring balance to the Force. |+| 2 | Attack of the Clones | Ten years after the invasion of Naboo, the Galactic Republic is facing a Separatist movement. |+| 3 | Revenge of the Sith | As Obi-Wan pursues a new threat, Anakin acts as a double agent between the Jedi Council and Palpatine and is lured into a sinister plan to rule the galaxy. |+| 4 | Star Wars | Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station. |+There are a few important differences from a spreadsheet, but it's a good starting point if you're new to Relational databases.## Creating Tables-Supabase provides several options for creating tables. You can use the Table Editor or create them directly using SQL.-We provide a SQL editor within the Dashboard, or you can [connect](/docs/guides/database/connecting/connecting-to-postgres) to your database-and run the SQL queries yourself.+When creating a table, it's best practice to add columns at the same time.+++You must define the "data type" of each column when it is created. You can add and remove columns at any time after creating a table.++Supabase provides several options for creating tables. You can use the Dashboard or create them directly using SQL.+We provide a SQL editor within the Dashboard, or you can [connect](../../guides/database/connecting-to-postgres) to your database+and run the SQL queries yourself.<Tabs-defaultActiveId="UI"-values={[- {label: 'UI', value: 'UI'},- {label: 'SQL', value: 'SQL'},-]}>-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Table editor" section.-2. Click "New Table".-3. Enter the table name "todos".-4. Click "Save".-5. Click "New Column".-6. Enter the column name "task" and make the type "text".-7. Click "Save".-```+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard"><video width="99%" muted playsInline controls="true">-<source src="/docs/videos/api/api-create-table-sm.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-create-table-sm.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard.+2. Click **New Table** and create a table with the name `todos`.+3. Click **Save**.+4. Click **New Column** and create a column with the name `task` and type `text`.+5. Click **Save**.-```sql--- Create a table called "todos" with a column to store tasks.+</TabItem>+<TabItem value="sql">-create table todos (+```sql+create table movies (id bigint generated by default as identity primary key,- task text check (char_length(task) > 3)+ name text,+ description text);```-</TabsPanel>+</TabItem></Tabs>+:::note+When naming tables, use lowercase and underscores instead of spaces (e.g., `table_name`, not `Table Name`).+:::-### Tips--- It is best practice to use lowercase and underscores when naming tables. For example: `table_name`, not `Table Name`.-- Tables belong to `schemas`. If you don't explicitly pass the schema, Postgres will assume that you want to create the table in the `public` schema.+## Columns+You must define the "data type" when you create a column.### Data types-Every column is a predefined type. PostgreSQL provides many [default types](https://www.postgresql.org/docs/current/datatype.html), and you can even design your own (or use extensions) if the default types don't fit your needs. Here's a list of all of the default data types provided by Postgres:+Every column is a predefined type. PostgreSQL provides many [default types](https://www.postgresql.org/docs/current/datatype.html), and you can even design your own (or use extensions)+if the default types don't fit your needs.<details><summary>Show/Hide default data types</summary>-| `Name` | `Aliases` | `Description` |-| ------------------------------------------- | -------------------- | ----------------------------------------------------------------- |-| bigint | int8 | Signed eight-byte integer. For numbers ranging from -9223372036854775808 to +9223372036854775807. |-| bigserial | serial8 | Autoincrementing eight-byte integer. For numbers ranging from 1 to 9223372036854775807. |-| bit | | Fixed-length bit string. |-| bit varying | varbit | Variable-length bit string. |-| boolean | bool | Logical Boolean (true/false). |-| box | | Rectangular box on a plane. |-| bytea | | Binary data (“byte array”). |-| character | char | Fixed-length character string. |-| character varying | varchar | Variable-length character string. |-| cidr | | IPv4 or IPv6 network address. |-| circle | | Circle on a plane. |-| date | | Calendar date (year, month, day). |-| double precision | float8 | Double precision floating-point number (8 bytes). 15 decimal digits of precision. |-| inet | | IPv4 or IPv6 host address. |-| integer | int, int4 | Signed four-byte integer. -2147483648 to +2147483647. |-| interval \[ fields \] | | Time span. |-| json | | Textual JSON data. |-| jsonb | | Binary JSON data, decomposed. If you are doing a lot of JSON manipulation in Postgres you should consider using JSONB for efficiency. Otherwise, if you are just doing typical data storing and fetching, JSON should be fine. |-| line | | Infinite line on a plane. |-| lseg | | Line segment on a plane. |-| macaddr | | MAC (Media Access Control) address. |-| macaddr8 | | MAC (Media Access Control) address (EUI-64 format). |-| money | | currency. |-| numeric | decimal | Exact numeric of selectable precision. Up to 131072 digits before the decimal point; up to 16383 digits after. For storing number that require very high precision. Use the numeric type when you need more precision than float4 or float8 offer. |-| path | | Geometric path on a plane. |-| pg\_lsn | | PostgreSQL Log Sequence Number. |-| pg\_snapshot | | User-level transaction ID snapshot. |-| point | | Geometric point on a plane. |-| polygon | | Closed geometric path on a plane. |-| real | float4 | Single precision floating-point number (4 bytes). 6 decimal digits precision. |-| smallint | int2 | Signed two-byte integer. For numbers ranging from -32768 to +32767. |-| smallserial | serial2 | Autoincrementing two-byte integer. For numbers ranging from 1 to 32767. |-| serial | serial4 | Autoincrementing four-byte integer. For numbers ranging from 1 to 2147483647. |-| text | | Variable-length character string. This is the general purpose data type for textual content. |-| time \[ without time zone \] | | Time of day (no time zone). |-| time with time zone | timetz | Time of day, including time zone. |-| timestamp \[ without time zone \] | | Date and time (no time zone). |-| timestamp with time zone | timestamptz | Date and time, including time zone. |-| tsquery | | Text search query. |-| tsvector | | Text search document. |-| txid\_snapshot | | User-level transaction ID snapshot (deprecated; see pg\_snapshot). |-| uuid | | Universally unique identifier. |-| xml | | XML data. |+| `Name` | `Aliases` | `Description` |+| --------------------------------- | ----------- | ---------------------------------------------------------------- |+| bigint | int8 | signed eight-byte integer |+| bigserial | serial8 | autoincrementing eight-byte integer |+| bit | | fixed-length bit string |+| bit varying | varbit | variable-length bit string |+| boolean | bool | logical Boolean (true/false) |+| box | | rectangular box on a plane |+| bytea | | binary data (“byte array”) |+| character | char | fixed-length character string |+| character varying | varchar | variable-length character string |+| cidr | | IPv4 or IPv6 network address |+| circle | | circle on a plane |+| date | | calendar date (year, month, day) |+| double precision | float8 | double precision floating-point number (8 bytes) |+| inet | | IPv4 or IPv6 host address |+| integer | int, int4 | signed four-byte integer |+| interval \[ fields \] | | time span |+| json | | textual JSON data |+| jsonb | | binary JSON data, decomposed |+| line | | infinite line on a plane |+| lseg | | line segment on a plane |+| macaddr | | MAC (Media Access Control) address |+| macaddr8 | | MAC (Media Access Control) address (EUI-64 format) |+| money | | currency amount |+| numeric | decimal | exact numeric of selectable precision |+| path | | geometric path on a plane |+| pg_lsn | | PostgreSQL Log Sequence Number |+| pg_snapshot | | user-level transaction ID snapshot |+| point | | geometric point on a plane |+| polygon | | closed geometric path on a plane |+| real | float4 | single precision floating-point number (4 bytes) |+| smallint | int2 | signed two-byte integer |+| smallserial | serial2 | autoincrementing two-byte integer |+| serial | serial4 | autoincrementing four-byte integer |+| text | | variable-length character string |+| time \[ without time zone \] | | time of day (no time zone) |+| time with time zone | timetz | time of day, including time zone |+| timestamp \[ without time zone \] | | date and time (no time zone) |+| timestamp with time zone | timestamptz | date and time, including time zone |+| tsquery | | text search query |+| tsvector | | text search document |+| txid_snapshot | | user-level transaction ID snapshot (deprecated; see pg_snapshot) |+| uuid | | universally unique identifier |+| xml | | XML data |+</details>+<br />++You can "cast" columns from one type to another, however there can be some incompatibilities between types.+For example, if you cast a `timestamp` to a `date`, you will lose all the time information that was previously saved.++### Primary Keys++A table can have a "primary key" - a unique identifier for every row of data. A few tips for Primary Keys:++- It's recommended to create a Primary Key for every table in your database.+- You can use any column as a primary key, as long as it is unique for every row.+- It's common to use a `uuid` type or a numbered `identity` column as your primary key.++```sql+create table movies (+ id bigint generated always as identity primary key+);+```++In the example above, we have:++1. created a column called `id`+1. assigned the data type `bigint`+1. instructed the database that this should be `generated always as identity`, which means that Postgres will automatically assign a unique number to this column.+1. Becuase it's unique, we can also use it as our `primary key`.++We could also use `generated by default as identity`, which would allow us to insert our own unique values.++```sql+create table movies (+ id bigint generated by default as identity primary key+);+```++## Loading data++There are several ways to load data in Supabase. You can load data directly into the database or using the [APIs](../../guides/api).+Use the "Bulk Loading" instructions if you are loading large data sets.++### Basic data loading++<Tabs+ defaultValue="sql"+ values={[+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Dart', value: 'dart'},+ ]}>++<TabItem value="sql">++```sql+insert into movies+ (name, description)+values+ ('The Empire Strikes Back', 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'),+ ('Return of the Jedi', 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.');+```++</TabItem>++<TabItem value="javascript">++```sql+const { data, error } = await supabase+ .from('movies')+ .insert([{+ name: 'The Empire Strikes Back',+ description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'+ }, {+ name: 'Return of the Jedi',+ description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.'+ }])+```++</TabItem>++<TabItem value="dart">++```sql+final res = await supabase+ .from('movies')+ .insert([{+ name: 'The Empire Strikes Back',+ description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'+ }, {+ name: 'Return of the Jedi',+ description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.'+ }]).execute();+```++</TabItem>+</Tabs>++### Bulk data loading++When inserting large data sets it's best to use PostgreSQL's [COPY](https://www.postgresql.org/docs/current/sql-copy.html) command.+This loads data directly from a file into a table. There are several file formats available for copying data: text, csv, binary, JSON, etc.++For example, if you wanted to load a CSV file into your movies table:++```csv title="./movies.csv"+"The Empire Strikes Back", "After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda."+"Return of the Jedi", "After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star."+```++You would [connect](../../guides/database/connecting-to-postgres#direct-connections) to your database directly and load the file with the COPY command:++```bash+psql -h DATABASE_URL -p 5432 postgres -U postgres \+ -c "COPY movies FROM './movies.csv';"+```++## Joining tables with Foreign Keys++Tables can be "joined" together using Foreign Keys.++++This is where the "Relational" naming comes from, as data typically forms some sort of relationship.++In our "movies" example above, we might want to add a "category" for each movie (for example, "Action", or "Documentary").+Let's create a new table called `categories` and "link" our `movies` table.++```sql+create table categories (+ id bigint generated always as identity primary key,+ name text -- category name+);++alter table movies+ add column category_id bigint references categories;+```++You can also create "many-to-many" relationships by creating a "join" table.+For example if you had the following situations:++- You have a list of `movies`.+- A movie can have several `actors`.+- An `actor` can perfom in several movies.++<Tabs+ groupId="dashboard-or-sql"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>++<TabItem value="dashboard">++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/TKwF3IGij5c"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++</TabItem>++<TabItem value="sql">++```sql+create table movies (+ id bigint generated by default as identity primary key,+ name text,+ description text+);++create table actors (+ id bigint generated by default as identity primary key,+ name text+);++create table performances (+ id bigint generated by default as identity primary key,+ movie_id bigint not null references movies,+ actor_id bigint not null references actors+);+```++</TabItem>+</Tabs>++## Schemas++Tables belong to `schemas`. Schemas are a way of organizing your tables, often for security reasons.++++If you don't explicitly pass a schema when creating a table, Postgres will assume that you want to create the table in the `public` schema.++We can create schemas for organizing tables. For example, we might want a private schema which is hidden from our API:++```sql+create schema private;+```++Now we can create tables inside the `private` schema:++```sql+create table salaries (+ id bigint generated by default as identity primary key,+ salary bigint not null,+ actor_id bigint not null references public.actors+);+```++## Views++A View is a convenient shortcut to a query. Creating a view does not involve new tables or data. When run, an underlying query is executed, returning its results to the user.++:::caution++By default, PostgreSQL views bypass Row Level Security unless you change their owner (see https://github.com/supabase/supabase/discussions/901). PostgreSQL v15 (coming soon) will have a more intuitive control for this through [security invoker views](https://www.depesz.com/2022/03/22/waiting-for-postgresql-15-add-support-for-security-invoker-views/) and the previous step won't be needed.++:::++Say we have the following tables from a database of a university:++**`students`**++| id | name | type |+| --- | ---------------- | ------------- |+| 1 | Princess Leia | undergraduate |+| 2 | Yoda | graduate |+| 3 | Anakin Skywalker | graduate |++**`courses`**++| id | title | code |+| --- | ------------------------ | ------- |+| 1 | Introduction to Postgres | PG101 |+| 2 | Authentication Theories | AUTH205 |+| 3 | Fundamentals of Supabase | SUP412 |++**`grades`**++| id | student_id | course_id | result |+| --- | ---------- | --------- | ------ |+| 1 | 1 | 1 | B+ |+| 2 | 1 | 3 | A+ |+| 3 | 2 | 2 | A |+| 4 | 3 | 1 | A- |+| 5 | 3 | 2 | A |+| 6 | 3 | 3 | B- |++Creating a view consisting of all the three tables will look like this:++```sql+create view transcripts as+ select+ students.name,+ students.type,+ courses.title,+ courses.code,+ grades.result+ from grades+ left join students on grades.student_id = students.id+ left join courses on grades.course_id = courses.id;++alter view transcripts owner to authenticated;+```++Once done, we can now access the underlying query with:++```sql+select * from transcripts;+```++### When to use views++Views provide the several benefits:++- Simplicity+- Consistency+- Logical Organization+- Security++#### Simplicity++As a query becomes complex it becomes a hassle to call it. Especially when we run it at regularly. In the example above, instead of repeatedly running:++```sql+select+ students.name,+ students.type,+ courses.title,+ courses.code,+ grades.result+from grades+left join students on grades.student_id = students.id+left join courses on grades.course_id = courses.id;+```++We can run this instead:++```sql+select * from transcripts;+```++Additionally, a view behaves like a typical table. We can safely use it in table `JOIN`s or even create new views using existing views.++#### Consistency++Views ensure that the likelihood of mistakes decreases when repeatedly executing a query. In our example above, we may decide that we want to exclude the course _Introduction to Postgres_. The query would become:++```sql+select+ students.name,+ students.type,+ courses.title,+ courses.code,+ grades.result+from grades+ left join students on grades.student_id = students.id+ left join courses on grades.course_id = courses.id+where courses.code != 'PG101';+```++Without a view, we would need to go into every dependent query to add the new rule. This would increase in the likelihood of errors and inconsistencies, as well as introducing a lot of effort for a developer. With views, we can alter just the underlying query in the view **transcripts**. The change will be applied to all applications using this view.++#### Logical Organization++With views, we can give our query a name. This is extremely useful for teams working with the same database. Instead of guessing what a query is supposed to do, a well-named view can easily explain it. For example, by looking at the name of the view **transcripts**, we can infer that the underlying query might involve the **students**, **courses**, and **grades** tables.++#### Security++Views can restrict the amount and type of data presented to a user. Instead of allowing a user direct access to a set of tables, we provide them a view instead. We can prevent them from reading sensitive columns by excluding them from the underlying query.++### Materialized Views++A [materialized view](https://www.postgresql.org/docs/12/rules-materializedviews.html) is a form of view but it also stores the results to disk. In subsequent reads of a materialized view, the time taken to return its results would be much faster than a conventional view. This is because the data is readily available for a materialized view while the conventional view executes the underlying query each time it is called.++Using our example above, a materialized view can be created like this:++```sql+create materialized view transcripts as+ select+ students.name,+ students.type,+ courses.title,+ courses.code,+ grades.result+ from grades+ left join students on grades.student_id = students.id+ left join courses on grades.course_id = courses.id;+```++Reading from the materialized view is the same as a conventional view:++```sql+select * from transcripts;+```++### Refreshing materialized views++Unfortunately, there is a trade-off - data in materialized views are not always up to date. We need to refresh it regularly to prevent the data from becoming too stale. To do so:++```sql+refresh materialized view transcripts;+```++It's up to you how regularly refresh your materialized views, and it's probably different for each view depending on its use-case.++### Materialized views vs Conventional views++Materialized views are useful when execution times for queries or views are too slow. These could likely occur in views or queries involving multiple tables and billions of rows. When using such a view, however, there should be tolerance towards data being outdated. Some use-cases for materialized views are internal dashboards and analytics.++Creating a materialized view is not a solution to inefficient queries. You should always seek to optimize a slow running query even if you are implementing a materialized view.++## Resources++- [Official Docs: Create table](https://www.postgresql.org/docs/current/sql-createtable.html)+- [Official Docs: Create view](https://www.postgresql.org/docs/12/sql-createview.html)+- [PostgreSQL Tutorial: Create tables](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-create-table/)+- [PostgreSQL Tutorial: Add column](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-add-column/)+- [PostgreSQL Tutorial: Views](https://www.postgresqltutorial.com/postgresql-views/)diff --git a/apps/temp-docs/docs/guides/database/timeouts.mdx b/apps/temp-docs/docs/guides/database/timeouts.mdxindex 81979b95fba..2436c5dc0db 100644--- a/apps/temp-docs/docs/guides/database/timeouts.mdx+++ b/apps/temp-docs/docs/guides/database/timeouts.mdx@@ -4,13 +4,11 @@ title: Timeoutsdescription: Timeouts and optimization----# Timeouts-By default, Supabase limits the maximum statement execution time to _3 seconds_ for users accessing the API using the anon key, and _8 seconds_ for authenticated users. Additionally, all users are subject to a global limit of _2 minutes_. This serves as a backstop against resource exhaustion due to either poorly written queries, or abusive usage.### Changing the default timeout-The timeout values were picked as a reasonable default for the majority of use-cases, but can be modified using the [`alter role`](https://www.postgresql.org/docs/13/sql-alterrole.html) statement:+The timeout values were picked as a reasonable default for the majority of use-cases, but can be modified using the [`alter role`](https://www.postgresql.org/docs/current/sql-alterrole.html) statement:```sqlalter role authenticated set statement_timeout = '15s';@@ -24,6 +22,6 @@ set statement_timeout to 60000; -- 1 minute in milliseconds### Statement Optimization-All Supabase projects come with the [`pg_stat_statements`](https://www.postgresql.org/docs/13/pgstatstatements.html) extension installed, which tracks planning and execution statistics for all statements executed against it. These statistics can be used in order to diagnose the performance of your project.+All Supabase projects come with the [`pg_stat_statements`](https://www.postgresql.org/docs/current/pgstatstatements.html) extension installed, which tracks planning and execution statistics for all statements executed against it. These statistics can be used in order to diagnose the performance of your project.-This data can further be used in conjunction with the [`explain`](https://www.postgresql.org/docs/13/using-explain.html) functionality of Postgres to optimize your usage.+This data can further be used in conjunction with the [`explain`](https://www.postgresql.org/docs/current/using-explain.html) functionality of Postgres to optimize your usage.diff --git a/apps/temp-docs/docs/guides/examples.mdx b/apps/temp-docs/docs/guides/examples.mdxindex dd681a7d936..30fc3eff526 100644--- a/apps/temp-docs/docs/guides/examples.mdx+++ b/apps/temp-docs/docs/guides/examples.mdx@@ -1,46 +1,98 @@----title: 'Examples and Resources'-description: 'Supabase examples and resources'+id: examples+title: Examples and Resources+description: 'Examples you can use to get started with Supabase'----# Examples and Resources+<!-- This page is outdated and should not be added to the sidebar until it has been reworked -->We have a [set of examples](https://github.com/supabase/supabase/tree/master/examples) in our [main repository](https://github.com/supabase/supabase) to help you get started.-## Todo List+## Featured++### Supabase Crash Course++By [Traversy Media](https://www.youtube.com/watch?v=7uKQBl9uZ00).++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/7uKQBl9uZ00"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++### Build an App With Supabase and NextJS++By [@jlengstorf](https://twitter.com/jlengstorf) and [@jonmeyers_io](https://twitter.com/jonmeyers_io).++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/8vqY1KT4TLU"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++### Is Supabase Legit++By [Fireship](https://www.youtube.com/watch?v=WiwfiVdfRIc).++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/WiwfiVdfRIc"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Official Examples++### Todo ListBuild a basic Todo List with Supabase and your favorite frontend framework:-- [Expo Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/expo-todo-list)-- [Next.js Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/nextjs-todo-list)-- [React Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/react-todo-list)+- [Expo Todo List.](https://github.com/supabase/examples/tree/main/supabase-js-v1/todo-list/expo-todo-list)+- [Next.js Todo List.](https://github.com/supabase/examples/tree/main/supabase-js-v1/todo-list/nextjs-todo-list)+- [React Todo List.](https://github.com/supabase/examples/tree/main/supabase-js-v1/todo-list/react-todo-list)- [Svelte Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/sveltejs-todo-list)-- [Vue 3 Todo List (Typescript).](https://github.com/supabase/supabase/tree/master/examples/todo-list/vue3-ts-todo-list)-- [Angular Todo List.](https://github.com/supabase/supabase/tree/master/examples/angular-todo-list)+- [Vue 3 Todo List (Typescript).](https://github.com/supabase/examples/tree/main/supabase-js-v1/todo-list/vue3-ts-todo-list)+- [Angular Todo List.](https://github.com/supabase/examples/tree/main/supabase-js-v1/todo-list/angular-todo-list)+- [Nuxt 3 Todo List.](https://github.com/nuxt-community/supabase-module/tree/main/demo)-## Auth examples#+### Auth examples-- [Supabase Auth with vanilla Javascript..](https://github.com/supabase/supabase/tree/master/examples/auth/javascript-auth) Use Supabase without any frontend frameworks.-- [Supabase Auth with Next.js SSR.](https://github.com/supabase/supabase/tree/master/examples/nextjs-with-supabase-auth) Uses cookies to persist auth between the server and the client.-- [Supabase Auth with RedwoodJS.](https://redwood-playground-auth.netlify.app/supabase) Try out Supabase authentication in the [RedwoodJS](https://redwoodjs.com/) Authentication Playground complete with OAuth support and code samples.+- [Supabase Auth with vanilla JavaScript.](https://github.com/supabase/examples/tree/main/supabase-js-v1/auth/javascript-auth). Use Supabase without any frontend frameworks.+- [Supabase Auth with Next.js](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management).+- [Supabase Auth with RedwoodJS.](https://redwood-playground-auth.netlify.app/supabase) Try out Supabase authentication in the [RedwoodJS](https://redwoodjs.com) Authentication Playground complete with OAuth support and code samples.-## Collaborative+### Collaborative-- [Next.js Slack Clone.](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)+- [Next.js Slack Clone.](https://github.com/supabase/examples/tree/main/supabase-js-v1/slack-clone/nextjs-slack-clone)## Community+### Courses++- Build a FullStack App with Next.js, Supabase & Prisma by [@gdangel0](https://twitter.com/gdangel0): [Free course](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-322389284337222224)+### Libraries-- Dart (in development): [GitHub](https://github.com/supabase/supabase-dart )++- D (in development): [GitHub](https://github.com/csharpdf/dupabase)+- Flutter (in development): [GitHub](https://github.com/supabase/supabase-flutter)- Python (in development): [GitHub](https://github.com/supabase/supabase-py)- C# (in development): [GitHub](https://github.com/supabase/supabase-csharp)-- Kotlin (in development): [GitHub](https://github.com/supabase/supabase-kt)-- useSupabase: Supabase React Hooks. [GitHub](https://github.com/gbibeaul/use-supabase)-- vue-supabase: Supabase Vue wrapper. [GitHub](https://github.com/supabase/vue-supabase)-- vue-3-supabase: Supabase Vue 3 wrapper. [GitHub](https://github.com/DidoMarchet/vue-3-supabase)-- nuxt-supabase: Supabase Nuxt wrapper. [GitHub](https://github.com/supabase/nuxt-supabase)-- react-supabase: Supabase React Hooks. [Docs](https://react-supabase.vercel.app/) [GitHub](https://github.com/tmm/react-supabase)-- @triniwiz/nativescript-supabase: Supabase NativeScript. [GitHub](https://github.com/triniwiz/nativescript-plugins/tree/master/packages/nativescript-supabase)+- Kotlin (in development): [GitHub](https://github.com/supabase-community/postgrest-kt)+- `useSupabase`: Supabase React Hooks. [GitHub](https://github.com/gbibeaul/use-supabase)+- `vue-supabase`: Supabase Vue wrapper. [GitHub](https://github.com/supabase/vue-supabase)+- `vue-3-supabase`: Supabase Vue 3 wrapper. [GitHub](https://github.com/DidoMarchet/vue-3-supabase)+- `nuxt-supabase`: Supabase Nuxt wrapper. [GitHub](https://github.com/supabase/nuxt-supabase)+- `@nuxtjs/supabase`: Supabase Nuxt 3 module. [GitHub](https://github.com/nuxt-community/supabase-module)+- `react-supabase`: Supabase React Hooks. [Docs](https://react-supabase.vercel.app) [GitHub](https://github.com/tmm/react-supabase)+- ` @triniwiz/nativescript-supabase`: Supabase NativeScript. [GitHub](https://github.com/triniwiz/nativescript-plugins/tree/master/packages/nativescript-supabase)### Guides@@ -50,41 +102,54 @@ Build a basic Todo List with Supabase and your favorite frontend framework:- Setting up Umami Analytics with Supabase. [Blog](https://dev.to/jakobbouchard/setting-up-umami-with-vercel-and-supabase-3a73)- Creating New Supabase Users In NextJS. [Blog](https://www.aboutmonica.com/blog/creating-new-supabase-users-in-next-js)- Creating Protected Routes In NextJS With Supabase. [Blog](https://www.aboutmonica.com/blog/creating-protected-routes-in-next-js-with-supabase)-- Migrate from Google Cloud Storage (GCS) to Supabase Storage Gist+- Migrate from Google Cloud Storage (GCS) to Supabase Storage [Gist](https://gist.github.com/danalloway/86f79efd5ca336ff7364554ac3104014)- Subscriptions with Supabase and Stripe Billing [Blog](https://www.sandromaglione.com/2021/04/29/supabase-auth-create-stripe-customer-subscription-supabase-stripe-billing-part-1/)- Flutter Supabase Authentication [Blog](https://www.sandromaglione.com/2021/04/24/flutter-supabase-authentication/)-- Supabase in 6 minutes []Video(https://www.youtube.com/watch?v=c8DNV9yl0mg)-- Let's build SupaAuth - Build an Authentication System using Supabase, Next.js and Typescript 6-part [Blog Series](https://aalam.in/blog/supabase-auth-intro-setup-next)+- Supabase in 6 minutes [Video](https://www.youtube.com/watch?v=c8DNV9yl0mg)+- Let's build SupaAuth - Build an Authentication System using Supabase, Next.js and Typescript [6-part Blog Series](https://aalam.in/blog/supabase-auth-intro-setup-next)- In-depth self-hosting guide using Nginx [Blog](https://dev.to/chronsyn/self-hosting-with-supabase-1aii)+- Build an Email and Social Auth for Next JS with Supabase, Tailwind CSS 3.0 and TypeScript [Blog](https://creativedesignsguru.com/next-js-supabase-auth/)+- Link Shortener using Supabase and Ory [3-part Blog Series](https://www.ory.sh/tutorial-url-shortener-supabase-ory-integration-backend/)### Example apps--Supabase + Stripe + Next.js. [GitHub](https://github.com/vercel/nextjs-subscription-payments)-Supabase + Svelte Trello clone. [GitHub](https://github.com/joshnuss/supabase-kanban)-Supabase + Expo Starter. [GitHub](https://github.com/codingki/react-native-expo-template/tree/master/template-typescript-bottom-tabs-supabase-auth-flow)-Supabase + Nest.js. [GitHub](https://github.com/hiro1107/nestjs-supabase-auth)-Supabase + Cloudflare Workers. [GitHub](https://github.com/supabase/supabase/tree/master/examples/with-cloudflare-workers)-Supabase + Cloudflare Workers + Webpack. [GitHub](https://github.com/signalnerve/supabase-workers-proxy)-Realtime chat app with Supabase + React. [GitHub](https://github.com/shwosner/realtime-chat-supabase-react)-Repository.surf: GitHub insights dashboard. [GitHub](https://github.com/supabase/repository.surf)-Supabase + React + Mobx-State-Tree Instagram Clone. [GitHub](https://github.com/NiketanG/instaclone)-KeepLink: Simple bookmark service with tags and archive. [GitHub](https://github.com/fengkx/keeplink)-Supabase + Next.js (Next.js Starter Kit) [Github](https://github.com/one-aalam/next-starter-kit/tree/auth-supabase)-Supabase + Svelte (Svelte Starter Kit) [Github](https://github.com/one-aalam/svelte-starter-kit)-Supabase + SolidJS (SolidJS Starter Kit) [Github](https://github.com/one-aalam/solid-starter-kit)-Supabase + Nuxt3 (Nuxt Starter Kit) [Github](https://github.com/one-aalam/nuxt-starter-kit)-Supabase + Remix (Remix Starter Kit) [Github](https://github.com/one-aalam/remix-starter-kit)-Supabase + Angular (Angular Starter Kit) [Github](https://github.com/one-aalam/ng-starter-kit)+- Supabase + Stripe + Next.js. [GitHub](https://github.com/vercel/nextjs-subscription-payments)+- Supabase + Svelte Trello clone. [GitHub](https://github.com/joshnuss/supabase-kanban)+- Supabase + Expo Starter. [GitHub](https://github.com/codingki/react-native-expo-template/tree/master/template-typescript-bottom-tabs-supabase-auth-flow)+- Supabase + Nest.js. [GitHub](https://github.com/hiro1107/nestjs-supabase-auth)+- Supabase + Cloudflare Workers. [GitHub](https://github.com/supabase/examples/tree/main/supabase-js-v1/with-cloudflare-workers)+- Supabase + Cloudflare Workers + Webpack. [GitHub](https://github.com/signalnerve/supabase-workers-proxy)+- Realtime chat app with Supabase + React. [GitHub](https://github.com/shwosner/realtime-chat-supabase-react)+- Repository.surf: GitHub insights dashboard. [GitHub](https://github.com/supabase/repository.surf)+- Supabase + React Native Instagram Clone. [GitHub](https://github.com/NiketanG/instaclone)+- KeepLink: Simple bookmark service with tags and archive. [GitHub](https://github.com/fengkx/keeplink)+- Supabase + Next.js (Next.js Starter Kit) [GitHub](https://github.com/one-aalam/next-starter-kit/tree/auth-supabase)+- Supabase + Svelte (Svelte Starter Kit) [GitHub](https://github.com/one-aalam/svelte-starter-kit)+- Supabase + SolidJS (SolidJS Starter Kit) [GitHub](https://github.com/one-aalam/solid-starter-kit)+- Supabase + Nuxt3 (Nuxt Starter Kit) [GitHub](https://github.com/one-aalam/nuxt-starter-kit)+- Supabase + Remix (Remix Starter Kit) [GitHub](https://github.com/one-aalam/remix-starter-kit)+- Supabase + Angular (Angular Starter Kit) [GitHub](https://github.com/one-aalam/ng-starter-kit)+- Supabase + Nuxt3 + nuxtjs/supabase [Github](https://github.com/nuxt-community/supabase-module/tree/main/demo)+- Supabase + Ory Kratos & Ory Oathkeeper [Github](https://github.com/ory/examples/tree/master/kratos-keto-oathkeeper-supabase)+- Supabase + Ory Cloud [Github](https://github.com/ory/examples/tree/master/supabase-ory-cloud)+- Supabase Auth with React Native + Next.js (Monorepo) [Github](https://github.com/mateoguzmana/react-native-next-supabase-auth-monorepo)### Blog Posts--Realtime Subscriptions using Vue + Supabase. [Blog](https://dev.to/ftonato/realtime-subscriptions-using-vue-supabase-1e11)-Creating a microblog using Vue + Supabase. [Blog](https://dev.to/ftonato/creating-a-microblog-using-vue-supabase-31p)-Track Real-time Page Views. [Blog](https://codebycorey.com/blog/page-views-nextjs-supabase)-Supabase as a Sentry alternative. [Blog](http://kopi.cloud/blog/2021/sentry-supabase/)-Using Supabase with Chartbrew. [Blog](https://chartbrew.com/blog/how-to-visualize-your-supabase-data-with-chartbrew/)-Authentication with Supabase and React. [Blog](https://hyperfoo.io/posts/supabase-authentication-react)-Supabase Schema Visualizer. [Blog](https://dev.to/zernonia/supabase-schema-visualizer-no-installation-login-49kg)-Create a real-time UI using Next.js + Supabase. [Blog](https://pablopunk.com/posts/how-to-create-a-real-time-ui-with-nextjs-and-supabase)+- Realtime Subscriptions using Vue + Supabase. [Blog](https://dev.to/ftonato/realtime-subscriptions-using-vue-supabase-1e11)+- Creating a microblog using Vue + Supabase. [Blog](https://dev.to/ftonato/creating-a-microblog-using-vue-supabase-31p)+- Track Real-time Page Views. [Blog](https://codebycorey.com/blog/page-views-nextjs-supabase)+- Supabase as a Sentry alternative. [Blog](http://kopi.cloud/blog/2021/sentry-supabase/)+- Using Supabase with Chartbrew. [Blog](https://chartbrew.com/blog/how-to-visualize-your-supabase-data-with-chartbrew/)+- Authentication with Supabase and React. [Blog](https://hyperfoo.io/posts/supabase-authentication-react)+- Supabase Schema Visualizer. [Blog](https://dev.to/zernonia/supabase-schema-visualizer-no-installation-login-49kg)+- Create a real-time UI using Next.js + Supabase. [Blog](https://pablopunk.com/posts/how-to-create-a-real-time-ui-with-nextjs-and-supabase)+- How to add Twitter auth quickly with Supabase to your Next.js site ⚡ [Blog](https://blog.avneesh.tech/how-to-add-twitter-auth-quickly-with-supabase-to-your-nextjs-site)+- Under the hood: Architecture and Technology Stack of Supabase ⚡ [Blog](https://www.workingsoftware.dev/tech-stack-and-architecture-of-supabase/)++### Podcasts++- [Software Engineering Daily](https://softwareengineeringdaily.com/2020/10/15/supabase-open-source-firebase-with-paul-copplestone/)+- [Heavy Bit](https://www.heavybit.com/library/podcasts/jamstack-radio/ep-71-open-source-firebase-alternative-with-paul-copplestone-of-supabase/)+- [Log Rocket](https://podrocket.logrocket.com/9)+- [FS Jam](https://fsjam.org/episodes/episode-33-supabase-with-paul-copplestone)diff --git a/apps/temp-docs/docs/guides/functions.mdx b/apps/temp-docs/docs/guides/functions.mdxnew file mode 100644index 00000000000..8bcab320554--- /dev/null+++ b/apps/temp-docs/docs/guides/functions.mdx@@ -0,0 +1,277 @@+---+id: functions+title: Edge Functions+description: 'Globally distributed TypeScript functions.'+sidebar_label: Overview+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++Edge Functions are server-side TypeScript functions, distributed globally at the edge—close to your users. They can be used for listening to webhooks or integrating your Supabase project with third-parties [like Stripe](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/stripe-webhooks).++Edge Functions are developed using [Deno](https://deno.com), which offers a few benefits to you as a developer:++- It is open source.+- It is portable. Supabase Edge Functions run locally, and on any other Deno-compatible platform (including self-hosted infrastructure).+- It is TypeScript first and supports WASM.+- Edge Functions are globally distributed for low-latency.++## Quickstart++Learn how to develop Edge Functions in less than 7 minutes:++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/rzglqRdZUQE"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Prerequisites++Follow the steps to prepare your Supabase project on your local machine.++- Install the Supabase CLI. [Docs](/docs/guides/cli).+- Login to the CLI using the command: `supabase login`. [Docs](/docs/reference/cli/usage#supabase-login).+- Initialize Supabase inside your project using the command: `supabase init`. [Docs](/docs/guides/cli/local-development#getting-started).+- Link to your Remote Project using the command `supabase link --project-ref your-project-ref`. [Docs](/docs/reference/cli/usage#supabase-link).+- Optional: Setup your environment: Follow [this setup guide](https://deno.land/manual/getting_started/setup_your_environment) to integrate the Deno language server with your editor.++## Getting Started++Let's build an Edge Function locally, then deploy it to the Supabase Platform.++### Creating a function++Let's create a new Edge Function called `hello-world` inside your project:++```bash+supabase functions new hello-world+```++This creates a function stub in your `supabase` folder at `./functions/hello-world/index.ts`.++### Deploy to production++```bash+supabase functions deploy hello-world+```++This command bundles your Edge Function from `./functions/hello-world/index.ts` and deploys it to the Supabase platform.+The command outputs a URL to the Supabase Dashboard which you can open to find view more details. Let's open the link to find the execution command.++:::note++By default, Edge Functions require a valid JWT in the authorization header. This header is automatically set when invoking your function via a Supabase client library.++If you want to use Edge Functions to handle webhooks (e.g. [Stripe payment webhooks](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/stripe-webhooks) etc.), you need to pass the `--no-verify-jwt` flag when deploying your function.++:::++### Executing Remote Functions++You can execute Edge Functions using curl. Copy the curl command from the Dashboard. It should look like this:++```bash+curl --request POST 'https://<project_ref>.functions.supabase.co/hello-world' \+ --header 'Authorization: Bearer ANON_KEY' \+ --header 'Content-Type: application/json' \+ --data '{ "name":"Functions" }'+```++If you receive an error `Invalid JWT`, find the `ANON_KEY` of your project in the Dashboard under `Settings > API`.++After invoking your Edge Function you should see the response `{ "message":"Hello Functions!" }`.++## Debugging your Functions++You can debug your deployed Edge Functions using the "Functions" section of the Dashboard. There are two types debugging tools available:++- Invocations: shows the Request and Response for each execution.+- Logs: shows any platform events, including deployments and errors.++++## Developing locally++You can run your Edge Function locally using [`supabase functions serve`](/docs/reference/cli/usage#supabase-functions-serve):++```bash+supabase start # start the supabase stack+supabase functions serve hello-world # start the Function watcher+```++The `functions serve` command has hot-reloading capabilities. It will watch for any changes to your files and restart the Deno server.++### Invoking Functions locally++While serving your local Function, you can execute it using curl:++```bash+curl --request POST 'http://localhost:54321/functions/v1/hello-world' \+ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \+ --header 'Content-Type: application/json' \+ --data '{ "name":"Functions" }'+```++You should see the response `{ "message":"Hello Functions!" }`.++<details>+<summary>Implementation details</summary>++- All Edge Functions are `POST` requests.+- The `Authorization` header is required. You can use either the `ANON` key, the `SERVICE_ROLE` key, or a logged-in user's JWT.+- The Function is proxied through the local API (`http://localhost:54321`)++</details>+<br />++If you execute Function with a different payload the response will change. <br />+Modify the `--data '{"name":"Functions"}'` line to `--data '{"name":"World"}'` and try invoking the command again!++## Secrets and Environment Variables++It's common that you will need to use sensitive information or environment-specific variables inside your Edge Functions. You can access these using Deno's built-in handler++```js+Deno.env.get(MY_SECRET_NAME)+```++### Default secrets++By default, Edge Functions have access to these secrets:++- `SUPABASE_URL`: The API gateway for your Supabase project.+- `SUPABASE_ANON_KEY`: The `anon` key for your Supabase API. This is safe to use in a browser when you have [Row Level Security](/docs/guides/auth/row-level-security) enabled.+- `SUPABASE_SERVICE_ROLE_KEY`: The `service_role` key for your Supabase API. This is safe to use in Edge Functions, but it should NEVER be used in a browser. This key will bypass [Row Level Security](/docs/guides/auth/row-level-security).+- `SUPABASE_DB_URL`: The URL for your [PostgreSQL database](/docs/guides/database). You can use this to connect directly to your database.++### Local secrets++Let's create a local file for storing our secrets, and inside it we can store a secret `MY_NAME`:++```jsx+echo "MY_NAME=Yoda" >> ./supabase/.env.local+```++This creates a new file `./supabase/.env.local` for storing your local development secrets.++:::caution++Never check your .env files into Git!++:::++Now let's access this environment variable `MY_NAME` inside our Function. Anywhere in your function, add this line:++```jsx+console.log(Deno.env.get('MY_NAME'))+```++Now we can invoke our function locally, by serving it with our new `.env.local` file:++```bash+supabase functions serve hello-world --env-file ./supabase/.env.local+```++When the function starts you should see the name “Yoda” output to the terminal.++### Production secrets++Let's create a `.env` for production. In this case we'll just use the same as our local secrets:++```bash+cp ./supabase/.env.local ./supabase/.env+```++This creates a new file `./supabase/.env` for storing your production secrets.++:::caution++Never check your `.env` files into Git!++:::++Let's push all the secrets from the `.env` file to our remote project using [`supabase secrets set`](/docs/reference/cli/usage#supabase-secrets-set):++```bash+supabase secrets set --env-file ./supabase/.env++# You can also set secrets individually using:+supabase secrets set MY_NAME=Chewbacca+```++You don't need to re-deploy after setting your secrets.++To see all the secrets which you have set remotely, use [`supabase secrets list`](/docs/reference/cli/usage#supabase-secrets-list):++```bash+supabase secrets list+```++## Suggestions++### Database Functions vs Edge Functions++For data-intensive operations we recommend using [Database Functions](/docs/guides/database/functions), which are executed within your database+and can be called remotely using the [REST and GraphQL API](/docs/guides/api).++For use-cases which require low-latency we recommend [Edge Functions](/docs/guides/functions), which are globally-distributed and can be written in TypeScript.++### Organizing your Edge Functions++We recommend developing “fat functions”. This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (`_`). We recommend this folder structure:++```bash+└── supabase+ ├── functions+ │ ├── _shared+ │ | ├── supabaseAdmin.ts # Supabase client with SERVICE_ROLE key+ │ │ └── supabaseClient.ts # Supabase client with ANON key+ │ ├── function-one # use hyphens to name functions+ │ │ └── index.ts+ │ └── function-two+ │ └── index.ts+ ├── migrations+ └── config.toml+```++### Naming Edge Functions++We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase).++### CORS (Cross-Origin Resource Sharing)++We recommend adding a check to handle [CORS Preflight](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) requests in your edge function to be able to invoke the function from browsers.++See the [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/browser-with-cors/index.ts).++```ts+export const corsHeaders = {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey',+}++serve(async (req) => {+ if (req.method === 'OPTIONS') {+ return new Response('ok', { headers: corsHeaders })+ }+ ...+})+```++### Using HTTP Methods++Edge Functions supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS`. A function can be designed to perform different actions based on a request's HTTP method. See the [example on building a RESTful service](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/restful-tasks) to learn how to handle different HTTP methods in your function.++## Limitations++- Deno Deploy limitations+ - Deno does not support outgoing connections to ports `25`, `465`, and `587`.+ - Cannot write to File System+- Edge Functions+ - Local development - only one function at a time+ - Serving of HTML content is not supported (`GET` requests that return `text/html` will be rewritten to `text/plain`).diff --git a/apps/temp-docs/docs/guides/functions/auth.mdx b/apps/temp-docs/docs/guides/functions/auth.mdxnew file mode 100644index 00000000000..da021238a02--- /dev/null+++ b/apps/temp-docs/docs/guides/functions/auth.mdx@@ -0,0 +1,63 @@+---+id: auth+title: Auth+description: Supabase Edge Functions and Auth.+---++Edge Functions work seamlessly with [Supabase Auth](/docs/guides/auth), allowing you to identify which user called your function.++When [invoking](/docs/reference/javascript/invoke) a function with one of the [client libraries](/docs/reference), the logged in user's JWT is automatically attached to the function call and becomes accessible within your function.++This is important, for example, to identify which customer's credit card should be charged. You can see this concept end-to-end in our [Stripe example app](https://github.com/supabase-community/expo-stripe-payments-with-supabase-functions).++## Auth Context & RLS++By creating a supabase client with the auth context from the function, you can do two things:++1. Get the user object.+2. Run queries in the context of the user with [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies enforced.++```js title="supabase/functions/select-from-table-with-auth-rls/index.ts"+import { serve } from 'https://deno.land/[email protected]/http/server.ts'+import { createClient } from 'https://esm.sh/@supabase/[email protected]'++serve(async (req: Request) => {+ try {+ // Create a Supabase client with the Auth context of the logged in user.+ const supabaseClient = createClient(+ // Supabase API URL - env var exported by default.+ Deno.env.get('SUPABASE_URL') ?? '',+ // Supabase API ANON KEY - env var exported by default.+ Deno.env.get('SUPABASE_ANON_KEY') ?? '',+ // Create client with Auth context of the user that called the function.+ // This way your row-level-security (RLS) policies are applied.+ // highlight-next-line+ { global: { headers: { Authorization: req.headers.get('Authorization')! } } }+ )+ // Now we can get the session or user object+ // highlight-start+ const {+ data: { user },+ } = await supabaseClient.auth.getUser()+ // highlight-end++ // And we can run queries in the context of our authenticated user+ // highlight-start+ const { data, error } = await supabaseClient.from('users').select('*')+ if (error) throw error+ // highlight-end++ return new Response(JSON.stringify({ user, data }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ } catch (error) {+ return new Response(JSON.stringify({ error: error.message }), {+ headers: { 'Content-Type': 'application/json' },+ status: 400,+ })+ }+})+```++See the [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts).diff --git a/apps/temp-docs/docs/guides/functions/cicd-workflow.mdx b/apps/temp-docs/docs/guides/functions/cicd-workflow.mdxnew file mode 100644index 00000000000..d876604da88--- /dev/null+++ b/apps/temp-docs/docs/guides/functions/cicd-workflow.mdx@@ -0,0 +1,36 @@+---+id: cicd-workflow+title: CI / CD Workflow+description: How to deploy Supabase Edge Functions with a CI / CD pipeline.+---++As described in the Supabase CLI [Environments Guide](/docs/guides/cli/managing-environments), you can use the [`setup-cli` GitHub Action](https://github.com/marketplace/actions/supabase-cli-action) to run Supabase CLI commands in your GitHub Actions, for example to deploy a Supabase Edge Function:++```yaml+name: Deploy Function++on:+ push:+ branches:+ - main+ workflow_dispatch:++jobs:+ deploy:+ runs-on: ubuntu-latest++ env:+ SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}+ PROJECT_ID: zdtdtxajzydjqzuktnqx++ steps:+ - uses: actions/checkout@v3++ - uses: supabase/setup-cli@v1+ with:+ version: 1.0.0++ - run: supabase functions deploy your-function-name --project-ref $PROJECT_ID+```++See the [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/.github/workflows/deploy.yaml).diff --git a/apps/temp-docs/docs/guides/functions/examples.mdx b/apps/temp-docs/docs/guides/functions/examples.mdxnew file mode 100644index 00000000000..39a48de9a0b--- /dev/null+++ b/apps/temp-docs/docs/guides/functions/examples.mdx@@ -0,0 +1,57 @@+---+id: examples+title: Examples+description: Useful Supabase Edge Functions Examples.+---++import ButtonCard from '@site/src/components/ButtonCard'+const examples = [+ {+ name: 'With supabase-js',+ description: 'Use the Supabase client inside your Edge Function.',+ href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts',+ },+ {+ name: 'With CORS headers',+ description: 'Send CORS headers for invoking from the browser.',+ href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/browser-with-cors/index.ts',+ },+ {+ name: 'React Native with Stripe',+ description: 'Full example for using Supabase and Stripe, with Expo.',+ href: 'https://github.com/supabase-community/expo-stripe-payments-with-supabase-functions',+ },+ {+ name: 'Flutter with Stripe',+ description: 'Full example for using Supabase and Stripe, with Flutter.',+ href: 'https://github.com/supabase-community/flutter-stripe-payments-with-supabase-functions',+ },+ {+ name: 'Building a RESTful Service API',+ description: 'Learn how to use HTTP methods and paths to build a RESTful service for managing tasks.',+ href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/restful-tasks/index.ts',+ },+ {+ name: 'Working with Supabase Storage',+ description: 'An example on reading a file from Supbase Storage.',+ href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/read-storage/index.ts',+ }+]++You can find a list of useful [Edge Function Examples](https://github.com/supabase/supabase/tree/master/examples/edge-functions) in our GitHub repository.++<div class="container" style={{ padding: 0 }}>+ <div class="row is-multiline">+ {examples.map((x) => (+ <div class="col col--6">+ <ButtonCard+ class="card"+ to={x.href}+ title={x.name}+ description={x.description}+ style={{ height: '100%' }}+ />+ </div>+ ))}+ </div>+</div>diff --git a/apps/temp-docs/docs/guides/hosting/docker.mdx b/apps/temp-docs/docs/guides/hosting/docker.mdxindex 933db721189..1b0ea6fa0d6 100644--- a/apps/temp-docs/docs/guides/hosting/docker.mdx+++ b/apps/temp-docs/docs/guides/hosting/docker.mdx@@ -1,7 +1,8 @@---id: docker-title: With Docker-description: How to use configure and deploy Supabase.+title: Self-hosting with Docker+description: How to configure and deploy Supabase.+sidebar_label: Docker---Docker is the easiest way to get started with self-hosted Supabase.@@ -10,70 +11,94 @@ Docker is the easiest way to get started with self-hosted Supabase.You need the following installed in your system:-- [Docker](https://docs.docker.com/engine/install/) and docker-compose+- [Docker](https://docs.docker.com/engine/install/) and [docker-compose](https://docs.docker.com/compose/install/)- [Git](https://git-scm.com/downloads)-## Getting started+## Quick Start### Get the codeCheckout the docker directory in the Supabase repo:```sh+# Get the codegit clone --depth 1 https://github.com/supabase/supabase-cd supabase/docker-```--### Manage Secrets-Copy `.env.example` to `.env` and populate the values.+# Go to the docker folder+cd supabase/docker-```sh+# Copy the fake env varscp .env.example .env++# Start+docker-compose up```-In particular, these are required:+Now visit [http://localhost:3000](http://localhost:3000) to start using Supabase Studio.++## Securing your setup-- `POSTGRES_PASSWORD`: the password for the `postgres` role-- `JWT_SECRET`: used by PostgREST and GoTrue, among others-- `SITE_URL`: the base URL of your site-- `SMTP_*`: mail server credentials+While we provided you with some example secrets for getting started, you should NEVER deploy your Supabase setup using the defaults we have provided.++Please follow these steps to secure your Docker setup. We [strongly recommend](../../guides/hosting/overview#managing-your-secrets) using a secrets manager when deploying to production.### Generate API Keys-Use your `JWT_SECRET` to generate a `anon` and `service` API keys using the [JWT generator](/docs/guides/hosting/overview#api-keys).+Use your `JWT_SECRET` to generate a `anon` and `service` API keys using the [JWT generator](../../guides/hosting/overview#api-keys).Replace the values in these files:-- `docker-compose.yml`:+- `.env`:- `ANON_KEY` - replace with an `anon` key- - `SERVICE_KEY` - replace with a `service` key-- `volumes/kong.yml`+ - `SERVICE_ROLE_KEY` - replace with a `service` key+- `volumes/api/kong.yml`- `anon` - replace with an `anon` key- `service_role` - replace with a `service` key-### Start+### Update Secrets-You can now start Supabase:+Update the `.env` file with your own secrets. In particular, these are required:-```sh-docker-compose up-```+- `POSTGRES_PASSWORD`: the password for the `postgres` role.+- `JWT_SECRET`: used by PostgREST and GoTrue, among others.+- `SITE_URL`: the base URL of your site.+- `SMTP_*`: mail server credentials. You can use any SMTP server.-Your database will be persisted in `volumes/db/data`, and your storage objects in `volumes/storage`.+### Securing the Dashboard-Try out the examples in `supabase/examples` to verify if it works correctly!+The Docker setup doesn't include a management database for managing users and logins. If you plan to deploy the Studio to the web we suggest you put it behind a web proxy with Basic Auth or hide it behind a VPN.## Configuration+Each system can be [configured](../../guides/hosting/overview#configuration) to suit your particular use-case.+To keep the setup simple, we made some choices that may not be optimal for production:- the database is in the same machine as the servers-- the storage uses the filesystem backend instead of S3+- Storage uses the filesystem backend instead of S3+- Auth should be configured with a production-ready SMTP server++### Using an external database++We strongly [recommend](../../guides/hosting/overview#managing-your-database) that you decouple your database from `docker-compose` before deploying.+The middleware will run with any PostgreSQL database that has logical replication enabled. The following environment variables should be updated+in the `.env` file to point to your external database:++```env title=".env"+POSTGRES_PASSWORD=your-super-secret-and-long-postgres-password++POSTGRES_HOST=db+POSTGRES_DB=postgres+POSTGRES_USER=postgres+POSTGRES_PORT=5432+```++Once you have done this, you can safely comment out the `db` section of the `docker-compose` file, and remove any instances where the services `depends_on` the `db` image.++### Setting database's `log_min_messages`-We strongly [recommend](/docs/guides/hosting/overview#managing-your-database) that you decouple your database-before deploying.-Each system can be [configured](/docs/guides/hosting/overview#configuration) to suit your particular use-case.+By default, `docker-compose` sets the database's `log_min_messages` configuration to `fatal` to prevent redundant logs generated by Realtime.+However, you might miss important log messages such as database errors. Configure `log_min_messages` based on your needs.## Deployingdiff --git a/apps/temp-docs/docs/guides/hosting/overview.mdx b/apps/temp-docs/docs/guides/hosting/overview.mdxindex cab86235072..f8f9c96a88a 100644--- a/apps/temp-docs/docs/guides/hosting/overview.mdx+++ b/apps/temp-docs/docs/guides/hosting/overview.mdx@@ -10,23 +10,9 @@ import JwtGenerator from '@site/src/components/JwtGenerator'There are several ways to use Supabase:- [Supabase Cloud](https://app.supabase.com): you don't need to deploy anything. We will manage and scale your infrastructure.-- [Docker](/docs/guides/hosting/docker): deploy to your own infrastructure.+- [Docker](../../guides/hosting/docker): deploy to your own infrastructure.- Kubernetes: coming soon.-#### Before you begin--The self-hosted version of Supabase does not include a UI yet.-We are working on this in stages, starting with our [UI library](https://github.com/supabase/ui) and with a [WIP PR here](https://github.com/supabase/supabase/pull/2281).-[[more context](https://github.com/supabase/supabase/discussions/1001#discussioncomment-558696)]--In the meantime, here are some suggestions for working with your Postgres Database:--- `pgadmin`: https://www.pgadmin.org-- `dbeaver`: https://dbeaver.com-- `BeeKeeper`: https://beekeeperstudio.io-- `HeidiSQL`: https://heidisql.com-- `Table Plus`: https://www.tableplus.io-## ArchitectureSupabase is a combination of open source tools, each specifically chosen for Enterprise-readiness.@@ -34,15 +20,15 @@ Supabase is a combination of open source tools, each specifically chosen for EntIf the tools and communities already exist, with an MIT, Apache 2, or equivalent open license, we will use and support that tool.If the tool doesn't exist, we build and open source it ourselves.-+-- [PostgreSQL](https://www.postgresql.org/) is an object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance.-- [Realtime](https://github.com/supabase/realtime) is an Elixir server that allows you to listen to PostgreSQL inserts, updates, and deletes using websockets. Supabase listens to Postgres' built-in replication functionality, converts the replication byte stream into JSON, then broadcasts the JSON over websockets.+- [Kong](https://github.com/Kong/kong) is a cloud-native API gateway.+- [GoTrue](https://github.com/netlify/gotrue) is an SWT based API for managing users and issuing SWT tokens.- [PostgREST](http://postgrest.org/) is a web server that turns your PostgreSQL database directly into a RESTful API+- [Realtime](https://github.com/supabase/realtime) is an Elixir server that allows you to listen to PostgreSQL inserts, updates, and deletes using websockets. Realtime polls Postgres' built-in replication functionality for database changes, converts changes to JSON, then broadcasts the JSON over websockets to authorized clients.- [Storage](https://github.com/supabase/storage-api) provides a RESTful interface for managing Files stored in S3, using Postgres to manage permissions.- [postgres-meta](https://github.com/supabase/postgres-meta) is a RESTful API for managing your Postgres, allowing you to fetch tables, add roles, and run queries, etc.-- [GoTrue](https://github.com/netlify/gotrue) is an SWT based API for managing users and issuing SWT tokens.-- [Kong](https://github.com/Kong/kong) is a cloud-native API gateway.+- [PostgreSQL](https://www.postgresql.org/) is an object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance.## Configuration@@ -60,7 +46,7 @@ Each system has a number of configuration options which can be found in the releIt is recommended that you decouple your database from the middleware so that you can upgrade the middleware without any downtime.The "middleware" is everything except Postgres, and it should work with any Postgres provider (such as AWS RDS), or your own Postgres cluster.-### Database Extensions+### ExtensionsSupabase requires some Postgres extensions to be enabled by default for the API and Auth system to work. You can find the extensions inside the[schema initialization script](https://github.com/supabase/supabase/blob/master/docker/volumes/db/init/00-initial-schema.sql).@@ -83,7 +69,7 @@ For UUID functions, required for PostgreSQL <13.For working with JWT and Auth functions.-### Database Roles+### RolesSupabase creates several default roles in your Postgres database. To restore defaults at any time you can run the commands inside the[schema initialization script](https://github.com/supabase/supabase/blob/master/docker/volumes/db/init/00-initial-schema.sql).@@ -125,6 +111,10 @@ For running commands via the Supabase UI.Supabase Administrative role for maintaining your database.+### Realtime Logs++Set your database's `log_min_messages` configuration to `fatal` to prevent redundant database logs generated by Realtime. However, you might miss important log messages such as database errors. Configure `log_min_messages` based on your needs.+## API KeysThe API Gateway (Kong) uses JWT to authenticate access through to the database. The JWT should correspond to a relevant Postgres Role,@@ -154,3 +144,12 @@ If you have decoupled your database from the middleware, then you should be ableSupabase is evolving fast, and we'll continue to improve the migration strategy as part of our core offering.We realize that database migrations are difficult, and this is one of the problems we plan to make easy for developers.++## Deployment options++While Supabase officially supports Docker, we have several other deployment strategies managed by the community:++- [supabase-docker](../../guides/hosting/docker) (Official)+- [supabase-kubernetes](https://github.com/supabase-community/supabase-kubernetes) (Unofficial)+- [supabase-terraform](https://github.com/supabase-community/supabase-terraform) (Unofficial)+- [supabase-traefik](https://github.com/supabase-community/supabase-traefik) (Unofficial)diff --git a/apps/temp-docs/docs/guides/hosting/platform.mdx b/apps/temp-docs/docs/guides/hosting/platform.mdxindex 501db3765ce..bbfe32e34f8 100644--- a/apps/temp-docs/docs/guides/hosting/platform.mdx+++ b/apps/temp-docs/docs/guides/hosting/platform.mdx@@ -1,34 +1,85 @@---id: platformtitle: Supabase Platform-description: Getting started with the Supabase platform.+description: Getting started with the Supabase Platform.+sidebar_label: Overview---Supabase is a hosted platform which makes it very simple to get started without needing to manage any infrastructure.Visit [app.supabase.com](https://app.supabase.com) and sign in to start creating projects.+## Projects++Each project on Supabase comes with:++- A dedicated [Postgres database](/docs/guides/database)+- [Auto-generated APIs](/docs/guides/api)+- [Auth and user management](/docs/guides/auth)+- [Edge Functions](/docs/guides/functions)+- [Realtime API](/docs/guides/realtime)+- [Storage](/docs/guides/storage)+## Organizations-Organizations are a way to group your projects. Every Organization can be configured with different Team members and billing settings.+Organizations are a way to group your projects. Each organization can be configured with different team members and billing settings.-### Managing Team Members+## Manage team members-You can invite your Team members into your Organizations so that you can collaborate on projects.+You can invite your team members into your organizations to collaborate on projects.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/invite-team.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/invite-team.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-## Projects+You can also assign roles to your team members with different access levels. The table below shows the corresponding permissions for each available role in the Dashboard.++| Permissions | Owner | Administrator | Developer |+| ------------------------ | ----- | ------------- | --------- |+| **Organization** |+| Change organization name | ✅ | | |+| Delete organization | ✅ | | |+| **Members** |+| Add an Owner | ✅ | | |+| Remove an Owner | ✅ | | |+| Add an Adminstrator | ✅ | ✅ | |+| Remove an Administrator | ✅ | ✅ | |+| Add a Developer | ✅ | ✅ | |+| Remove a Developer | ✅ | ✅ | |+| Revoke an invite | ✅ | ✅ | |+| Resend an invite | ✅ | ✅ | |+| **Billing** |+| Read invoices | ✅ | ✅ | ✅ |+| Read billing email | ✅ | ✅ | ✅ |+| Change billing email | ✅ | | |+| View subscription | ✅ | ✅ | ✅ |+| Update subscription | ✅ | ✅ | |+| Read billing address | ✅ | ✅ | ✅ |+| Update billing address | ✅ | ✅ | |+| Read tax codes | ✅ | ✅ | ✅ |+| Update tax codes | ✅ | ✅ | |+| Read payment methods | ✅ | ✅ | ✅ |+| Update payment methods | ✅ | ✅ | |+| **Projects** |+| Create a project | ✅ | ✅ | |+| Delete a project | ✅ | ✅ | |+| Update a project | ✅ | ✅ | |+| Pause a project | ✅ | ✅ | |+| Resume a project | ✅ | ✅ | |+| Restart a project | ✅ | ✅ | ✅ |-Each project on Supabase comes with these features:+## Platform status-- A dedicated Postgres database. [Learn more](/docs/guides/database)-- Auto-generated APIs.-- User management. [Learn more](/docs/guides/auth)-- Storage. [Learn more](/docs/guides/storage)+If Supabase experiences outages, we keep you as informed as possible, as early as possible. We provide the following feedback channels:-## Next Steps+- Status page: [status.supabase.com](https://status.supabase.com/)+- RSS Feed: [status.supabase.com/history.rss](https://status.supabase.com/history.rss)+- Atom Feed: [status.supabase.com/history.atom](https://status.supabase.com/history.atom)+- Slack Alerts: You can receive updates via the RSS feed, using Slack's [built-in RSS functionality](https://slack.com/help/articles/218688467-Add-RSS-feeds-to-Slack) <br />`/feed subscribe https://status.supabase.com/history.atom`-- Sign in to [app.supabase.com](https://app.supabase.com)+Make sure to review our [SLA](/docs/company/sla) for details on our commitment to Platform Stability.diff --git a/apps/temp-docs/docs/guides/integrations/appsmith.mdx b/apps/temp-docs/docs/guides/integrations/appsmith.mdxnew file mode 100644index 00000000000..47357c345ea--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/appsmith.mdx@@ -0,0 +1,166 @@+---+id: appsmith+title: 'Appsmith'+description: 'Get started with Supabase and Appsmith, an open-source framework for building internal tools.'+---++This guide explains how to quickly build a Support Dashboard by connecting a Supabase back-end to an Appsmith front-end.++[Appsmith](https://www.appsmith.com/) is an open-source framework for building internal tools. It lets you drag-and-drop UI components to build pages, connect to any API, database or GraphQL source and write logic with JavaScript objects.++If you don’t have an Appsmith account, create one [here](https://app.appsmith.com/user/signup).++Let’s get started!++## Step 1: Set up your Backend on Supabase++- On the [Supabase dashboard](https://app.supabase.com), click `New project` and set the name to **Support Dashboard**++++- Create a new table by clicking on the Create Table option on the side navigation.+- Supabase provides many ways to add data to the tables, from writing queries to creating schemas using UI to simply uploading CSV files. For our support dashboard, we will be creating the **tickets** table by uploading the [CSV file](https://raw.githubusercontent.com/vihar/datasets/master/tickets.csv) on Supabase.++++The database is now set up.++## Step 2: Connect the database to Appsmith++- Note down the database connection information under Project Settings in Supabase.++++- On Appsmith, create a new application under the dashboard under your preferred organization.+- Click on the `+` icon next to Datasources on the left navigation bar under Page1+- Next, click on Create New tab and choose PostgreSQL datasource, you’ll see the following screenshot:++++- Fill out the form to connect to your Supabase instance. Click **Test** to test connection and then **Save** to save the datasource++++## Step 3: Build UI on Appsmith++- Click on the + icon next to widgets and drag and drop a Tab widget. We can configure using the property pane by clicking on the cog icon on the top-right corner.+- As seen in the below screenshot, we have added four tabs to support the dashboard.++++- Add widgets to the **Home** tab to create the dashboard as shown in the screenshot below. For eg: **Critical Open Issues** is a **Text** widget and below it is an **Input** widget which we will bind later to display the number of open tickets.++- Set up the **New** button to open a modal which will have a form to raise a new ticket.++++- In the modal widget, add a few widgets to accept input when creating a new ticket. Please refer to the screenshot below.++++## Step 4: Writing Queries in Appsmith and binding data to widgets++- Click on the + icon next to Datasources on the navigation bar and click New Query next to the Supabase connection here to create a new query.++++- Rename the query to create_new_ticket under the query pane; here we can write SQL that can collect the data from the widgets using mustache templates.++```jsx+INSERT INTO PUBLIC."tickets"("id","createdAt","user","updatedAt","description",+"status","priority","category","assignedTo")+VALUES('{{appsmith.store.ticket.id}}','{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_user.text}}',+'{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_description.text}}','{{c_status.selectedOptionValue}}',+'{{c_property.selectedOptionValue}}',+'{{c_category.selectedOptionValue}}','{{c_assignee.selectedOptionValue}}');+```++- Click the **Confirm** button on the modal and under **Events**, set the **onClick** property to execute the create_new_ticket query.+- Create a second query named **get_tickets** that will list all the tickets.++ ***++```jsx+SELECT * FROM public."tickets";+```++- Drag and drop a table widget under the **Assigned To Me** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results.++```jsx+{+ {+ get_tickets.data.filter(+ (t) => t.assignedTo === '[email protected]' && t.status !== 'closed'+ )+ }+}+```++- Drag and drop a table widget under the **Resolved** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results.++```jsx+{+ {+ get_tickets.data.filter((t) => t.status === 'open')+ }+}+```++- Drag and drop a table widget under the **Closed** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results.++```jsx+{+ {+ get_tickets.data.filter((t) => t.status === 'closed')+ }+}+```++## Step 5: Creating Charts in Appsmith++- On the **Home** tab, click on the first Chart widget. Add Title **Open Issues By Category**. Change the **Chart Type** property to **Column Chart**.+- Update the x-axis and y-axis Labels under **Axis** on the property pane.+- Add the following code snippet under the **Series Data** property to bind the data to be displayed on the x and y axes.++```jsx+[+ {+ "x": "Hardware",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='hardware').length}}+ },+ {+ "x": "Software",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='software').length}}+ },+ {+ "x": "Other",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='other').length}}+ }+]+```++- The second chart will be a pie chart. Add the title, axes labels as mentioned above,+- Add the following code snippet under the **Series Data** property of the pie chart.++```jsx+[+ {+ "x": "High",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='high').length}}+ },+ {+ "x": "Medium",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='medium').length}}+ },+ {+ "x": "Low",+ "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='low').length}}+ }+]+```++## Resources++- [Appsmith](https://www.appsmith.com/) official website.+- [Appsmith GitHub](https://github.com/appsmithorg).+- [Appsmith](https://docs.appsmith.com/) documentation.diff --git a/apps/temp-docs/docs/guides/integrations/auth0.mdx b/apps/temp-docs/docs/guides/integrations/auth0.mdxnew file mode 100644index 00000000000..91e989b40d4--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/auth0.mdx@@ -0,0 +1,461 @@+---+id: auth0+title: 'Auth0'+description: 'Swap out Supabase authentication with Auth0. Let Auth0 handle tokens and signing users in and out, while Supabase enforces authorization policies with Row Level Security (RLS).'+---++This guide steps through building a Next.js application with Auth0 and Supabase. We configure Auth0 to handle authenticating users and managing tokens, while writing our authorization logic in Supabase - using Row Level Security policies.++> Note: This guide is heavily inspired by the [Using Next.js and Auth0 with Supabase](https://auth0.com/blog/using-nextjs-and-auth0-with-supabase/) article on [Auth0's blog](https://auth0.com/blog/). Check it out for a practical step-by-step guide on integrating Auth0 and Supabase.++The full code example for this guide can be found [here](https://github.com/dijonmusters/supabase-auth0-example).++[Auth0](https://auth0.com/) is an authentication and authorization platform, offering numerous strategies to authenticate and manage users. It provides fine-grain control over how users sign in to your application, the token that is generated, and what data is stored about your users.++[Next.js](https://nextjs.org/) is a web application framework built on top of React. We will be using it for this example, as it allows us to write server-side logic within our application. Auth0 have also written a [very well integrated authentication library](https://www.npmjs.com/package/@auth0/nextjs-auth0) specifically for Next.js.++> Note: API routes (serverless functions) in Next.js closely resemble the structure of Node server frameworks - such as Express, Koa and Fastify. The server-side logic in this guide could easily be refactored in one of these frameworks and managed as a separate application to the front-end.++If you don’t have an Auth0 account, create one [here](https://auth0.com/signup).++You will also need a Supabase account, which can be created by signing in [here](https://app.supabase.com/).++## Step 1: Creating an Auth0 tenant++From the Auth0 dashboard, click the menu to the right of the Auth0 logo, and select `Create tenant`.++++Enter a `Domain` for your tenant - this will need to be unique.++Select a `Region` - this should be geographically close to the majority of your users.++Select `Development` for `Environment Tag` - this should be production when you're ready to go live.++++## Step 2: Setting up an Auth0 application++From the sidebar menu, select `Applications` > `Applications` and click `Create Application`.++Give your application a name, select the `Regular Web Applications` option and click `Create`.++++Select `Settings` and navigate to the `Application URIs` section, and update the following:++`Allowed Callback URLs`: `http://localhost:3000/api/auth/callback`++`Allowed Logout URLs`: `http://localhost:3000`++Scroll to the bottom of the `Settings` section and reveal the `Advanced Settings`.++Select `OAuth` and set `JSON Web Token Signature` to `RS256`.++Confirm `OIDC Conformant` is `Enabled`.++Click `Save` to update the settings.++## Step 3: Creating a Supabase project++From your [Supabase dashboard](https://app.supabase.com/), click `New project`.++Enter a `Name` for your Supabase project.++Enter a secure `Database Password`.++Select the same `Region` you selected for your Auth0 tenant.++Click `Create new project`.++++## Step 4: Creating data in Supabase++From the sidebar menu in the [Supabase dashboard](https://app.supabase.com/), click `Table editor`, then `New table`.++Enter `todo` as the `Name` field.++Select `Enable Row Level Security (RLS)`.++Create two new columns:++- `title` as `text`+- `user_id` as `text`+- `is_complete` as `bool` with the default value `false`++Click `Save` to create the new table.++++From the `Table editor` view, select the `todo` table and click `Insert row`.++Fill out the `title` field and click `Save`.++++Click `Insert row` and add a couple of extra todos.++++## Step 5: Building a Next.js app++Create a new Next.js project:++```bash+npx create-next-app <name-of-project>+```++Create a `.env.local` file and enter the following values:++```+AUTH0_SECRET=any-secure-value+AUTH0_BASE_URL=http://localhost:3000+AUTH0_ISSUER_BASE_URL=https://<name-of-your-tenant>.<region-you-selected>.auth0.com+AUTH0_CLIENT_ID=get-from-auth0-dashboard+AUTH0_CLIENT_SECRET=get-from-auth0-dashboard+NEXT_PUBLIC_SUPABASE_URL=get-from-supabase-dashboard+NEXT_PUBLIC_SUPABASE_KEY=get-from-supabase-dashboard+SUPABASE_SIGNING_SECRET=get-from-supabase-dashboard+```++> Note: Auth0 values can be found under `Settings > Basic Information` for your application.++++> Note: Supabase values can be found under `Settings > API` for your project.++++Restart your Next.js development server to read in the new values from `.env.local`.++```bash+npm run dev+```++## Step 6: Install Auth0 Next.js library++Install the `@auth0/nextjs-auth0` library.++```bash+npm i @auth0/nextjs-auth0+```++Create a new file `pages/api/auth/[...auth0].js` and add:++```jsx+// pages/api/auth/[...auth0].js++import { handleAuth } from '@auth0/nextjs-auth0'++export default handleAuth()+```++> Note: This will create a few API routes for us. The main ones we will use are `/api/auth/login` and `/api/auth/logout` to handle signing users in and out.++Open `pages/_app.js` and wrap our `Component` with the `UserProvider` from Auth0:++```jsx+// pages/_app.js++import React from 'react'+import { UserProvider } from '@auth0/nextjs-auth0'++const App = ({ Component, pageProps }) => {+ return (+ <UserProvider>+ <Component {...pageProps} />+ </UserProvider>+ )+}++export default App+```++Update `pages/index.js` to ensure the user is logged in to view the landing page.++```jsx+// pages/index.js++import styles from '../styles/Home.module.css'+import { withPageAuthRequired } from '@auth0/nextjs-auth0'+import Link from 'next/link'++const Index = ({ user }) => {+ return (+ <div className={styles.container}>+ <p>+ Welcome {user.name}!{' '}+ <Link href="/api/auth/logout">+ <a>Logout</a>+ </Link>+ </p>+ </div>+ )+}++export const getServerSideProps = withPageAuthRequired()++export default Index+```++> Note: `withPageAuthRequired` will automatically redirect the user to `/api/auth/login` if they are not currently logged in.++Test this is working by navigating to `http://localhost:3000` which should redirect you to an Auth0 sign in screen.++++Either `Sign up` for a new account, or click `Continue with Google` to sign in.++You should now be able to view the landing page.++++## Step 7: Sign Auth0 token for Supabase++Currently, neither Supabase or Auth0 allow for a custom signing secret to be set for their JWT. They also use different [signing algorithms](https://auth0.com/docs/configure/applications/signing-algorithms).++Therefore, we need to extract the bits we need from Auth0's JWT, and sign our own to send to Supabase.++We can do that using Auth0's `afterCallback` function, which gets called anytime the user authenticates.++Install the `jsonwebtoken` library.++```bash+npm i jsonwebtoken+```++Update `pages/api/auth/[...auth0].js` with the following:++```jsx+// pages/api/auth/[...auth0].js++import { handleAuth, handleCallback } from '@auth0/nextjs-auth0'+import jwt from 'jsonwebtoken'++const afterCallback = async (req, res, session) => {+ const payload = {+ userId: session.user.sub,+ exp: Math.floor(Date.now() / 1000) + 60 * 60,+ }++ session.user.accessToken = jwt.sign(+ payload,+ process.env.SUPABASE_SIGNING_SECRET+ )++ return session+}++export default handleAuth({+ async callback(req, res) {+ try {+ await handleCallback(req, res, { afterCallback })+ } catch (error) {+ res.status(error.status || 500).end(error.message)+ }+ },+})+```++Our `payload` for the JWT will contain our user's unique identifier from Auth0 - `session.user.sub` and an expiry of 1 hour.++We are signing this JWT using Supabase's signing secret, so Supabase will be able to validate it is authentic and hasn't been tampered with in transit.++> Note: We need to sign the user out and back in again to run the `afterCallback` function, and create our new token.++Now we just need to send the token along with the request to Supabase.++## Step 8: Requesting data from Supabase++Create a new file called `utils/supabase.js` and add the following:++```jsx+// utils/supabase.js++import { createClient } from '@supabase/supabase-js'++const getSupabase = (access_token) => {+ const supabase = createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.NEXT_PUBLIC_SUPABASE_KEY+ )++ if (access_token) {+ supabase.auth.session = () => ({+ access_token,+ })+ }++ return supabase+}++export { getSupabase }+```++This will be our client for talking to Supabase. We can pass it an `access_token` and it will be attached to our request.++Let's load our `todos` from Supabase in our landing page!++```jsx+// pages/index.js++import styles from '../styles/Home.module.css'+import { withPageAuthRequired } from '@auth0/nextjs-auth0'+import { getSupabase } from '../utils/supabase'+import Link from 'next/link'+import { useEffect } from 'react'++const Index = ({ user }) => {+ const [todos, setTodos] = useState([])+ const supabase = getSupabase(user.accessToken)++ useEffect(() => {+ const fetchTodos = async () => {+ const { data } = await supabase.from('todo').select('*')+ setTodos(data)+ }++ fetchTodos()+ }, [])++ return (+ <div className={styles.container}>+ <p>+ Welcome {user.name}!{' '}+ <Link href="/api/auth/logout">+ <a>Logout</a>+ </Link>+ </p>+ {todos?.length > 0 ? (+ todos.map((todo) => <p key={todo.id}>{todo.content}</p>)+ ) : (+ <p>You have completed all todos!</p>+ )}+ </div>+ )+}++export const getServerSideProps = withPageAuthRequired()++export default Index+```++Alternatively, we could fetch todos on the server using the `getServerSideProps` function.++```jsx+// pages/index.js++import styles from '../styles/Home.module.css'+import { withPageAuthRequired, getSession } from '@auth0/nextjs-auth0'+import { getSupabase } from '../utils/supabase'+import Link from 'next/link'++const Index = ({ user, todos }) => {+ return (+ <div className={styles.container}>+ <p>+ Welcome {user.name}!{' '}+ <Link href="/api/auth/logout">+ <a>Logout</a>+ </Link>+ </p>+ {todos?.length > 0 ? (+ todos.map((todo) => <p key={todo.id}>{todo.content}</p>)+ ) : (+ <p>You have completed all todos!</p>+ )}+ </div>+ )+}++export const getServerSideProps = withPageAuthRequired({+ async getServerSideProps({ req, res }) {+ const {+ user: { accessToken },+ } = await getSession(req, res)++ const supabase = getSupabase(accessToken)++ const { data: todos } = await supabase.from('todo').select('*')++ return {+ props: { todos },+ }+ },+})++export default Index+```++Either way, when we reload our application, we are still getting the empty state for todos.++++This is because we enabled Row Level Security, which blocks all requests by default. To enable our user to select their `todos` we need to write a policy.++## Step 9: Write a policy to allow select++Our policy will need to know who our currently logged in user is to determine whether or not they should have access. Let's create a PostgreSQL function to extract the current user from our new JWT.++Navigate back to the Supabase dashboard, select `SQL` from the sidebar menu, and click `New query`. This will create a new query called `new sql snippet`, which will allow us to run any SQL against our Postgres database.++Write the following and click `Run`.++```sql+create or replace function auth.user_id() returns text as $$+ select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text;+$$ language sql stable;+```++This will create a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload.++> Note: To learn more about PostgreSQL functions, check out [our deep dive video](https://www.youtube.com/watch?v=MJZCCpCYEqk).++Let's create a policy that checks whether this user is the owner of the todo.++Select `Authentication` from the Supabase sidebar menu, click `Policies`, and then `New Policy` on the `todo` table.++++From the modal, select `Create a policy from scratch` and add the following.++++This policy is calling the function we just created to get the currently logged in user's ID `auth.user_id()` and checking whether this matches the `user_id` column for the current `todo`. If it does, then it will allow the user to select it, otherwise it will continue to deny.++Click `Review` and then `Save policy`.++> Note: To learn more about RLS and policies, check out [our deep dive video](https://www.youtube.com/watch?v=Ow_Uzedfohk).++The last thing we need to do is update the `user_id` columns for our existing `todos`.++Head back to the Supabase dashboard, and select `Table editor` from the sidebar.++++Each of our `user_id` columns are set to `NULL`!++To get the ID for our Auth0 user, head over to the Auth0 dashboard, select `User Management` from the sidebar, click `Users` and select your test user.++++Copy their `user_id`.++++Update each row in Supabase.++++Now when we refresh our application, we should finally see our list of `todos`!++> Note: Check out [the repo](https://github.com/dijonmusters/supabase-auth0-example/blob/main/pages/index.js) for an example of writing new `todos` to Supabase.++## Resources++- [Auth0](https://auth0.com/) official website.+- [Auth0 blog](https://auth0.com/blog/).+- [Using Next.js and Auth0 with Supabase article](https://auth0.com/blog/using-nextjs-and-auth0-with-supabase/).+- [Auth0 community](https://community.auth0.com/).+- [Auth0 documentation](https://auth0.com/docs/).diff --git a/apps/temp-docs/docs/guides/integrations/authsignal.mdx b/apps/temp-docs/docs/guides/integrations/authsignal.mdxnew file mode 100644index 00000000000..c98930959f3--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/authsignal.mdx@@ -0,0 +1,582 @@+---+id: authsignal+title: 'Authsignal'+description: 'Add an MFA step after sign-in. Use Supabase Auth to sign in with email and password and Authsignal to initiate an Authenticator App challenge.'+---++This guide shows how to integrate [Authsignal](https://www.authsignal.com/) with [Next.js](https://nextjs.org/) and [Supabase](https://supabase.com/) in order to add an MFA step after sign-in.++The user flow is as follows:++1. The user enters their email and password to sign in+2. If the user has set up MFA, they're prompted to complete an MFA challenge (via Authenticator App) in order to complete sign-in+3. If the user has not set up MFA, they're signed in immediately and will see a button to set up MFA++The approach uses a temporary encrypted cookie to ensure that the Supabase auth cookies (`access_token` and `refresh_token`) are only set if the MFA challenge was successful. Session data is encrypted using [@hapi/iron](https://hapi.dev/family/iron).++The full code version of this example can be found [here](https://github.com/authsignal/supabase-example).++A live demo can be found [here](https://authsignal-supabase-example.vercel.app).++## How it works++1. A sign-in form posts email and password to the Next.js API route `/api/sign-in`+2. The `signIn` API route calls the Supabase client's `signInWithEmail` method and gets back a session object+3. The `signIn` API route then calls the Authsignal client's `track` method to determine if an MFA challenge is required+4. If a challenge is required, the `signIn` API route saves the session object in a temporary encrypted cookie and redirects to Authsignal+5. Once the challenge is completed, Authsignal redirects back to `/api/callback` which retrieves the session and sets the Supabase auth cookies+6. The `callback` API route then redirects to the index page which is protected with Supabase's `withPageAuth` wrapper around `getServerSideProps`++## Step 1: Configuring an Authsignal tenant++Go to the [Authsignal Portal](https://portal.authsignal.com) and create a new project and tenant.++You will also need to [enable at least one authenticator for your tenant](https://portal.authsignal.com/organisations/tenants/authenticators) - for example Authenticator Apps.++Finally, to configure the sign-in action to always challenge, go [here](https://portal.authsignal.com/actions/signIn/rules) and set the default action outcome to `CHALLENGE` and click save.++++## Step 2: Creating a Supabase project++From your [Supabase dashboard](https://app.supabase.com/), click `New project`.++Enter a `Name` for your Supabase project and enter or generate a secure `Database Password`, then click `Create new project`.++Once your project is created go to `Authentication -> Settings -> Auth Providers` and ensure `Enable Email provider` is checked and that `Confirm Email` is unchecked.++++## Step 3: Building a Next.js app++Create a new Next.js project:++```bash+npx create-next-app --typescript supabase-authsignal-example+cd supabase-authsignal-example+```++Create a `.env.local` file and enter the following values:++```+NEXT_PUBLIC_SUPABASE_URL=get-from-supabase-dashboard+NEXT_PUBLIC_SUPABASE_ANON_KEY=get-from-supabase-dashboard+AUTHSIGNAL_SECRET=get-from-authsignal-dashboard+TEMP_TOKEN_SECRET=this-is-a-secret-value-with-at-least-32-characters+```++Supabase values can be found under `Settings > API` for your project.++Authsignal values can be found under `Settings > API Keys` for your tenant.++`TEMP_TOKEN_SECRET` is used to encrypt the temporary cookie. Set it to a random 32 character length string.++Restart your Next.js development server to read in the new values from `.env.local`.++```bash+npm run dev+```++## Step 4: Installing dependencies++Install the Supabase client and Auth helpers for Next.js:++```+npm install @supabase/supabase-js @supabase/auth-helpers-nextjs+```++Install the Authsignal Node.js client:++```+npm install @authsignal/node+```++Finally install 2 packages to help encrypt and serialize session data in cookies:++```+npm install @hapi/iron cookie+npm install --save-dev @types/cookie+```++## Step 5: Initializing the Authsignal client++Add the following code to `/lib/authsignal.ts`:++```+import { Authsignal } from "@authsignal/node";++const secret = process.env.AUTHSIGNAL_SECRET;++if (!secret) {+ throw new Error("AUTHSIGNAL_SECRET is undefined");+}++const redirectUrl = "http://localhost:3000/api/callback";++export const authsignal = new Authsignal({ secret, redirectUrl });+```++The `redirectUrl` here is a Next.js API route which Authsignal will redirect back to after an MFA challenge. We'll implement this below.++## Step 6: Managing session data in cookies++Next we will add some helper functions for managing cookies:++- `setTempCookie` encrypts and serializes the Supabase session data and sets it in a temporary cookie+- `getSessionFromTempCookie` decrypts and parses this session data back from the cookie+- `setAuthCookie` sets the Supabase auth cookies (`access_token` and `refresh_token`) and clears the temporary cookie++Add the following code to `/lib/cookies.ts`:++```+import Iron from "@hapi/iron";+import { Session } from "@supabase/supabase-js";+import { parse, serialize } from "cookie";+import { NextApiRequest, NextApiResponse } from "next";++export async function setTempCookie(session: Session, res: NextApiResponse) {+ const token = await Iron.seal(session, TEMP_TOKEN_SECRET, Iron.defaults);++ const cookie = serialize(TEMP_COOKIE, token, {+ maxAge: session.expires_in,+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ path: "/",+ sameSite: "lax",+ });++ res.setHeader("Set-Cookie", cookie);+}++export async function getSessionFromTempCookie(+ req: NextApiRequest+): Promise<Session | undefined> {+ const cookie = req.headers.cookie as string;++ const cookies = parse(cookie ?? "");++ const tempCookie = cookies[TEMP_COOKIE];++ if (!tempCookie) {+ return undefined;+ }++ const session = await Iron.unseal(+ tempCookie,+ TEMP_TOKEN_SECRET,+ Iron.defaults+ );++ return session;+}++export function setAuthCookie(session: Session, res: NextApiResponse) {+ const { access_token, refresh_token, expires_in } = session;++ const authCookies = [+ { name: ACCESS_TOKEN_COOKIE, value: access_token },+ refresh_token+ ? { name: REFRESH_TOKEN_COOKIE, value: refresh_token }+ : undefined,+ ]+ .filter(isDefined)+ .map(({ name, value }) =>+ serialize(name, value, {+ maxAge: expires_in,+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ path: "/",+ sameSite: "lax",+ })+ );++ // Also clear the temp cookie+ const updatedCookies = [+ ...authCookies,+ serialize(TEMP_COOKIE, "", { maxAge: -1, path: "/" }),+ ];++ res.setHeader("Set-Cookie", updatedCookies);+}++const isDefined = <T>(value: T | undefined): value is T => !!value;++const TEMP_TOKEN_SECRET = process.env.TEMP_TOKEN_SECRET!;+const TEMP_COOKIE = "as-mfa-cookie";+const ACCESS_TOKEN_COOKIE = "sb-access-token";+const REFRESH_TOKEN_COOKIE = "sb-refresh-token";+```++## Step 7: Building the UI++We will add some form components for signing in and signing up as well as a basic home page.++Add the following code to `/pages/sign-up.tsx`:++```+import Link from "next/link";+import { useRouter } from "next/router";++export default function SignUpPage() {+ const router = useRouter();++ return (+ <main>+ <form+ onSubmit={async (e) => {+ e.preventDefault();++ const target = e.target as typeof e.target & {+ email: { value: string };+ password: { value: string };+ };++ const email = target.email.value;+ const password = target.password.value;++ await fetch("/api/sign-up", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email, password }),+ }).then((res) => res.json());++ router.push("/");+ }}+ >+ <label htmlFor="email">Email</label>+ <input id="email" type="email" name="email" required />+ <label htmlFor="password">Password</label>+ <input id="password" type="password" name="password" required />+ <button type="submit">Sign up</button>+ </form>+ <div>+ {"Already have an account? "}+ <Link href="sign-in">+ <a>Sign in</a>+ </Link>+ </div>+ </main>+ );+}+```++Then add the following code to `/pages/sign-in.tsx`:++```+import Link from "next/link";+import { useRouter } from "next/router";++export default function SignInPage() {+ const router = useRouter();++ return (+ <main>+ <form+ onSubmit={async (e) => {+ e.preventDefault();++ const target = e.target as typeof e.target & {+ email: { value: string };+ password: { value: string };+ };++ const email = target.email.value;+ const password = target.password.value;++ const { state, mfaUrl } = await fetch("/api/sign-in", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email, password }),+ }).then((res) => res.json());++ if (state === "CHALLENGE_REQUIRED") {+ window.location.href = mfaUrl;+ } else {+ router.push("/");+ }+ }}+ >+ <label htmlFor="email">Email</label>+ <input id="email" type="email" name="email" required />+ <label htmlFor="password">Password</label>+ <input id="password" type="password" name="password" required />+ <button type="submit">Sign in</button>+ </form>+ <div>+ {"Don't have an account? "}+ <Link href="sign-up">+ <a>Sign up</a>+ </Link>+ </div>+ </main>+ );+}+```++Now we will use Supabase's `withPageAuth` wrapper around `getServerSideProps` to make the home page require authentication via SSR. Replace the existing code in `/pages/index.tsx` with the following:++```+import { getUser, User, withPageAuth } from "@supabase/auth-helpers-nextjs";+import { GetServerSideProps } from "next";+import { useRouter } from "next/router";+import { authsignal } from "../lib/authsignal";++interface Props {+ user: User;+ isEnrolled: boolean;+}++export const getServerSideProps: GetServerSideProps<Props> = withPageAuth({+ redirectTo: "/sign-in",+ async getServerSideProps(ctx) {+ const { user } = await getUser(ctx);++ const { isEnrolled } = await authsignal.getUser({userId: user.id});++ return {+ props: { user, isEnrolled },+ };+ },+});++export default function HomePage({ user, isEnrolled }: Props) {+ const router = useRouter();++ return (+ <main>+ <section>+ <div> Signed in as: {user?.email}</div>+ <button+ onClick={async (e) => {+ e.preventDefault();++ const { mfaUrl } = await fetch("/api/mfa", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ isEnrolled }),+ }).then((res) => res.json());++ window.location.href = mfaUrl;+ }}+ >+ {isEnrolled ? "Manage MFA settings" : "Set up MFA"}+ </button>+ <button onClick={() => router.push("/api/sign-out")}>Sign out</button>+ </section>+ </main>+ );+}+```++Optional: To make things look a bit nicer, you can add the following to `/styles/globals.css`:++```+main {+ min-height: 100vh;+ display: flex;+ flex: 1;+ flex-direction: column;+ justify-content: center;+ align-items: center;+}++section,+form {+ display: flex;+ flex-direction: column;+ min-width: 300px;+}++button {+ cursor: pointer;+ font-weight: 500;+ line-height: 1;+ border-radius: 6px;+ border: none;+ background-color: #24b47e;+ color: #fff;+ padding: 0 15px;+ height: 40px;+ margin: 10px 0;+ transition: background-color 0.15s, color 0.15s;+}++input {+ outline: none;+ font-family: inherit;+ font-weight: 400;+ background-color: #fff;+ border-radius: 6px;+ color: #1d1d1d;+ border: 1px solid #e8e8e8;+ padding: 0 15px;+ margin: 5px 0;+ height: 40px;+}++a {+ color: #24b47e;+ cursor: pointer;+}+```++## Step 8: Adding the API routes++Now we'll replace the existing api routes in `/pages/api/` with 5 new routes:++- `/sign-in.ts`: handles signing in with Supabase and initiating the MFA challenge with Authsignal+- `/sign-up.ts`: handles signing up with Supabase+- `/sign-out.ts`: clears the Supabase auth cookies and signs the user out+- `/mfa.ts`: handles the user's attempt to set up MFA or to manage their existing MFA settings+- `/callback.ts`: handles completing the MFA challenge with Authsignal++Add the following code to `/pages/api/sign-in.ts`:++```+import { supabaseClient } from "@supabase/auth-helpers-nextjs";+import { NextApiRequest, NextApiResponse } from "next";+import { authsignal } from "../../lib/authsignal";+import { setAuthCookie, setTempCookie } from "../../lib/cookies";++export default async function signIn(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const { email, password } = req.body;++ const { data, error } = await supabaseClient.auth.api.signInWithEmail(+ email,+ password+ );++ if (error || !data?.user) {+ return res.send({ error });+ }++ const { state, url: mfaUrl } = await authsignal.track({+ action: "signIn",+ userId: data.user.id,+ });++ if (state === "CHALLENGE_REQUIRED") {+ await setTempCookie(data, res);+ } else {+ setAuthCookie(data, res);+ }++ res.send({ state, mfaUrl });+}+```++Then to handle new sign-ups add the following to `/pages/api/sign-up.ts`:++```+import { supabaseClient } from "@supabase/auth-helpers-nextjs";+import { Session } from "@supabase/supabase-js";+import { NextApiRequest, NextApiResponse } from "next";+import { setAuthCookie } from "../../lib/cookies";++export default async function signUp(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const { email, password } = req.body;++ const { data, error } = await supabaseClient.auth.api.signUpWithEmail(+ email,+ password+ );++ if (error || !isSession(data)) {+ res.send({ error });+ } else {+ setAuthCookie(data, res);+ res.send({ data });+ }+}++const isSession = (data: any): data is Session => !!data?.access_token;+```++To clear the auth cookies on sign-out add the following to `/pages/api/sign-out.ts`:++```+import { supabaseClient } from "@supabase/auth-helpers-nextjs";+import { NextApiRequest, NextApiResponse } from "next";++export default async function signOut(+ req: NextApiRequest,+ res: NextApiResponse+) {+ supabaseClient.auth.api.deleteAuthCookie(req, res, { redirectTo: "/sign-in" });+}+```++To handle the user's actions to set up MFA or manage their existing MFA settings, add the following to `/pages/api/mfa.ts`:++```+import { getUser, withApiAuth } from "@supabase/auth-helpers-nextjs";+import { NextApiRequest, NextApiResponse } from "next";+import { authsignal } from "../../lib/authsignal";++export default withApiAuth(async function mfa(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "POST") {+ return res.status(405).send({ message: "Only POST requests allowed" });+ }++ const { user } = await getUser({ req, res });++ const { isEnrolled } = req.body;++ const { url: mfaUrl } = await authsignal.track({+ action: isEnrolled ? "manageSettings" : "enroll",+ userId: user.id,+ redirectToSettings: isEnrolled,+ });++ res.send({ mfaUrl });+});+```++Because the user should be authenticated with Supabase to set up or manage MFA, we can use Supabase's `withApiAuth` wrapper to protect this route.++The `redirectToSettings` param specifies whether the user should be redirected to the MFA page settings panel after a challenge, rather than redirecting them immediately back to the application.++Finally we need a route to handle the redirect back from Authsignal after an MFA challenge. Add the following to `/pages/api/callback.ts`:++```+import { NextApiRequest, NextApiResponse } from "next";+import { authsignal } from "../../lib/authsignal";+import { getSessionFromTempCookie, setAuthCookie } from "../../lib/cookies";++export default async function callback(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const token = req.query.token as string;++ const { success } = await authsignal.validateChallenge({ token });++ if (success) {+ const session = await getSessionFromTempCookie(req);++ if (session) {+ setAuthCookie(session, res);+ }+ }++ res.redirect("/");+}+```++That's it! You should now be able to sign up a new user and set up MFA.++Then if you sign out, you'll be prompted to complete an MFA challenge when signing back in again.++## Resources++- To learn more about Authsignal take a look at the [API Documentation](https://docs.authsignal.com/).+- You can customize the look and feel of the Authsignal Prebuilt MFA page [here](https://portal.authsignal.com/organisations/tenants/customizations).diff --git a/apps/temp-docs/docs/guides/integrations/clerk.mdx b/apps/temp-docs/docs/guides/integrations/clerk.mdxnew file mode 100644index 00000000000..8e39d8011d5--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/clerk.mdx@@ -0,0 +1,184 @@+---+id: clerk+title: 'Clerk'+description: 'This guide explains how to connect your Supabase database with Clerk, a powerful authentication provider built for the modern web.'+---++This guide explains how to connect your Supabase database with [Clerk](https://clerk.dev), an authentication provider built for the modern web.++Clerk authenticates users, manages session tokens, and provides user management functionality that can be used in combination with the authorization logic available in Supabase through PostgreSQL Row Level Security (RLS) policies.++This guide assumes you have a Supabase account and database project already set up.++If you don't have a Clerk account, you can [create one now](https://dashboard.clerk.dev/sign-up).++## Step 1: Create JWT template++The first step is to create a new Clerk application from your Clerk Dashboard if you haven't done so already. You can choose whichever authentication strategy and social login providers you prefer. For more information, check out Clerk's [guide](https://docs.clerk.dev/popular-guides/setup-your-application).++After your Clerk application has been created, use the lefthand menu to navigate to the **JWT Templates** page.++Click on the button to create a new template based on Supabase.++++This will pre-populate the default claims required by Supabase. You can include additional claims or modify them as necessary. [Shortcodes](https://docs.clerk.dev/popular-guides/jwt-templates#shortcodes) are also available for adding dynamic values.++ℹ️ Note the name of the JWT template (which you can change) because this will be needed later.++++## Step 2: Sign JWT with Supabase secret++Supabase requires JWTs be signed with the HS256 signing algorithm and use their signing key. Find the JWT secret key in your Supabase project under **Settings** > **API** in the **Config** section.++++Click to reveal the JWT secret, copy it, and then paste it in the Signing key field in the Clerk JWT template.++++After the key is added, click the **Apply Changes** button to save your template.++## Step 3: Configure client++The next step is to configure your client. Supabase provides an official [JavaScript/TypeScript client library](https://github.com/supabase/supabase-js) and there are [libraries in other languages](https://supabase.com/docs/reference/javascript/installing) built by the community.++This guide will use a Next.js project with the JS client as an example, but the mechanism of setting the authentication token should be similar with other libraries and frameworks.++Assuming a Next.js application, set the following environment variables in an `.env.local` file:++```bash+NEXT_PUBLIC_CLERK_FRONTEND_API=your-frontend-api+NEXT_PUBLIC_SUPABASE_URL=your-supabase-url+NEXT_PUBLIC_SUPABASE_KEY=your-supabase-anon-key+```++**Note**: If you're using Create React App, replace the `NEXT_PUBLIC` prefix with `REACT_APP`++Your Clerk Frontend API can be found on the [API Keys](https://dashboard.clerk.dev/last-active?path=api-keys) screen.++++To get the ones needed for Supabase, navigate to the same Settings > API page as before and locate the anon public key and URL.++++**Note**: It is recommended that you enable [Row Level Security](https://supabase.com/docs/guides/auth/row-level-security) (RLS) for your database tables and configure access policies as needed.++After setting those three environment variables, you should be able to start up your application development server.++Install the JavaScript client for Supabase with:++```bash+npm install @supabase/supabase-js+```++Initialize the Supabase client by passing it the environment variables.++This can be saved to a common file, for example as `lib/supabaseClient.js`++```jsx+import { createClient } from '@supabase/supabase-js'++const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL+const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_KEY++export const supabase = createClient(supabaseUrl, supabaseKey)+export default supabase+```++## Step 4: Set up Clerk Provider++Install the latest Clerk Next.js SDK by running the following:++```bash+npm install @clerk/nextjs@next+```++**Note**: There is also a Clerk library for [React](https://github.com/clerkinc/javascript/tree/main/packages/react) and [React Native with Expo](https://github.com/clerkinc/javascript/tree/main/packages/expo).++After the package is installed, wrap your application with the `<ClerkProvider />` component.++In a Next.js application, this is typically done in `pages/_app.js`:++```jsx+import { ClerkProvider } from '@clerk/nextjs'++function MyApp({ Component, pageProps }) {+ return (+ <ClerkProvider>+ <Component {...pageProps} />+ </ClerkProvider>+ )+}++export default MyApp+```++## Step 5: Set auth token with Supabase++In order to access the custom JWT, you can use the `getToken` function returned by the Clerk `useAuth` hook and pass it the name of your template (hopefully you remembered from earlier).++**Note**: The `getToken({ template: <your-template-name> })` call is asynchronous and returns a Promise that needs to be resolved before accessing the token value. This token is short-lived for better security and should be called before every request to your Supabase backend. The caching and refreshing of the token is handled automatically by Clerk.++Call `supabase.auth.setAuth(token)` to override the JWT on the current client. The JWT will then be sent to Supabase with all subsequent network requests.++```jsx+import { useAuth } from '@clerk/nextjs'+import supabase from '../lib/supabaseClient'++export default function Home() {+ const { getToken } = useAuth()++ const fetchData = async () => {+ // TODO #1: Replace with your JWT template name+ const token = await getToken({ template: 'supabase' })++ supabase.auth.setAuth(token)++ // TODO #2: Replace with your database table name+ const { data, error } = await supabase.from('your_table').select()++ // TODO #3: Handle the response+ }++ return (+ <button type="button" onClick={fetchData}>+ Fetch data+ </button>+ )+}+```++## Access user ID in RLS policies++It is common practice to need access to the user identifier on the database level, especially when working with RLS policies in Postgres. Although Supabase provides a special function `auth.uid()` to extract the user ID from the JWT, this does not work with Clerk. The workaround is to write a custom SQL function to read the `sub` property from the JWT claims.++In the **SQL Editor** section of the Supabase dashboard, click New Query and enter the following:++```sql+create or replace function requesting_user_id()+returns text+language sql stable+as $$+ select nullif(current_setting('request.jwt.claims', true)::json->>'sub', '')::text;+$$;+```++This will create a `requesting_user_id()` function that can be used within an RLS policy.++For example, this policy would check that the user making the request is authenticated and matches the `user_id` column of a todos table.++## Access user ID in table column++If you would like the requesting user ID from the JWT to automatically populate a text type column in your database table, you can set the **Default Value** field to the previously defined `requesting_user_id()` function.++++## Resources++- [Clerk + Supabase starter repo](https://github.com/clerkinc/clerk-supabase-starter)+- [Next.js + Supabase + Clerk tutorial](https://clerk.dev/blog/nextjs-supabase-todos-with-multifactor-authentication)+- [Clerk guide for Next.js Authentication](https://docs.clerk.dev/get-started/nextjs)+- [Clerk Community Discord channel](https://discord.com/invite/b5rXHjAg7A)diff --git a/apps/temp-docs/docs/guides/integrations/dashibase.mdx b/apps/temp-docs/docs/guides/integrations/dashibase.mdxnew file mode 100644index 00000000000..dd53242782d--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/dashibase.mdx@@ -0,0 +1,99 @@+---+id: dashibase+title: 'Dashibase'+description: 'Create an internal CRUD dashboard with Supabase and Dashibase in 15 mins.'+---++Are you tired of building admin panels? [Dashibase](https://dashibase.com/) is a super fast way to build internal CRUD dashboards with a Notion-like UI.++This guide walks you through how to build a customer admin panel using Supabase on the backend and Dashibase on the front so that you and your team can easily find and update customer information.++## Quick explanation++Just so we are on the same page, here are some of the terms we use:++- **Data source:** This is the data that powers your dashboard (i.e. your Supabase database).+- **Dashboard:** This is the friendly interface that you build on top of your Supabase database using Dashibase.+- **Page:** Each dashboard can have multiple pages. Each page can have multiple blocks of text or tables.++Now that is out of the way, let's build our customer admin panel.++(Start your stopwatch!)++## Step 1. Connect Supabase to Dashibase++First, in Dashibase, go to “Data Sources” via the left sidebar and click on “Connect data source” in the upper-right corner.++Note: We do not download or store any of your database data.++++Enter your database credentials, which you can find in Supabase under Settings > Database > Connection info. For additional security, you can also download your SSL certificate and upload it to Dashibase.++++## Step 2. Set up your data access policy++Once you have connected your database, you can also control what your team can see and edit in your database via Dashibase. There are usually certain data that you don’t want others to edit or even see (e.g. address, email, identification number).++Note: If you prefer to restrict access to your database _before_ you connect to Dashibase for security reasons, you can [create a restricted user](https://aws.amazon.com/blogs/database/managing-postgresql-users-and-roles/) via [Supabase's SQL Editor](https://supabase.com/docs/guides/database#the-sql-editor). The slight advantage of doing this in Dashibase is that there is a GUI, which makes it easier to set up the access control (but we understand some developers might find it more secure to restrict the access themselves).++++You can even control which columns within a table that others can see and edit. In the example below, for the `tags` table, the `name` column can be read and updated, the `created_at` column can be read, and the `id` column cannot even be read.++++Once you are happy with the data access control, you can decide who in your organization can edit this data source (usually other developers) or use this data source to create dashboards.++++## Step 3. Build your dashboard++To create a dashboard, go to “Dashboards” via the left sidebar in Dashibase and click on “Create dashboard” in the upper-right corner.++Here’s where the fun begins. There are many ways to build your dashboards in Dashibase using features such as markdown formatting and slash command.++You will see some automatically-generated content in your dashboard so that you can set up your dashboard more quickly. For this example, let's clear them out and start from scratch.++++Using our Notion-like UI, you can quickly build out your dashboard through typing. For example, you can type '/table' to add a table from your database to your dashboard. No more dragging components across your screen and dropping them on a blank canvas repeatedly.++++If you have set up [foreign keys in your Supabase database](https://supabase.com/docs/guides/database/tables#joining-tables-with-foreign-keys), you can easily show data from multiple tables on the table in your Dashibase dashboard. Simply click on the "Columns" button beside the "Filter" button and select the columns you want to show or hide. For this example, we want to show the customers' country and plan price, which are in separate `countries` and `plans` tables.++++For all the tables in your dashboard, you can rename the column headers, add filter and sort, adjust the column width, and more.++You can also add text to provide context or instructions for the rest of your team as they are using your dashboard. This saves you the trouble of having your dashboard and documentation in separate places.++++Most importantly, we automatically generate a single-item view for each of the items on your table so that you do not have to manually create it yourself. You can easily edit or rearrange the blocks just like in Notion.++++## Step 4. Share your dashboard with your team++Finally, save and share the dashboard with your team. There are two levels of access:++- Edit dashboard: Edit the text blocks, edit the tables, etc.+- Use dashboard: View and update the data via the dashboard++Click on the “Share” button in the upper-right corner of your dashboard to share access:++++Now your team can use this customer admin panel to find and update customer information easily!++P.S. How long did we take? :)++## Resources++- [Dashibase website](https://dashibase.com/)+- [Dashibase open-source repo](https://github.com/dashibase)+- [Dashibase Twitter](https://twitter.com/dashibase)+- [Dashibase Discord](https://discord.gg/crhDFYvbbq)diff --git a/apps/temp-docs/docs/guides/integrations/dhiwise.mdx b/apps/temp-docs/docs/guides/integrations/dhiwise.mdxnew file mode 100644index 00000000000..15b4110ed1e--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/dhiwise.mdx@@ -0,0 +1,175 @@+---+id: dhiwise+title: 'DhiWise'+description: 'Get started with Supabase and DhiWise. Convert your Figma designs into Flutter apps, store data, and authenticate your users'+---+import select from "/img/guides/integrations/dhiwise/select.png"+import create from "/img/guides/integrations/dhiwise/create.png"++This guide explains how to connect Supabase backend to DhiWise Flutter application quickly.++[DhiWise](https://www.dhiwise.com/) is a Developer tool to convert Figma designs into React and Flutter applications. It lets you quickly integrate Databases and APIs into your React and Flutter Apps.++If you don't have a DhiWise account, create one [here](https://app.dhiwise.com).++DhiWise supports easy Supabase Integration in just five steps.++Let's get started!++## Step 1: SignIn to Supabase++Go to [Supabase](https://supabase.com/), Click `Sign In`, and create a new account by authenticating with **GitHub**. If you already have an account, you will be logged in.++## Step 2: Create a new project in Supabase++Click on `New project` from the Dashboard and select an organization. If you don't have an organization, create one using `+ New organization.`++- Give your Supabase project a `name.`+- Enter a secure `Database Password.`+- Choose the `region` where your app's backend is hosted.+- Click `Create new project.`++++## Step 3: Find the API key and URL++Once your project is created, you can access the API Key and URL string, Or if you already have an account go to your `organization-> app-> settings-> API`.++++## Step 4: Integrations++There are two ways you can integrate Supabase into your DhiWise Flutter applications.++### Authentication++You can integrate `Supabase Email/Password SignUp` or `Supabase Email/Password SignIn` on your components.++- Open the screen of your flutter application+- Go to the component on which you want to add authentication+- on the `onClick` method - select `authentication`+- From the list, If you want SignUp - select `SignUp with Email/Password`; otherwise, select `SignIn with Email/Password` from Supabase Auth section++++And that's it. Supabase authentication will be added to the selected component.++After downloading the application source code,+1. Add Supabase URL and Supabase public key inside ***lib/core/utils/initial_bindings*** file.+2. For additional details, refer ***https://supabase.com/docs/guides/with-flutter***++### Working with Data++When you first integrate Supabase in your DhiWise Flutter application, You will be asked to add [Supabase auth key and URL](##step-3-find-the-api-key-and-url). When you add them, all the tables available in your Supabase project will be synced in DhiWise. You can integrate Select and Create queries on your Flutter screen for a particular table in DhiWise.++<h3> Select records </h3>++#### **Step 1:**+Select the screen from the screen list where you want to integrate Supabase.++#### **Step 2:**+Next, go to the view where you want to add Integration, and from the suggestion box for the `onClick` property, choose `Supabase integration,` which will take you to the Integration screen. Where you will be asked to `Enter function name.` Enter the name of your function and click `Submit.`++#### **Step 3:**+After submitting the function name, you will be asked to select a type of Supabase integration. To retrieve data from Supabase, choose `select.`++#### **Step 4:**+Next, select the table from which you want to fetch records from the listed Tables.++#### **Step 5:**+Select the type of integration++| Type | Description |+| --- | --- |+| **Single** | Used to fetch a single record from the database. |+| **Multiple** | Used to fetch multiple records from the database. |++:::info+For Multiple types, you need to set `data limit,` `order by, and `order.`+:::++#### **Step 6:**+You will be redirected to the API Integration screen, where you can set request and response.++For request binding, the below types are supported. Also, Select the operator for comparison before moving forward.++| Type | Description |+| --- | --- |+| **View** | Select any component from your screen. |+| **Constant** | Select a constant you've created in your app. |+| **Get from preference** | Select the key you want to fetch from preference. |+| **Navigation argument** | Select data that's been passed from one screen to another. |++For response binding, the below types are supported.++| Type | Description |+| --- | --- |+| **View** | Select any component from the screen. |+| **Save to preference** | Storing the data to preference. |++#### **Select 7:**+`Handle action` - Select the action you wish to take once the Supabase call has either been accepted successfully or refused due to an error.++Available action for On success and On error are,++1. [Show Alert](https://docs.dhiwise.com/docs/flutter/show-alert)+2. [Navigation](https://docs.dhiwise.com/docs/flutter/navigation)++#### **Step 8:**+Finally, you have added Supabase to your application to fetch records on your screen!++:::tip Example+Suppose you want to fetch records from Supabase and populate the item list on your screen. You can integrate Supabase as discussed above and bind the response with your list view.+:::++<h3> Create records </h3>++#### **Step 1:**+Choose the screen you wish to integrate Supabase for from the list of screens.++#### **Step 2:**+Next, switch to the component you want to add Integration, and on the `onClick` property, choose `Supabase integration,` which will take you to its integration screen, where you will be asked to **Enter function name**, which will be used in generated code. Enter the name for it and click `Submit`++#### **Step 3:**+After submitting the function name, you will be asked to select a type of Supabase integration. For example, to create a record in Supabase, choose `Create.`++#### **Step 4:**+Next, select the table where you want to create a record from the listed Tables.++#### **Step 5:**+If you want to create a Single record, Select **Select**. Otherwise, **Multiple**.++#### **Step 6:**+Now, you will be redirected to the API Integration screen, where you can set request and response.++For request binding, the below types are supported.++| Type | Description |+| --- | --- |+| **View** | Select any component from the screen |+| **Constant** | Select a constant you've created in your app.|+| **Get from preference** | Select the key you want to fetch from preference. |+| **Navigation argument** | Select data that's been passed from one screen to another. |++For response binding, the below types are supported.++| Type | Description |+| --- | --- |+| **View** | Select any component from the screen |+| **Save to preference** | Storing the data to preference. |++#### **Select 7:**+`Handle action` - Select the action you wish to take once the Supabase call has either been accepted successfully or refused due to an error.++Available action for On success and On error are,++1. [Show Alert](https://docs.dhiwise.com/docs/flutter/show-alert)+2. [Navigation](https://docs.dhiwise.com/docs/flutter/navigation)++#### **Step 9:**+Finally, you have added Supabase to your application to create records from your screen data!++## Resources++- [DhiWise Official Website](https://dhiwise.com)+- [DhiWise Documentation](https://docs.dhiwise.com)\ No newline at end of filediff --git a/apps/temp-docs/docs/guides/integrations/directus.mdx b/apps/temp-docs/docs/guides/integrations/directus.mdxnew file mode 100644index 00000000000..ae5c51da936--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/directus.mdx@@ -0,0 +1,131 @@+---+id: directus+title: 'Directus'+description: 'In this guide, we will show you how to create a Supabase project, install the Directus platform locally and configure the two to connect.'+---++In this guide, we will demonstrate how to create a new Supabase project, install a fresh instance of the Directus platform, then configure the two to work together seamlessly. If you're unfamiliar with either of these systems, don't worry! We'll start off with an overview of each platform and explain how they complement each other, noting any overlap in capabilities.++## Introduction++++[Supabase](https://supabase.com/) is an open-source Firebase alternative that provides a PostgreSQL database, storage, authentication, and a dynamic REST API based on your schema. While it is possible to self-host Supabase on your own infrastructure, this article will focus on Supabase Cloud's Free tier, which is the fastest and easiest way to get started.++++[Directus](https://directus.io/) is an open-source data platform that layers on top of any SQL database, providing a powerful suite of tools. The Directus Engine provides dynamic REST and GraphQL APIs based on your schema, hooks and automation, authentication and access control, and file transformations. Directus Studio enables engineers and non-technical users alike to browse, manage, and visualize database content through a no-code app.++---++Supabase is a suite of open-source tools making Postgres databases, file storage, authentication, and edge functions more accessible to developers of all skill levels. Directus is also developer tooling and additionally provides a Data Studio that is safe and intuitive enough for anyone, including non-technical users, to use. This is the crucial bit that gives the two platforms such a strong “network effect.”++When these two systems are brought together, you get a scalable datastore, limitless connectivity options, and a no-code app that allows your technical and business teams to collaborate together efficiently.++The two platforms share an overlap of capabilities that deepens their integration and offers developers the freedom of choice across a broader spectrum of connectivity. Key areas of intersection include:++The ability to generate _powerful_ APIs dynamically to connect data+User management and fine-grained access control+Digital asset storage and management.++More importantly, Directus and Supabase share a common vision for your data, making them quite symbiotic. Both solutions are completely open-source, with self-hosted and cloud deployment options available. They are unopinionated in their approach, with vendor-agnostic data storage, and they both focus on providing a polished developer experience along with comprehensive documentation.++By linking the Supabase database with your Directus Project, _you get a superset of data tools._ You'll benefit from Supabase's Postgres database and its _dev-centric_ admin app with the raw power to run SQL queries, **_as well as_** the Directus no-code app, which enables intuitive permissions-based data access for the whole team.++Let's dive into how we actually set up and link these two platforms to create a modern data stack powerhouse.++## Create a Supabase Project++As mentioned, while you can [deploy Supabase locally](https://supabase.com/docs/guides/local-development). For the purpose of this guide, we'll use Supabase Cloud:++1. Create a **Supabase** account by signing in with GitHub.+2. Give your organization a name (this can be changed later).+3. Click **New Project** and select your organization.+4. Follow the prompts, setting a project Name, Database Password, Region, and Pricing Plan, then click **Create New Project**.+5. After your project has been provisioned, navigate to **Settings > Database** in the sidebar.+6. Scroll down to **Connection Info** and take note of your database's **Host**, **Database Name**, **Port**, **User**, and **Password**. You will need to enter this during your Directus project setup.++## Optional: Add PostGIS to Support Geometry and Mapping++To take full advantage of the built-in geometry and mapping features Directus offers, we recommend enabling Geometric Data Support. To add PostGIS, follow these steps:++++1. From the sidebar, navigate to **Database > Extensions**.+2. Use the search bar to look up `PostGIS`.+3. Toggle the PostGIS option to enable it.++## Set up Directus++At the time of writing this article, [Directus Cloud](https://directus.cloud/) does not yet support hybrid deployments for connecting an external database. So, we'll be deploying a self-hosted instance to connect with Supabase. To install a self-hosted instance of Directus that's connected to our Supabase project, follow these steps:++1. Run the following command in your terminal:++```bash+npm init directus-project example-project+```++2. Using the up/down arrow keys, select `Postgres` from the list:++```bash+? Choose your database client Postgres+```++3. Next, you will be prompted to input database credentials. Add in the Supabase Database Connection Info noted above as follows:++- **Database Host** – The IP address for your database.+- **Port** – Port number your database is running on.+- **Database Name** – Name of your existing database.+- **Database User** – Name of existing user in database.+- **Database Password** – Password to enter database.+- **Enable SSL** – Select Y for yes or N for no.+- **Root** – The root name.++4. Now, simply set an email and password for your first Directus admin account. To be clear, this is Directus-specific, and is unrelated to your database user:++```bash+Create your first admin user:+? Email: [email protected]+? Password: ********+```++Once this is complete, you should see details about your new project:++```bash+Your project has been created at <file-path>/example-project.+The configuration can be found in <file-path>/example-project/.env+```++5. Lastly, navigate to your new project folder (in this case `example-project`) and start the platform:++```bash+cd example-project+npx directus start+```++**Please note:** To prevent public accessibility when using the supabase-js library,turn on row level security (RLS) on all these tables inside of the Supabase Dashboard. By default when RLS is turned on these tables cannot be read from or written to with the supabase-js library.++That's it! Your project is now up and running locally. You can access the Directus Studio in the browser via the URL displayed, and log in with the Directus admin credentials you entered above:++```bash+✨ Server started at http://localhost:8055+```++In a matter of minutes, we've created a flexible data backend, with access to an intuitive no-code app for managing and visualizing data along with a robust connectivity toolkit. This modern data stack is flexible and scalable enough to power any data-driven project… all you need to do is build the frontend!++## Next Steps++From here, the sky's the limit on what you can build. You'll probably want to invite some new collaborators to your project and start architecting your data model.++Below are some additional resources to dive in and start exploring these two platforms:++**Directus**++- See the [Directus guides](https://directus.io/guides/).+- Join the Directus community on [Discord](https://directus.chat/).+- Check out the source code on the official [Directus GitHub Repo](https://github.com/directus/directus).++**Supabase**++- Explore the [Supabase documentation](https://supabase.com/docs)+- Join the Supabase community on [Discord](https://discord.supabase.com/)diff --git a/apps/temp-docs/docs/guides/integrations/draftbit.mdx b/apps/temp-docs/docs/guides/integrations/draftbit.mdxnew file mode 100644index 00000000000..56e5eabd09a--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/draftbit.mdx@@ -0,0 +1,231 @@+---+id: draftbit+title: 'Draftbit'+description: 'Connect your Supabase postgres database to your Low-code mobile app.'+---++This guide explains how to connect a Supabase back-end to a Draftbit front-end and then configure all CRUD operations necessary to build a simple mobile app.++[Draftbit](https://draftb.it/3Fkbask) is a "pro-code" low-code mobile app building platform. Draftbit exports React Native source code that is 100% run on open-source languages and libraries.++Draftbit is back-end agnostic and connects to Supabase via REST API.++> Note: For the demonstration purpose of this guide, we are using a pre-populated database in Supabase. We are calling `Groceries`. To follow along, rename it any way you prefer.++++If you don’t have a Draftbit account, create one [here](https://draftb.it/3Fkbask). Once you’ve got your account set up, Create a New App. You can select `Start From a Blank App` for this demo and proceed to the Builder interface.++## Step 1: Get the RESTful endpoint and Project API key++To connect the REST API in the Draftbit app, the following fields are required:++- Base URL of the REST API, which is in the format: `https://<your-domain>.supabase.co/rest/v1` where the `<your-domain` is a unique domain name generated by Supabase.+- The `supabase-key` is the secret key.++You can find these unique values in the API settings of your Supabase account.++- Click the Settings button from the top menu bar.+- In Settings, select **API**.+- In the **Project URL** section, select and copy the URL. It is the Base URL of your Supabase REST API. It will be required to make a connection to the Draftbit app.+- Also, under `Project API keys`, select and copy the API key under `anon`. It is required for every request made to the Supabase database.++++## Step 2: Save Supabase API key as Authorization Header in Draftbit++To authorize your Draftbit app with Supabse, in the builder interface:++- Open the **Settings** tab from the top menu bar.+- In Project Settings, navigate to App Variables.+- Enter a name to access the API Key such as `Authorization_Header`. When making the service connection in the next section, it will be passed as the value for the header `Authorization`.+- The value of this key requires you to enter an authorization token that starts with syntax `Bearer <your-api-key>` (the space between `Bearer` and `<your-api-key>` is required). Click **Add** after adding the value.+- Enter another key name to access the API Key such as `Api_Key_Header`. When making the service connection in the next section, it will be passed as the header `apiKey` value.+- The value of this key requires you to enter an authorization token that starts with syntax is `<your-api-key>`. Click **Add** after adding the value.+- Click **Save** to save these keys and close the modal.++++## Step 3: Add Supabase RESTful endpoint in Draftbit++In your Draftbit builder interface:++- Open the **API & Cloud Services** modal from the top menu bar.+- From the **Connect a service** menu, click on **Rest API**.++- In Step 1: Enter a name for your REST API. Then, paste your `Base URL` (from the first section) into the Base URL field.+- In Step 2: Under **Key** add `Authorization` and `apikey`. Then, under **Value**, select the global variables (from the previous section) to add the actual values for both keys.+- Click Save.++++## Making API requests with Supabase & Draftbit++### GET request to Fetch all records++In this section, let's populate a Fetch component with all the data from a simple Supabase and then display the data fetched from the Supabase data table in a List component.++For reference, here is a how the Components tree looks like for this screen:++++The next step is to create an endpoint. Let's try fetching all the data using a `GET` HTTP request. Select the Supabase service in the **API & Cloud Services** modal, and then:++- Click **Add endpoint**.+- In Step 1: enter the name for the endpoint. Make sure the **Method** select is `GET`.+- In Step 2: add the base name path: `/groceries/select=*`, where `groceries` is the table name in Supabase.+- In Step 4: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase.+- Click Save.++++In the Builder, on the app screen:++- Select the Fetch component in the Components tree and go to the [Data tab from Properties Panel](doc:introduction-to-the-builder#properties-panel).+- For **Service**, select the name of the Supabase Service.+- For **Endpoint**, select the endpoint you want to fetch the data from.+- Select the List component in the Components and go to the [Data tab from Properties Panel](doc:introduction-to-the-builder#properties-panel). In Data, select `Top-Level Response` from the dropdown menu.+- Then, select the Text component in the Components and then go to the Data tab from the Properties Panel.+- Add a `{{varName}}` value (inside the curly braces) to represent a column field from the Supabase. For example, add `{{title}}` to represent the column name from the Supabase Base.+- Under **Variables**, you will see the variable name defined in the previous step. From the dropdown menu, select the appropriate field that represents the data field.++++### GET request to fetch single row++Open the **API & Cloud services** modal from the top menu, select the Supabase service, and then:++- Click **Add endpoint**.+- In Step 1: enter a name for the endpoint.+- In Step 2: add the `/groceries/column-name=eq.{{column-name}}` variable. Then, add a Test value for the `{{column-name}}`. For example, it can be the `title` or the `id`.+- In Step 4: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase.+- Click Save.++++On app screen:++- Select the Fetch component in the Components tree and go to the Data tab from Properties Panel+- For **Service**, select the name of the Supabase Service.+- For **endpoint**, select the endpoint you want to fetch the data from.+- Set the value for the `id` in the Configuration > URL Structure section to Navigation > id.+- Select the List component in the Components and go to the Data tab from Properties Panel. In Data, select `Top-Level Response` from the dropdown menu.+- Then, select the Text component in the Components and then go to the Data tab from the Properties Panel.+- Add a `{{varName}}` value (inside the curly braces) to represent the column field from the Supabase. For example, add `{{title}}` to represent the field and value from the Supabase data table.+- Under **Variables**, you will see the variable name defined in the previous step. From the dropdown menu, select the appropriate field that represents the data field.++++### POST request to submit a new row++Submitting new Data from the Draftbit app to Supabase's REST API requires the request to be sent using the HTTP `POST` method.++For this section, you need to use at least one component that accepts user input and has a Field Name prop to POST data using Supabase REST API.++You can use one of the following components in Draftbit:++- Text Input+- Text Area/Text Field+- Checkbox+- Slider+- Radio Button Group+- Radio Button++In addition, you need a Touchable component like a Button to attach the POST action. After you have created these components, we will create the `POST` endpoint:++- Click **Add endpoint**.+- In Step 1: enter a name for the endpoint and select the Method to `POST`.+- In Step 2: enter the base name as path: `/groceries`.+- In Step 3: add a valid Body structure to submit a POST request. Add one or many `{{variable}}` for test values. Click Body Preview to validate the structure of the Body in the request. For the example, let's create a variable called `{{inputValue}}`.+- In Step 4: to see the new row added to the Supabase data table as JSON response inside the Builder, you have to pass a new header called `Prefer` with its value as `return=representation`.+- In Step 5: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase and click Save.++++Once you follow the above steps, you should get a 200 OK response with exactly the new record as a JSON you have entered for your schema.++An example of how Body in a request will look like:++```json+{+ "title": {{inputValue}}+}+```++Where `title` is the column name in your Supabase database table.++In Draftbit, using a Touchable or a Button component, you can trigger the action **API Request** to submit the data to the endpoint.++Now, there is a working `POST` request in Draftbit. Map its response to the components on your screen in Draftbit.++First, for each input component, make sure you have set the Field Names (found in the Configs tab, second from the left) to unique values. For example, in the screen below, there is one TextInput field component with the value of the `Field Name` prop of `textInputValue`.++++Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`.++In the API request action:++- In **Service**, select the name to Supabase API Service.+- In **Endpoint**, select the name of the Endpoint.+- Then add the configuration for the body request to be sent by selecting the values for `{{inputValue}}`.++++After completing the above steps, you can trigger the API request to submit new data to the Supabase database.++### PATCH request to Update a new record++Updating an existing record from the Draftbit app to Supabase's REST API requires the request to be sent using the HTTP `PATCH` method.++After you have created your screen components in the Draftbit builder, open the Supabase service and make the `PATCH` endpoint:++- Click **Add endpoint**.+- In Step 1: enter a name for the endpoint and select the Method to `PATCH`.+- In Step 2: enter the base name as path: `/groceries?id=eq.{{id}}`, where `id` is the value of an existing record in the database.+- In Step 3: add a valid Body structure to submit a PATCH request. Add one or many `{{variable}}` for test values depending on the structure of your app. Click Body Preview to validate the structure of the Body in the request. For the example, let's create a variable called `{{inputValue}}`.+- In Step 5: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase and click Save.++++Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`.++In the API request action:++- In **Service**, select the name to Supabase API Service.+- In **Endpoint**, select the name of the Endpoint.+- Then add the configuration for the query param, and the body request to be sent by selecting the values for `{{inputValue}}`.++++After completing the above steps, you can trigger the API request to update existing data in the Supabase database.++### DELETE request to remove an existing record++The `DELETE` request is to the Supabase with an item's `column-name` to remove that particular record from the table. You can use a [filter from Supabase](https://supabase.io/docs/reference/javascript/using-filters) to filter the value of a specific `column-name`.++After you have created your screen components in the Draftbit builder, open the Supabase service and create the `DELETE` endpoint:++- Click **Add endpoint**.+- In Step 1: enter a name for the endpoint and select the Method to `DELETE`.+- In Step 2: add `/groceries/columnName=eq.{{columnName}}`. Then, add a Test value for the `{{columnName}}`. For example, the `{{columnName}}` here can be `id` of the record.+- In Step 4: click the **Test** button next to the Endpoint input to verify the response from the Supabase.+- Click Save.++++Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`.++In the API Request action:++- In **Service**, select the name to Supabase API Service.+- In **Endpoint**, select the name of the Endpoint.+- Then, add the configuration for the query request to be sent by selecting a value. For example, in this case it will be the `id` of the record coming from the Navigation parameter.++++## Resources++- [Draftbit](https://draftb.it/3Fkbask) official website.+- [Draftbit Community](https://community.draftbit.com/home).+- [Draftbit](https://docs.draftbit.com/) documentation.diff --git a/apps/temp-docs/docs/guides/integrations/fezto.mdx b/apps/temp-docs/docs/guides/integrations/fezto.mdxnew file mode 100644index 00000000000..c46cc6a4d66--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/fezto.mdx@@ -0,0 +1,27 @@+---+id: fezto+title: 'Frontend Zero to One'+description: 'Create an app automatically from your Supabase Postgres using OpenAPI'+---++[Frontend Zero to One is](https://www.fezto.xyz) is a service which creates an app for your Supabase Postgres database on-the-fly without any drag and drop, using the OpenAPI spec provided by PostgREST.++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/GOC6a0_AlgI"+ frameBorder="0"+ allow="accelerometer; encrypted-media; gyroscope; picture-in-picture"+ allowfullscreen+ ></iframe>+</div>++# Setup++In the [Supabase control panel](https://app.supabase.com/), open your project and click the Settings cog icon, and then "API".+You will need:++1. From the Project URL copy the project ID from https://your-project-id.supabase.co+2. From the "Project API keys" section copy the "anon" "public" API Key into the++Paste both into the [FEZTO Supabase setup page](https://www.fezto.xyz/#/supabase) and click Launch.+You can now share and bookmark the browser URL which includes the projectID and anon key with others to launch the same app.diff --git a/apps/temp-docs/docs/guides/integrations/integrations.mdx b/apps/temp-docs/docs/guides/integrations/integrations.mdxnew file mode 100644index 00000000000..9fdf5c6fa2d--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/integrations.mdx@@ -0,0 +1,34 @@+---+id: integrations+title: 'Supabase Marketplace'+description: 'Integrations and Partners'+---++The Supabase Marketplace brings together all the tools you need to extend your Supabase project. This includes:++- [Experts](https://supabase.com/partners/experts) - partners to help you build and support your Supabase project.+- [Integrations](https://supabase.com/partners/integrations) - extend your projects with external Auth, Caching, Hosting, and Low-code tools.++## Build an integration++Supabase provides several integration points:++- The [Postgres connection](/docs/guides/database/connecting-to-postgres). Anything that works with Postgres also works with Supabase projects.+- The [Project REST API](/docs/guides/api#rest-api) & client libraries.+- The [Project GraphQL API](/docs/guides/api#graphql-api).+- The [Platform API](/docs/reference/api).++## List your integration++[Apply to the Partners program](https://supabase.com/partners/integrations#become-a-partner) to list your integration in the Partners marketplace and in the Supabase docs.++Integrations are assessed on the following criteria:++- **Business viability**+ While we welcome everyone to built an integration, we only list companies that are deemed to be long-term viable. This includes an official business registration and bank account, meaningful revenue, or Venture Capital backing. We require this criteria to ensure the health of the marketplace.+- **Compliance**+ Integrations should not infringe on the Supabase brand/trademark. In short, you cannot use "Supabase" in the name. As the listing appears on the Supabase domain, we don't want to mislead developers into thinking that an integration is an official product.+- **Service Level Agreements**+ All listings are required to have their own Terms and Conditions, Privacy Policy, and Acceptable Use Policy, and the company must have resources to meet their SLAs.+- **Maintainability**+ All integrations are required to be maintained and functional with Supabase, and the company may be assessed on your ability to remain functional over a long time horizon.diff --git a/apps/temp-docs/docs/guides/integrations/keyri.mdx b/apps/temp-docs/docs/guides/integrations/keyri.mdxnew file mode 100644index 00000000000..936db47bad8--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/keyri.mdx@@ -0,0 +1,149 @@++id: keyri+title: 'Keyri'+description: 'QR authentication for an easy and flexible biometric solution across all platforms.'+---++Keyri can be used to incorporate sign-in-with-QR functionality into your Supabase app, allowing users to scan a QR code on your web app with your mobile app and be instantly logged into the web app without having to input any credentials.++Configuration is split into Web and Mobile components. On web, the Keyri QR Widget needs to be installed along with an event listener, and in your mobile app, install the Keyri SDK and pass into it the user's refresh token when sign-in-with-QR is initiated. When the refresh token lands in your web app, it's passed into Supabase's `setSession()` method.++# Sign up for Keyri++First make a free account on the Keyri dashboard (<https://app.keyri.com>). On Add Your Application, set a name and input the domain on which your app will eventually be deployed. You can create multiple application in Keyri to account for your development, staging, and production environments++++Note your application key from the Keys and Credentials section - this will be used in the Mobile portion of the implementation++++# Web++[](http://www.youtube.com/watch?v=jrjrcpc2PFQ "Supabase & Keyri | Web Integration Overview")++For your web app, first download KeyriQR.html (available [here](https://raw.githubusercontent.com/Keyri-Co/library-keyri-connect/main/KeyriQR.html)) and save it to a public directory.++Next, embed KeyriQR.html in your login page as an iFrame within the desired div. This serves as the widget that displays the dynamic QR code and connects with the Keyri API.++```html+<div>+ <iframe+ title='KeyriQR'+ src='/KeyriQR.html'+ id='qr-frame'+ height='300'+ width='300'+ scrolling='no'+ style={{ border: 'solid 5px white' }}+ ></iframe>+</div>+```++Next, for the same login view, set up an event listener to pick up the session token that the iFrame emits when the QR code is scanned by your app.++```javascript+useEffect(() => {+ window.addEventListener('message', async (evt) => {+ if (evt.data.keyri && evt.data.data && document.location.origin == evt.origin) {+ const { data } = evt;+ if (!data.error) {+ let refresh_token = JSON.parse(data.data).refreshToken;+ await handleQrLogin(refresh_token);+ } else if (data.error) {+ console.log(`Keyri error: ${data.message}`);+ }+ }+});+```++That's it!++# Mobile++[](http://www.youtube.com/watch?v=oGMsSKyh6tc "Supabase & Keyri | Mobile Integration Overview")++### Install Flutter++First, install the Flutter SDK, found at flutter.dev++Make sure to add Flutter to your PATH, for example: ++```shell+export PATH="$PATH:`pwd`/flutter/bin"+```++### Apple - initial setup++Download the latest version of Xcode from the Mac App Store. Make sure the Xcode provided simulator is using a 64-bit device (iPhone 5s or later). You can check the device by viewing the settings in the simulator’s **Hardware > Device** or **File > Open Simulator** menus.++### Android - initial setup++Download the latest version of [Android Studio](https://developer.android.com/studio). Install Android SDK and needed emulator(s).++### Create Project++Run this command in your terminal/shell at the desired location for your new project++```shell+$ flutter create my_app+```++You can then CD into the new directory, and run the test app with ++```shell+flutter run+```++This is a good test - if things are configured correctly so far you should see the default Flutter test app deployed.++### Add dependencies (Keyri and Supabase)++Open your Pubspec.yaml file, which should be at the top level directory in your new project++Add Keyri and Supabase under **dependencies**++++One can now access Supabase and Keyri sdks in their Flutter code++### Utilize the two together++1. Make a request to Supabase to authenticate the user++2. Parse the response to extract the token++3. Authenticate using Keyri+ 1. Below, we show how to utilize the EasyKeyriAuth function, which takes the user through scanning the code, creating the session, displaying the confirmation screen, and finalizing the payload transmission+ - Note - you can find your App Key in the Keyri Developer Portal++ 2. Alternatively, intermediate functions in the Keyri SDK, discussed in the mobile docs, can provide control over displaying a custom QR Scanner and/or Confirmation screen++```kotlin+// Sign in user with email and password+// Alternatively one can utilize the Supabase API to accomplish the same thing+final response = await client.auth.signIn(email: 'email', password: 'password');++if (response.error != null) {+ // Error+ print('Error: ${response.error?.message}');+} else {+ // Success+ final session = response.data;++ // This is the payload that needs to be send through Keyri+ final refreshToken = session.refreshToken++ // EasyKeyriAuth guides the user through scanning and parsing the QR, confirming the session, and configuring the payload+ // One can also use the initiateQRSession method to use the Keyri Scanner with a custom Confirmation screen+ // Or the ProcessLink method if you have your own scanner or are using deep linking+ await keyri+ .easyKeyriAuth([App Key],+ '{"refreshToken":"$refreshToken"}', [email])+ .then((authResult) => _onAuthResult(authResult))+ .catchError((error, stackTrace) => _onError(error));++}+++```diff --git a/apps/temp-docs/docs/guides/integrations/pgmustard.mdx b/apps/temp-docs/docs/guides/integrations/pgmustard.mdxnew file mode 100644index 00000000000..a0470a79293--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/pgmustard.mdx@@ -0,0 +1,66 @@+---+id: pgmustard+title: 'pgMustard'+description: 'Troubleshoot slow queries on Supabase with pgMustard, a visualization tool that also gives advice.'+---++This guide explains how to troubleshoot slow queries on Supabase using `explain` and pgMustard.++[pgMustard](https://pgmustard.com/) is a visualization tool for [`explain analyze`](https://www.postgresql.org/docs/current/using-explain.html#USING-EXPLAIN-ANALYZE) that also gives performance tips.++## Step 1: Get the query plan from Supabase++Use `explain analyze` to get a query plan from Postgres. This will run the query behind the scenes, so be careful with data modification queries.++pgMustard requires plans to be in json format, and the buffers, verbose, and settings parameters allow it to give better tips.++So a good prefix for your query would be:++```jsx+explain (analyze, format json, buffers, verbose, settings)+```++Run the query, and copy the output.++++If you’re using the Supabase SQL Editor, this is easily copied from the cell titled `QUERY PLAN`, as seen above.++If you have any trouble, check out pgMustard’s guide for [getting a query plan](https://www.pgmustard.com/getting-a-query-plan).++## Step 2: Paste the query plan into pgMustard++Paste the json output into pgMustard and press Submit.++++## Step 3: Look through the top tips and slowest operations++Review the top tips in pgMustard. These are scored on a scale of 0 to 5 stars, based on how much time-saving potential they have (5 stars meaning lots of potential).++++Click one of the tips, or one of the operations, to see more information.++++## Step 4: Consider your options++If you get some promising suggestions, you may wish to explore them.++If you don’t get any tips, your query might be quite fast for the amount of work it’s doing.++For the example we saw in Step 3, let's try adding an index on the `customer_name` field in Supabase.++++Going through Steps 1-3 again, we now get an efficient index scan, that will scale nicely as our data grows.++++We could look into why Postgres isn’t choosing to do an index-only scan here, but pgMustard is letting us know that it doesn’t think we’ll gain much by doing so, by scoring the tip 0.3 out of 5.++## Resources++- [pgMustard](https://www.pgmustard.com) official website.+- [pgMustard explain glossary](https://www.pgmustard.com/docs/explain).diff --git a/apps/temp-docs/docs/guides/integrations/plasmic.mdx b/apps/temp-docs/docs/guides/integrations/plasmic.mdxnew file mode 100644index 00000000000..3af93d722ef--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/plasmic.mdx@@ -0,0 +1,327 @@+---+id: plasmic+title: 'Plasmic'+description: 'Get started with Supabase and Plasmic, an open-source framework for building internal tools.'+---++In this guide, we will show you how to build a crowd-sourced Pokemon Pokedex, by connecting **Supabase**, an open source Firebase backend alternative, with **Plasmic**, a visual builder for the web. While many users leverage Plasmic to quickly launch and iterate on landing pages, in this tutorial we’ll show just how powerful Plasmic can be as a general-purpose visual builder for React, which can be used to design and implement fully featured read-write applications.++You can play with the live demo here:+[https://plasmic-supabase-demo.vercel.app/](https://plasmic-supabase-demo.vercel.app/)++You can also take a look at the Plasmic project here:+[https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6](https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6)++> You’ll need to enable 3rd-party cookies in your browser for the project to properly load.++++At a high level,++- **Supabase** is used to store the database of Pokemon (backed by Postgres) and provides an authentication backend. Our code base includes React components for querying the database, displaying this data, and supporting user sessions.+- **Plasmic** is used to create the pages and visual design of the application. We import our Supabase components into the Studio, which can be visually assembled and configured there (e.g. for displaying data).+- Plasmic designed pages are rendered back into the Next.js application.++## Step 1: Set up your Backend on Supabase++- On the [Supabase dashboard](https://app.supabase.com/), click `New project` and set the name of the project.+ By default, Supabase will already be set up for user signups with email, with users being stored in a `users` table.++++- Navigate to the `Table Editor` on the left side navigation bar. Here we can create a `New table` to store our Pokemon entries. Make sure you are in the `schema public` view. Create a new table called `entries`, with 6 columns:+ - `id`: is a unique ID for the entry. This column should be generated automatically as the primary column.+ - `user_id`: Create a relation to the `user` table by clicking on the link icon next to the column name. Here, you can select the `id` column of the `user` table.+ - `name`, `description`, `imageUrl`: This will store the name, description, and imageUrl for each Pokemon.+ - `inserted_at` : This will be an automatically populated column, set to when the row was first inserted.++> Note: In this tutorial we’ve turned off “[Row Level Security (RLS)](https://supabase.com/docs/guides/auth/row-level-security)”. In practice, you will want to create policies that restrict who gets to create, edit, and delete posts. By turning this off, any user can modify the database without restrictions.++++For your convenience, feel free to import the following CSV into Supabase to pre-populate your database. In order to import, you must select `Import data via spreadsheet`, in the new table dialog box. (It does not work on existing tables.)++[pokedex-export.csv](/img/guides/integrations/plasmic/pokedex-export.csv)++## Step 2: Set up your codebase++We have a working code example for you [here](https://github.com/plasmicapp/plasmic/tree/master/examples/supabase-demo). This starter comes with all of the code components you need to get started querying Supabase through Plasmic Studio.++> Code components are React components defined in your code base that we import into Plasmic Studio for use. Your project will be configured to look for these at `http://localhost:3000/plasmic-host` You can use these components in your design, as well as style them. Check out `supabase-demo/plasmic-init.ts` to see how they are registered with Plasmic.++First, clone the repo to your development machine and install the dependencies.++```bash+git clone [email protected]:plasmicapp/plasmic.git+cd plasmic/examples/supabase-demo/+yarn install+```++Copy `.env.example` to `.env.local`, which will store the environment variables when running a local development server. Add your Supabase project’s URL and public key, which you can find in the `API` tab on the left pane of your Supabase dashboard.++Now run the dev server, which listens at `http://localhost:3000`++```bash+yarn dev+```++## Step 3: Explore the existing application++Navigate to [http://localhost:3000](http://localhost:3000) in your web browser. The project will already be set up for user signups, logins, and an admin interface for adding and editing Pokemon to the database. Feel free to sign up with your email address for an account and add Pokemon to the database. Supabase will require that you verify your email address before you can log in.++If you pre-populated the database in Step 1. you should see the following homepage after logging in. Otherwise, feel free to add Pokemon manually via the UI.++++## Step 4: Clone the Plasmic project++Now let’s try to make some additions! The code base is currently configured to a read-only copy of the Plasmic project. Let’s make an editable copy first.++Open the default starter Plasmic project here:+[https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6](https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6)++++To make an editable copy, click on the `Copy Project` button in the blue bar. This will clone the project and redirect you to your copy.++### Step 4a: Configure your code base to use the new Plasmic project++Take note of the `project ID` and `API token`. You can find the project ID in the URL:+`https://studio.plasmic.app/projects/PROJECTID`.++The API token can be found by clicking the `Code` button in the top bar.++++Now go back to `.env.local` and update the corresponding project ID and token fields.++### Step 4b: Configure your Plasmic project app host++To tell Plasmic to look for your code components on your dev server, you’ll need to update your project’s app host to `http://localhost:3000/plasmic-host`.++> Note: At this point, you’ll need to keep your dev server running at `http://localhost:3000`for the project to load.++<video width="99%" autoPlay="autoplay" muted playsInline controls={true}>+ <source+ src="/docs/videos/guides/integrations/plasmic/configure-app-host-plasmic-05.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++After restarting the dev server and Plasmic Studio, you should now be able to make edits across Plasmic Studio and your codebase.++## Step 5: Create a new page for our Pokedex gallery++Let’s make a visual gallery for our Pokemon by using the code components from the code base.++Create a new page called `Gallery`, and set a path for this page (`/gallery`).++<video width="99%" autoPlay="autoplay" muted playsInline controls={true}>+ <source+ src="/docs/videos/guides/integrations/plasmic/create-gallery-page-plasmic-06.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++Insert a `SupabaseGrid` by searching the AddDrawer (by clicking the blue + button)++> For source see `components/CodeComponents/DatabaseComponents.tsx`++++Then in the right-hand panel, configure the props on `SupabaseGrid`.++- `tableName` should match the table you created in Supabase+- `tableColumns` are a comma-delimited list of columns you want to select from the table+- We also set the number of columns and spacing shown in the grid++++The `SupabaseGrid` will loop over the rows from the query.++Now customize the repeated content by inserting instances of `SupabaseField`. Select the type of content and a selector string to fetch a single value. In the example below, we use `{{row.imageUrl}}` to retrieve the `imageUrl` column of the row. Apply any styling and layout you want on these elements.++++### Putting it all together (video)++For your convenience, the following video shows you how to create the page end-to-end.++<video width="99%" autoPlay="autoplay" muted playsInline controls={true}>+ <source+ src="/docs/videos/guides/integrations/plasmic/end-to-end-plasmic-10.mp4"+ type="video/mp4"+ muted+ playsInline+ />+</video>++## Step 6: Check your dev server++If you have been running your development server this whole time, you’ll see that we have been automatically fetching and rebuilding your site as you make changes in Plasmic Studio. If you need to restart your dev server, just run:++```bash+yarn dev+```++See the results at `http://localhost:3000/gallery`.++## How does this all work under the hood?++### SupabaseGrid++`SupabaseGrid` is a code component that was registered in `plasmic-init.ts`. The `props` field is used to tell the Plasmic Studio the component prop interface, which allows us to expose these props in the right pane as shown in the screenshots earlier. See the docs for details on [component registration](https://docs.plasmic.app/learn/registering-code-components/).++```tsx+// plasmic-init.ts+...++PLASMIC.registerComponent(SupabaseGrid, {+ name: "SupabaseGrid",+ props: {+ tableName: "string",+ tableColumns: "string",+ queryFilters: "object",+ children: {+ type: "slot",+ defaultValue: {+ type: "text",+ value: "Placeholder",+ },+ },+ numColumns: {+ type: "number",+ defaultValue: 4,+ },+ columnGap: {+ type: "number",+ defaultValue: 16,+ },+ rowGap: {+ type: "number",+ defaultValue: 16,+ },+ count: "number",+ loading: {+ type: "slot",+ defaultValue: {+ type: "text",+ value: "Loading...",+ },+ },+ },+ importPath: "./components/CodeComponents/DisplayCollections",+});+```++### SupabaseQuery++`SupabaseGrid` wraps a `SupabaseQuery` component, where we perform the query based on the provided props and store the result in a `SupabaseQueryContext`. This will be used in downstream components to display the data.++```tsx+// supabase-demo/components/CodeComponents/DatabaseComponents.tsx+export function SupabaseQuery(props: SupabaseQueryProps) {+ // These props are set in the Plasmic Studio+ const { children, tableName, columns, className, filters, single } = props;+ const [result, setResult] = React.useState<any[] | undefined>(undefined);++...++ // Performs the Supabase query+ let query = supabase.from(tableName!).select(columns + ",id");+ query = applyFilter(query, validFilters, contexts);+ const { data, error, status } = await (single ? query.single() : query.order('id', { ascending: false }));++ if (error && status !== 406) {+ throw error;+ } else if (data) {+ setResult(data);+ }++...++ // Save the result in a `SupabaseQueryContext for use with downstream components+ return (+ <div className={className}>+ <SupabaseQueryContext.Provider value={result}>+ {children}+ </SupabaseQueryContext.Provider>+ </div>+ );+}+```++Note that this code component is defined in your codebase. Feel free to augment it to expose more powerful querying capabilities to the Plasmic Studio.++### SupabaseGridCollection++`SupabaseGrid` also nests a `SupabaseGridCollection` under the `SupabaseQuery`. This code component is a simple CSS grid, where we retrieve the Supabase query results from `SupabaseQueryContext`, and iterate over the results. For each row, we populate a `RowContext`, which will be used by the children to read the results of a single row. Note the use of `repeatedElement`, a special convenience function that enables the component’s children to be repeated. In this case, this represents a single card to be shown in the gallery.++```tsx+// supabase-demo/components/CodeComponents/DisplayCollections.tsx++export function SupabaseGridCollection(props: SupabaseGridCollectionProps) {+ const supabaseQuery = React.useContext(SupabaseQueryContext)+ const {+ children,+ columns,+ columnGap,+ rowGap,+ count,+ className,+ loading,+ testLoading,+ } = props++ const result = supabaseQuery+ if (!result || testLoading) {+ return loading+ }++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: `repeat(${columns}, 1fr)`,+ columnGap: `${columnGap}px`,+ rowGap: `${rowGap}px`,+ }}+ className={className}+ >+ {result.slice(0, count).map((row: any, i: any) => (+ <RowContext.Provider value={row} key={row.id}>+ <div key={row.id}>{repeatedElement(i === 0, children)}</div>+ </RowContext.Provider>+ ))}+ </div>+ )+}+```++### SupabaseField++`SupabaseField` will either render a `SupabaseTextField` or `SupabaseImgField` depending on the type. These code components simply read a single value from the contexts and display the data.++```tsx+// supabase-demo/components/CodeComponents/DisplayCollections.tsx++export function SupabaseTextField({+ name,+ className,+}: {+ name?: string+ className?: string+}) {+ const contexts = useAllContexts()+ if (!name) {+ return <p>You need to set the name prop</p>+ }+ return <div className={className}>{getPropValue(name, contexts)}</div>+}+```++In summary, by populating state into React contexts, we can store and retrieve data for use in other code components, which can be used for arbitrarily powerful interactions in Plasmic Studio.diff --git a/apps/temp-docs/docs/guides/integrations/polyscale.mdx b/apps/temp-docs/docs/guides/integrations/polyscale.mdxnew file mode 100644index 00000000000..412f94ff2c1--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/polyscale.mdx@@ -0,0 +1,63 @@+---+id: polyscale+title: 'PolyScale'+description: 'The easiest way to get low-latency reads from your Supabase database for multi-region applications is by using PolyScale, a code-free global caching service.'+---++[PolyScale](https://polyscale.ai) is an intelligent, serverless database caching engine which allows low-latency reads from Supabase globally, no coding required. Supabase can be connected to PolyScale in minutes, providing you fast access to your Supabase data around the globe.++This guide explains how to connect Supabase to a PolyScale cache.++The video below illustrates how to get connected. Or you can read the steps below.++<div class="video-container">+ <iframe+ src="https://www.youtube.com/embed/ZQ8TG-A-CIw?rel=0"+ frameborder="0"+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; modestbranding; showinfo=0"+ allowfullscreen+ width="100%"+ height="400px"+ ></iframe>+</div>++## Step 0: Create a PolyScale account++If you do not already have a PolyScale account, you can create an account [here](https://app.polyscale.ai/signup). PolyScale offers a free tier and no credit card is required.++## Step 1: Create your PolyScale Cache++### 1.1 Retrieve your Supabase Host++In your Supabase project, click on `Settings > Database` and scroll down to the `Connection info` section to copy your database `Host`.++++### 1.2 Configure your PolyScale Cache++- In your PolyScale account, click on the **New Cache** button+- Give the cache a **Name**+- Select **PostgreSQL** for the **Type**+- Enter the **Host** from Step 1.1 above+- Enter `5432` for the **Port**+- Click **Create**++++Your cache is now created. PolyScale automatically checks to see that your database is accessible from all our global PoPs.++## Step 2: Connect to your PolyScale Cache++Using your PolyScale cache is simple -- instead of connecting to your Supabase database directly, you'll replace your orignal connection string with the PolyScale connection string in your application.++For example, if your original connection string was: `postgres://postgres:[email protected]:5432`++Your PolyScale connection string would be: `postgres://postgres:[email protected]:5432?application_name=a645cb93-fa53-46b2-9d6c-227e357e5bfb`++You can read more about connecting to PolyScale [here](https://docs.polyscale.ai/connecting-to-polyscale#postgresql)++That's it.++## All done!++You can read more about PolyScale [here](https://www.polyscale.ai/) or check out our [documentation](https://docs.polyscale.ai/).diff --git a/apps/temp-docs/docs/guides/integrations/prisma.mdx b/apps/temp-docs/docs/guides/integrations/prisma.mdxnew file mode 100644index 00000000000..e7f8d517ccc--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/prisma.mdx@@ -0,0 +1,177 @@+---+id: prisma+title: 'Prisma'+description: 'Connect your Supabase postgres database to your Prisma project.'+---++This guide explains how to quickly connect the Postgres database provided by Supabase to a Prisma project.++[Prisma](https://prisma.io) is an [open source](https://github.com/prisma/prisma) next-generation ORM. It consists of the following parts:++- **Prisma Client**: Auto-generated and type-safe query builder for Node.js & TypeScript.+- **Prisma Migrate**: Migration system.+- **Prisma Studio**: GUI to view and edit data in your database.++## Step 1: Get the connection string from Supabase project settings++Go to the settings page from the sidebar and navigate to the **Database** tab. You’ll find the database’s connection string with a placeholder for the password you provided when you created the project.+++## Step 2: Testing the connection++To make sure that everything works correctly, let’s try the connection string in a Prisma project.++If you already have one, all you need to do is set the `DATABASE_URL` to the connection string (including the password) in your `.env` file, and you’re good to go.++In case you don’t have a Prisma project or this is your first time working with Prisma, you’re going to use the repo from the [quickstart](https://www.prisma.io/docs/getting-started/quickstart) guide.++### Cloning the starter project++Navigate into a directory of your choice and run the following command in your terminal if you’re on a Windows machine:++```bash+curl https://pris.ly/quickstart -L -o quickstart-main.tar.gz && tar -zxvf quickstart-main.tar.gz quickstart-main/typescript/starter && move quickstart-main\typescript\starter starter && rmdir /S /Q quickstart-main && del /Q quickstart-main.tar.gz+```++And if you’re using Mac OS or Linux, run the following command:++```bash+curl -L https://pris.ly/quickstart | tar -xz --strip=2 quickstart-main/typescript/starter+```++You can now navigate into the directory and install the project’s dependencies:++```bash+cd starter && npm install+```++### A look at the project’s structure++This project comes with TypeScript configured and has the following structure.++- A `prisma` directory which contains:+ - A `dev.db` file: This is a SQLite database.+ - A `schema.prisma` file: Where we define the different database models and relations between them.+- A `.env` file: Contains the `DATABASE_URL` variable, which Prisma will use.+- A `script.ts` file: where we will run some queries using Prisma Client.+ This starter also comes with the following packages installed:+- [`@prisma/client`](https://www.npmjs.com/package/@prisma/client): An auto-generated and type-safe query builder that’s _tailored_ to your data.+- [`prisma`](https://www.npmjs.com/package/prisma): Prisma’s command-line interface (CLI). It allows you to initialize new project assets, generate Prisma Client, and analyze existing database structures through introspection to automatically create your application models.+ > Note: Prisma works with both JavaScript and TypeScript. However, to get the best possible development experience, using TypeScript is highly recommended.++### Configuring the project to use PostgreSQL++Go ahead and delete the `prisma/dev.db` file because we will be switching to PostgreSQL.+Next, inside the `prisma/.env` file, update the value of the `DATABASE_URL` variable to the connection string you got in **step 1**. The URL might look as follows:++```env+# prisma/.env+postgres://postgres:[YOUR-PASSWORD]@db.vdbnhqozmlzdsaejdxwr.supabase.co:5432/postgres+```++Finally, inside your `schema.prisma` file, change the `provider` from “sqlite” to `“postgresql”`.+This is what your `schema.prisma` file should look like:++```go+datasource db {+ provider = “postgresql”+ url = env(“DATABASE_URL”)+}+generator client {+ provider = “prisma-client-js”+}+model Post {+ id Int @id @default(autoincrement())+ title String+ content String?+ published Boolean @default(false)+ author User? @relation(fields: [authorId], references: [id])+ authorId Int?+}+model User {+ id Int @id @default(autoincrement())+ email String @unique+ name String?+ posts Post[]+}+```++To test that everything works correctly, run the following command to create a migration:++```bash+prisma migrate dev --name init+```++You can optionally give your migration a name, depending on the changes you made. Since this is the project’s first migration, you’re setting the `--name` flag to “init”.+If everything works correctly, you should get the following message in your terminal:++```text+Your database is now in sync with your schema.+:heavy_check_mark: Generated Prisma Client (2.x.x) to ./node_modules/@prisma/client in 111ms+```++This will create a `prisma/migrations` folder inside your `prisma` directory and synchronize your Prisma schema with your database schema.++> Note: if you want to skip the process of creating a migration history, you can use the [`db push`](https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push) command instead of `migrate dev`.+> If you go to your Supabase project, in the table editor, you should see that two tables have been created, a `Post` and a `User` table.+> +> That’s it! You have now successfully connected a Prisma project to a PostgreSQL database hosted on Supabase and ran your first migration.++## Connection pooling with Supabase++If you’re working in a serverless environment (for example Node.js functions hosted on AWS Lambda, Vercel or Netlify Functions), you need to set up [connection pooling](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#serverless-environments-faas) using a tool like [PgBouncer](https://www.pgbouncer.org/). That’s because every function invocation may result in a [new connection to the database](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#the-serverless-challenge). Supabase [supports connection management using PgBouncer](https://supabase.io/blog/2021/04/02/supabase-pgbouncer#what-is-connection-pooling) and are enabled by default.+Go to the **Database** page from the sidebar in the Supabase dashboard and navigate to **connection pool** settings++When running migrations you need to use the non pooled connection URL (like the one we used in **step 1**). However, when deploying your app, you’ll use the pooled connection URL and add the `?pgbouncer=true` flag to the PostgreSQL connection URL. To minimize the number of concurrent connections, setting the `connection_limit` to `1` is also recommended. So the URL might look as follows:++```env+# prisma/.env+postgres://postgres:[YOUR-PASSWORD]@db.vdbnhqozmlzdsaejdxwr.supabase.co:6543/postgres?pgbouncer=true&connection_limit=1+```++Prisma Migrate uses database transactions to check out the current state of the database and the migrations table. However, the Migration Engine is designed to use a single connection to the database, and does not support connection pooling with PgBouncer. If you attempt to run Prisma Migrate commands in any environment that uses PgBouncer for connection pooling, you might see the following error:++```bash+Error: undefined: Database error+Error querying the database: db error: ERROR: prepared statement “s0” already exists+```++This is a known issue and it is being worked on, you can follow the progress on this [GitHub issue](https://github.com/prisma/prisma/issues/6485).+If you want to learn more about Prisma, check out the [docs](https://www.prisma.io/docs). Also in case you have any questions or run into any issue, feel free to start a discussion in the repo’s [discussions section](https://github.com/prisma/prisma/discussions).++## Troubleshooting++If you run `prisma migrate dev --name init` multiple times, it sometimes asks if you want to recreate the whole schema. If you chose yes, it will delete the public schema and recreate it. The default grants are missing after this. If you run into this problem, add a helper SQL for fixing the grants:++```sql+CREATE SCHEMA IF NOT EXISTS "auth";+CREATE SCHEMA IF NOT EXISTS "extensions";+create extension if not exists "uuid-ossp" with schema extensions;+create extension if not exists pgcrypto with schema extensions;+create extension if not exists pgjwt with schema extensions;++grant usage on schema public to postgres, anon, authenticated, service_role;+grant usage on schema extensions to postgres, anon, authenticated, service_role;+alter user supabase_admin SET search_path TO public, extensions; -- don't include the "auth" schema++grant all privileges on all tables in schema public to postgres, anon, authenticated, service_role, supabase_admin;+grant all privileges on all functions in schema public to postgres, anon, authenticated, service_role, supabase_admin;+grant all privileges on all sequences in schema public to postgres, anon, authenticated, service_role, supabase_admin;++alter default privileges in schema public grant all on tables to postgres, anon, authenticated, service_role;+alter default privileges in schema public grant all on functions to postgres, anon, authenticated, service_role;+alter default privileges in schema public grant all on sequences to postgres, anon, authenticated, service_role;++alter default privileges for user supabase_admin in schema public grant all on sequences to postgres, anon, authenticated, service_role;+alter default privileges for user supabase_admin in schema public grant all on tables to postgres, anon, authenticated, service_role;+alter default privileges for user supabase_admin in schema public grant all on functions to postgres, anon, authenticated, service_role;++alter role anon set statement_timeout = '3s';+alter role authenticated set statement_timeout = '8s';+```++## Resources++- [Prisma](https://prisma.io) official website.+- [Prisma GitHub](https://github.com/prisma/prisma).+- [Prisma](https://www.prisma.io/docs/) documentation.diff --git a/apps/temp-docs/docs/guides/integrations/sequin.mdx b/apps/temp-docs/docs/guides/integrations/sequin.mdxnew file mode 100644index 00000000000..3ba6e7afae9--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/sequin.mdx@@ -0,0 +1,84 @@+---+id: sequin+title: 'Sequin'+description: 'Sync platforms like Stripe and Salesforce with your Supabase database in real-time using Sequin.'+---++This guide explains how to quickly setup a sync between Sequin and a Supabase Postgres database.++[Sequin](https://sequin.io) allows you to sync platforms like Stripe and Salesforce with Supabase in real-time. You'll be able to read and write to your [Stripe](https://stripe.com/) customers or [Salesforce](https://www.salesforce.com/) accounts right from the Supabase client using SQL. Here's how to get setup.++## Step 1: Connect Sequin to Supabase++To connect Supabase to Sequin, you'll first need to retrieve the credentials for your Supabase Postgres database:++1. In the Supabase dashboard, go to the settings page and open up your **Database** settings. In the **Connection info** section, you'll find the credentials you need - like `host` and `user`:++ ++2. In the [Sequin console](https://app.sequin.io), go to your sync's configuration and open the **Destination** section. Select **Launch or Connect** and then click **Connect** to configure the connection to your Supabase Postgres:++ ++3. In the connection modal that appears, enter the `Host` and `Port` for your Supabase database and click **Continue**.++ ++4. Now, enter the `Database name` and set the `schema` name for your sync. For instance, if your syncing Stripe, you'll likely want to name your synced schema something like `stripe`. Finally, enter the `user` and `password` for your Supabase database and then click **Continue**. Sequin will verify it can properly connect to your database with the correct permissions.++ ++5. Sequin is now connected to your Supabase Postgres database and will ask you to confirm which database users should be able to access your synced schema. Select all of the users and click **Continue**:++ ++6. That's it. Sequin will now create a new schema and permissions group in your Supabase database. Name the database connection in Sequin something like `Supabase` and your done!++In the Supabase dashboard, you can go to the **Table Editor** and you'll see a new schema full of your synced platform data.++++## Step 2: Grant Permissions++To ensure the right users can access the synced schema Sequin manages, you'll need to run a couple permission grants.++1. In the Sequin console, click the **Connect** button next to your sync and copy down your `Schema` and unique `Read Group`.++ ++2. Now, in the Supabase dashboard, go to the **SQL Editor** and run the following permission grants:++ ```sql+ GRANT sequin_read_▒▒▒▒ TO postgres, anon, authenticated, service_role;++ GRANT USAGE ON SCHEMA {{your_schema_name}} TO anon, authenticated, service_role;++ GRANT ALL ON ALL TABLES IN SCHEMA {{your_schema_name}} TO anon, authenticated, service_role;++ ALTER DEFAULT PRIVILEGES FOR ROLE postgres, supabase_admin IN SCHEMA {{your_schema_name}} GRANT ALL ON TABLES TO anon, authenticated, service_role;+ ```++ These permission grants ensure that the various Supabase database users can access and read all the tables in your synced schema.++## Step 3: Configure the Supabase Client++Finally, you'll need to define a new [Supabase client](https://supabase.com/docs/reference/javascript/initializing#api-schemas) in your application to access your synced schema. In the file where you initialized your Supabase client, define a new client with a `schema` parameter:++```javascript+export const supabase_schema = createClient(+ 'https://xyzcompany.supabase.co',+ 'public-anon-key',+ {+ schema: {{your_schema_name}},+ }+);+```++You'll use this client to query for data in your synced schema.++## Resources++- [Sequin](https://sequin.io*) official website.+- [Sequin Console](https://app.sequin.io*).+- [Sequin](https://docs.sequin.io/welcome) documentation.+- [Sequin + Supabase + Stripe Tutorial](https://github.com/sequin-io/build-a-saas-with-next-js-supabase-stripe-and-sequin)diff --git a/apps/temp-docs/docs/guides/integrations/snaplet.mdx b/apps/temp-docs/docs/guides/integrations/snaplet.mdxnew file mode 100644index 00000000000..1153d206543--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/snaplet.mdx@@ -0,0 +1,116 @@+---+id: snaplet+title: 'Snaplet'+description: 'Get started with Supabase and Snaplet, a developer tool for working with safe, versioned, up-to-date production-like data'+---++This step-by-step guide explains how to use Snaplet to clone your production Supabase project into another development database.++[Snaplet](https://snaplet.dev/) is a developer tool that copies a Postgres database, transforming personal information, so that you can **safely code against actual data.** This functionality makes it possible to easily achieve environment parity in Supabase.++Let's get started!++Follow along in the video below as the founder of Snaplet, Peter Pistorius, takes you through the entire process. Otherwise, you can skip the video and dive into the step-by-step guide.++<div class="video-container">+ <iframe+ src="https://www.youtube.com/embed/oPtMMhdhEP4?rel=0"+ frameborder="0"+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; modestbranding; showinfo=0"+ allowfullscreen+ width="100%"+ height="400px"+ ></iframe>+</div>++## Step 1: Prerequisites++1. **A production Supabase project's connection string:** These can be found in Supabase via `Organization > Project > Database > Connection Pooling > Connection string`+2. **A development Supabase project's connection string:** Same steps as above, but a different project/environment+3. **A read-only role** in Production (recommended): This can be done by running the following statements on Supabase via `Organization > SQL Editor > + New Query`++> To create a read-only role across all schemas you can checkout the Snaplet [docs](https://docs.snaplet.dev/postgresql/create-read-only-role)++4. **Superuser access** for the development project. This can be done in Supabase via `Organization > SQL Editor > + New Query` and running this statement:+ `ALTER USER postgres WITH superuser;`++## Step 2: Copying your production database++### 2.1. Connect your data source++Navigate to [https://www.snaplet.dev/](https://www.snaplet.dev/) and sign up for a new account (it’s free). Once you have successfully signed up for a new account, create a team, and start by connecting to your Supabase project.++++Enter the credentials of your production Supabase project. Find the "Connection string" in Supabase via `Organization > Project > Settings > Database > Connection string` (at the bottom of the page).++The password is the same password you used when creating the Supabase project.++++You’ll have to confirm providing Snaplet access to your database. Snaplet will prompt you to only provide `read-only` access to your database. Snaplet has a guide in their documentation on how to do so [here](https://docs.snaplet.dev/postgresql/create-read-only-role).++> Note that whatever connection string you provide here will be that of your Data Source – essentially the production database in a real-life scenario++++### 2.2. Transform your data++++The next step is to exclude any schemas that you do not require. You are able to exclude an entire schema by clicking on the drop-down at the top, selecting the schema you would like to exclude and clicking ‘Exclude schema’. Alternatively, you can select a given schema and exclude only specific tables from that particular schema. Exclude any non-required table data (such as logs) and extensions and view your columns.++At this point, Snaplet will automatically detect any columns that have Personally Identifiable Information (PII) and mark them in purple. If there are any additional columns that hold data you would like to anonymise, you can click on the respective column name and provide a replacement value for the data in that column. To complete the onboarding, click on `Review and Save` and proceed to the dashboard.++++### 2.3. Create a Snapshot++Create a snapshot of your production database. This is what you’re going to restore later into your data target (more on that later in the guide).++## Step 3: Pasting into your development database++### 3.1. Create a data target on Supabase++Your data target is where you want Snaplet to restore the captured snapshot of your production project. This would most likely be either your staging or developer Supabase project. If you don’t already have a developer database setup on Supabase, create a new data target by setting up a new project on Supabase. To create a new project, follow the steps below:++1. Go to [app.supabase.com](https://app.supabase.com/)+2. Click on “new project”+3. Enter your project details+4. Wait for the new database to launch++> Remember the password you use when creating the project. You’ll need this password to connect your database to Snaplet later.++### 3.2. Make your `postgres` user a superuser++Snaplet requires the ability to drop the database schemas whilst restoring a snapshot. In order to do that, Snaplet requires `superuser` privileges.++1. Navigate to the `SQL Editor` in your Supabase console+2. Click on `new query`+3. Paste `alter user postgres with superuser;` into the SQL editor+4. Run the query++### 3.3. Install the Snaplet CLI++1. Open your terminal and run `curl -sL https://app.snaplet.dev/get-cli/ | bash`+2. Run `snaplet auth`+3. Navigate to [https://app.snaplet.dev/access-token/cli](https://app.snaplet.dev/access-token/cli) to get your access token+4. Paste your access token in the terminal++### 3.4. Restore to the data target++You're now ready to restore your production snapshot into your Supabase development project.++1. Navigate to your project directory+2. Run `snaplet setup` – you will be prompted to enter your database credentials. These are the database credentials of your **data target.** This could be your staging or development database++Once completed, you will be presented with a list of databases that are connected to your Snaplet account.++1. Select a data source from the list+2. Run `snaplet snapshot restore`++## All done!++As a Supabase user, you can see how this solves an issue developers all typically experience when attempting to create multiple development environments and populating each of those environments with data that can be worked with. Snaplet simplifies this process down to creating the respective Supabase projects, connecting the data source (The production database) to Snaplet and telling Snaplet where to restore that data (staging and development databases).++If you want to learn more about Snaplet, you can explore the Snaplet [docs](https://docs.snaplet.dev/). If you have any questions, feel free to [reach out on Discord](https://discord.com/invite/6HUuajc866).diff --git a/apps/temp-docs/docs/guides/integrations/stytch.mdx b/apps/temp-docs/docs/guides/integrations/stytch.mdxnew file mode 100644index 00000000000..b804c594682--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/stytch.mdx@@ -0,0 +1,659 @@+---+id: stytch+title: 'Stytch'+description: "Build a Next.js application powered by password-less authentication from Stytch, and Supabase's Row Level Security (RLS)."+---++In this guide we will build a simple expense tracker web application using Stytch, Supabase, and Next.js.++[Stytch](https://stytch.com?utm_source=supabase&utm_medium=guide) provides an all-in-one platform for passwordless auth. Stytch makes it easy for you to embed passwordless solutions into your websites and apps for better security, better conversion rates, and a better end user experience. Their easy-to-use SDKs and direct API access allows for maximum control and customization. In this example we will use [Email magic links](https://stytch.com/products/email-magic-links?utm_source=supabase&utm_medium=guide) to create and log in our users, and Session management. There is an additional, optional step to enable [Google One Tap](https://stytch.com/blog/improving-conversion-with-google-one-tap?utm_source=supabase&utm_medium=guide) which is an especially high-converting Google OAuth sign-up and login flow.++We will leverage Supabase to store and authorize access to user data. Supabase makes it simple to set up Row Level Security (RLS) policies which ensure users can only read and write data that they are authorized to do so. If you do not already have a Supabase account, you will need to create one.++This guide will use [Next.js](https://nextjs.org/) which is a web application framework built on top of React. Stytch provides a [Node.js library](https://github.com/stytchauth/stytch-node) and a [React library](https://github.com/stytchauth/stytch-react) which makes building Next.js apps super easy.++> Note: You can find a completed version of this project on [Github](https://github.com/stytchauth/stytch-nextjs-supabase).++## Step 0: Create a Stytch Account++If you already have a Stytch account you may skip this step.++Go to [Stytch](https://stytch.com?utm_source=supabase&utm_medium=guide), and create an account. Note that Stytch provides two ways to create an account, either via Google OAuth, or through Email magic links. This is the same user experience we will be building in this guide!++++## Step 1: Set up Stytch redirect URLs++First we need to add the redirect URLs that will be used during the Email magic link flow. This step helps ensure bad actors cannot spoof your magic links and hijack redirects.++Navigate to your [redirect URL settings](https://stytch.com/dashboard/redirect-urls?utm_source=supabase&utm_medium=guide) in the Stytch dashboard, and under **Test environment** create an entry where the **URL** is `http://localhost:3000/api/authenticate` and the **Type** is `All`.++++After pressing **Confirm**, the redirect URLs dashboard will update to show your new entry. We will use this URL later on.++++## Step 2: Create a Supabase project++From your [Supabase dashboard](https://app.supabase.com/), click **New project**.++Enter a `Name` for your Supabase project.++Enter a secure `Database Password`.++Click **Create new project**. It may take a couple minutes for your project to be provisioned.++++## Step 3: Creating data in Supabase++Once your Supabase project is provisioned, click Table editor, then New table. This tool is available from the sidebar menu in the [Supabase dashboard](https://app.supabase.com/).++Enter `expenses` as the **Name** field.++Select `Enable Row Level Security (RLS)`.++Add three new columns:++- `user_id` as `text`++- `title` as `text`++- `value` as `float8`++Click **Save** to create the new table.++++From the Table editor view, select the expenses table and click **Insert row**.++Fill out the title and value fields (leave user_id blank for now) and click **Save**.++++Use **Insert Row** to further populate the table with expenses.++++## Step 4: Building a Next.js app++Using a terminal, create a new Next.js project:++```bash+npx create-next-app stytch-supabase-example+```++Next, within `stytch-supabase-example` create a `.env.local` file and enter the following values:++```+STYTCH_PROJECT_ENV=test+STYTCH_PROJECT_ID=GET_FROM_STYTCH_DASHBOARD+STYTCH_PUBLIC_TOKEN=GET_FROM_STYTCH_DASHBOARD+STYTCH_SECRET=GET_FROM_STYTCH_DASHBOARD+NEXT_PUBLIC_SUPABASE_URL=GET_FROM_SUPABASE_DASHBOARD+NEXT_PUBLIC_SUPABASE_KEY=GET_FROM_SUPABASE_DASHBOARD+SUPABASE_SIGNING_SECRET=GET_FROM_SUPABASE_DASHBOARD+```++> Note: Stytch values can be found in the project [dashboard](https://stytch.com/dashboard/api-keys?utm_source=supabase&utm_medium=guide) under **API Keys**.++++> Note: Supabase values can be found under **Settings** > **API** for your project.++++Start your Next.js development server to read in the new values from `.env.local`.++```bash+npm run dev+```++You should have a running Next.js application on `localhost:3000`.++## Step 5: Build the Login Form++Now we will replace the default Next.js home page with a login UI. We will use the Stytch React library.++> Note: Stytch provides direct API access for those that want to build login UI themselves++Install the `@stytch/stytch-react` library.++```bash+npm install @stytch/stytch-react+```++In the root directory, create a new folder named `components` and file in that folder named `/StytchLogin.js`. Within this file, paste the snippet below. This will configure, and style the Stytch React component to use Email magic links.++```jsx+// components/StytchLogin.js+import React from 'react'+import { Stytch } from '@stytch/stytch-react'++const stytchConfig = {+ loginOrSignupView: {+ products: ['emailMagicLinks'],+ emailMagicLinksOptions: {+ loginRedirectURL: 'http://localhost:3000/api/authenticate',+ loginExpirationMinutes: 30,+ signupRedirectURL: 'http://localhost:3000/api/authenticate',+ signupExpirationMinutes: 30,+ createUserAsPending: true,+ },+ },+ style: {+ fontFamily: '"Helvetica New", Helvetica, sans-serif',+ width: '321px',+ primaryColor: '#0577CA',+ },+}++const StytchLogin = ({ publicToken }) => {+ return (+ <Stytch+ publicToken={publicToken}+ loginOrSignupView={stytchConfig.loginOrSignupView}+ style={stytchConfig.style}+ />+ )+}++export default StytchLogin+```++Additionally, create a profile component by creating a file called `Profile.js` in `/components`. We will use this component to render our expenses stored in Supabase later on.++```jsx+// components/Profile.js+import React from 'react'+import Link from 'next/link'++export default function Profile({ user }) {+ return (+ <div>+ <h1>Welcome {user.userId}</h1>+ <h2>Your expenses</h2>+ {user.expenses?.length > 0 ? (+ user.expenses.map((expense) => (+ <p key={expense.id}>+ {expense.title}: ${expense.value}+ </p>+ ))+ ) : (+ <p>You have no expenses!</p>+ )}++ <Link href="/api/logout" passHref>+ <button>+ <a>Logout</a>+ </button>+ </Link>+ </div>+ )+}+```++Finally, replace the contents of the file `/pages/index.js` to render our new `StytchLogin` and `Profile` components.++```jsx+// pages/index.js+import styles from '../styles/Home.module.css'+import Profile from '../components/Profile'+import StytchLogin from '../components/StytchLogin'++const Index = ({ user, publicToken }) => {+ let content+ if (user) {+ content = <Profile user={user} />+ } else {+ content = <StytchLogin publicToken={publicToken} />+ }++ return <div className={styles.main}>{content}</div>+}++export async function getServerSideProps({ req, res }) {+ const user = null // Will update later+ return {+ props: { user, publicToken: process.env.STYTCH_PUBLIC_TOKEN },+ }+}++export default Index+```++On `localhost:3000` there is now a login form prompting for your email address.++++Enter your email address and press **Continue with email**.++++In your inbox you will find a login request from your app.++++However, if you click the link in the email you will get a 404. We need to build an API route to handle the email magic link authentication.++## Step 6: Authenticate and start a session++To make authentication easier we will use the Stytch Node.js library. Run++```bash+npm install stytch+```++Additionally, we will need to store the authenticated session in a cookie. Run++```bash+npm install cookies-next+```++Create a new folder named `utils` and inside a file named`stytchLogic.js` with the following contents++```jsx+// utils/stytchLogic.js+import * as stytch from 'stytch'+import { getCookie, setCookies, removeCookies } from 'cookies-next'++export const SESSION_COOKIE = 'stytch_cookie'++let client+const loadStytch = () => {+ if (!client) {+ client = new stytch.Client({+ project_id: process.env.STYTCH_PROJECT_ID,+ secret: process.env.STYTCH_SECRET,+ env:+ process.env.STYTCH_PROJECT_ENV === 'live'+ ? stytch.envs.live+ : stytch.envs.test,+ })+ }++ return client+}++export const getAuthenticatedUserFromSession = async (req, res) => {+ const sessionToken = getCookie(SESSION_COOKIE, { req, res })+ if (!sessionToken) {+ return null+ }++ try {+ const stytchClient = loadStytch()+ const resp = await stytchClient.sessions.authenticate({+ session_token: sessionToken,+ })+ return resp.session.user_id+ } catch (error) {+ console.log(error)+ return null+ }+}++export const revokeAndClearSession = async (req, res) => {+ const sessionToken = getCookie(SESSION_COOKIE, { req, res })++ if (sessionToken) {+ try {+ const stytchClient = loadStytch()+ await stytchClient.sessions.revoke({+ session_token: sessionToken,+ })+ } catch (error) {+ console.log(error)+ }+ removeCookies(SESSION_COOKIE, { req, res })+ }++ return res.redirect('/')+}++export const authenticateTokenStartSession = async (req, res) => {+ const { token, type } = req.query+ let sessionToken+ try {+ const stytchClient = loadStytch()+ const resp = await stytchClient.magicLinks.authenticate(token, {+ session_duration_minutes: 30,+ })+ sessionToken = resp.session_token+ } catch (error) {+ console.log(error)+ const errorString = JSON.stringify(error)+ return res.status(400).json({ errorString })+ }++ setCookies(SESSION_COOKIE, sessionToken, {+ req,+ res,+ maxAge: 60 * 60 * 24,+ secure: true,+ })++ return res.redirect('/')+}+```++This logic is responsible for setting up the Stytch client we will use to call the API. It provides functions we will use to login, logout, and validate user sessions.++In order to complete the email login flow, create a new file `pages/api/authenticate.js` with the contents:++```jsx+// pages/api/authenticate.js+import { authenticateTokenStartSession } from '../../utils/stytchLogic'++export default async function handler(req, res) {+ return authenticateTokenStartSession(req, res)+}+```++We will also create a logout API endpoint with similar contents. In `pages/api/logout.js` include the following:++```jsx+// pages/api/logout.js+import { revokeAndClearSession } from '../../utils/stytchLogic'++export default async function handler(req, res) {+ return revokeAndClearSession(req, res)+}+```++Finally, update `pages/index.js` by importing `getAuthenticatedUserFromSession`, and calling it to set the user variable in `getServerSideProps`.++```jsx+// pages/index.js+import styles from '../styles/Home.module.css'++import StytchLogin from '../components/StytchLogin'+import Profile from '../components/Profile'+import { getAuthenticatedUserFromSession } from '../utils/stytchLogic'++const Index = ({ user, publicToken }) => {+ let content+ if (user) {+ content = <Profile user={user} />+ } else {+ content = <StytchLogin publicToken={publicToken} />+ }++ return <div className={styles.main}>{content}</div>+}++export async function getServerSideProps({ req, res }) {+ const userId = await getAuthenticatedUserFromSession(req, res)+ if (userId) {+ return {+ props: { user: { userId }, publicToken: process.env.STYTCH_PUBLIC_TOKEN },+ }+ }+ return {+ props: { publicToken: process.env.STYTCH_PUBLIC_TOKEN },+ }+}++export default Index+```++Return to `localhost:3000`, and login again by sending yourself a new email. Upon clicking through in the email you should be presented with “Welcome $USER_ID”. If you refresh the page, you should remain in an authenticated state. If you press **Logout** then you should return to the login screen.++++Now that we have a working login flow with persistent authentication it is time to pull in our expense data from Supabase.++## Step 7: Requesting user data from Supabase++First, install the Supabase client:++```bash+npm install @supabase/supabase-js+```++In order to pass an authenticated `user_id` to Supabase we will package it within a JWT. Install jsonwebtoken:++```bash+npm install jsonwebtoken+```++Create a new file `utils/supabase.js` and add the following:++```jsx+// utils/supabase.js+import { createClient } from '@supabase/supabase-js'+import jwt from 'jsonwebtoken'++const getSupabase = (userId) => {+ const supabase = createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.NEXT_PUBLIC_SUPABASE_KEY+ )++ if (userId) {+ const payload = {+ userId,+ exp: Math.floor(Date.now() / 1000) + 60 * 60,+ }++ supabase.auth.session = () => ({+ access_token: jwt.sign(payload, process.env.SUPABASE_SIGNING_SECRET),+ })+ }++ return supabase+}++export { getSupabase }+```++Our payload for the JWT will contain our user's unique identifier from Stytch, their `user_id`. We are signing this JWT using Supabase's signing secret, so Supabase will be able to validate it is authentic and hasn't been tampered with in transit.++Let's load our expenses from Supabase on the home page! Update `pages/index.js` a final time to make a request for expense data from Supabase.++```jsx+import styles from '../styles/Home.module.css'++import StytchLogin from '../components/StytchLogin'+import Profile from '../components/Profile'+import { getAuthenticatedUserFromSession } from '../utils/stytchLogic'+import { getSupabase } from '../utils/supabase'++const Index = ({ user, publicToken }) => {+ let content+ if (user) {+ content = <Profile user={user} />+ } else {+ content = <StytchLogin publicToken={publicToken} />+ }++ return <div className={styles.main}>{content}</div>+}++export async function getServerSideProps({ req, res }) {+ const userId = await getAuthenticatedUserFromSession(req, res)++ if (userId) {+ const supabase = getSupabase(userId)+ const { data: expenses } = await supabase.from('expenses').select('*')++ return {+ props: {+ user: { userId, expenses },+ publicToken: process.env.STYTCH_PUBLIC_TOKEN,+ },+ }+ } else {+ return {+ props: { publicToken: process.env.STYTCH_PUBLIC_TOKEN },+ }+ }+}++export default Index+```++When we reload our application, we are still getting the empty state for expenses.++This is because we enabled Row Level Security, which blocks all requests by default and lets you granularly control access to the data in your database. To enable our user to select their expenses we need to write a RLS policy.++## Step 8: Write a policy to allow select++Our policy will need to know who our currently logged in user is to determine whether or not they should have access. Let's create a PostgreSQL function to extract the current user from our new JWT.++Navigate back to the Supabase dashboard, select SQL from the sidebar menu, and click **New query**. This will create a new query,, which will allow us to run any SQL against our Postgres database.++Write the following and click **Run**.++```sql+create or replace function auth.user_id() returns text as $$+ select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text;+$$ language sql stable;+```++You should see the output `Success, no rows returned`. This created a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload.++> Note: To learn more about PostgreSQL functions, check out this [deep dive video](https://www.youtube.com/watch?v=MJZCCpCYEqk).++Let's create a policy that checks whether this user is the owner of an expense.++Select **Authentication** from the Supabase sidebar menu, click **Policies**, then **New Policy**.++++From the modal, select **For full customization create a policy from scratch** and add the following.++++This policy is calling the function we just created to get the currently logged in user's `user_id` `auth.user_id()` and checking whether this matches the `user_id` column for the current expense. If it does, then it will allow the user to select it, otherwise it will continue to deny.++Click Review and then Save policy. After you've saved, click Enable RLS on the table to enable the policy we just created.++> Note: To learn more about RLS and policies, check out this [video](https://www.youtube.com/watch?v=Ow_Uzedfohk).++The last thing we need to do is update the `user_id` columns for our existing expenses.++Head back to the Supabase dashboard, and select Table editor from the sidebar. You will notice each entry has `user_id` set to `NULL`. We need to update this value to the proper `user_id`.++++To get the `user_id` for our Stytch user, you can pull it from the welcome page in our example app (eg `user-test-61497d40-f957-45cd-a6c8-5408d22e93bc`).++++Update each row in Supabase to this `user_id`.++++Return to `localhost:3000`, and you will see your expenses listed.++++We now have a basic expense tracker application powered by Stytch, Supabase, and Next.js. From here you could add additional features like adding, editing, and organizing your expenses further.++> Note: You can find a completed version of this project on [Github](https://github.com/stytchauth/stytch-nextjs-supabase).++## Optional: Add Google One Tap++In this optional step, we will extend our application to allow users to login with Google One Tap in addition to Email magic links.++You will need to follow the first four steps of [this guide](https://stytch.com/docs/one-tap-guide?utm_source=supabase&utm_medium=guide) to create a Google project, set up Google OAuth consent, and configure credentials and redirect URLs.++First, we will make some adjustments to the `StytchLogin` component. We will update the configuration, so that it uses both Google OAuth, and Email magic links.++```jsx+// components/StytchLogin.js+import React from 'react'+import { Stytch } from '@stytch/stytch-react'++const stytchConfig = {+ loginOrSignupView: {+ products: ['oauth', 'emailMagicLinks'],+ oauthOptions: {+ providers: [+ {+ type: 'google',+ one_tap: true,+ position: 'embedded',+ },+ ],+ loginRedirectURL: 'http://localhost:3000/api/authenticate?type=oauth',+ signupRedirectURL: 'http://localhost:3000/api/authenticate?type=oauth',+ },+ emailMagicLinksOptions: {+ loginRedirectURL: 'http://localhost:3000/api/authenticate',+ loginExpirationMinutes: 30,+ signupRedirectURL: 'http://localhost:3000/api/authenticate',+ signupExpirationMinutes: 30,+ createUserAsPending: true,+ },+ },+ style: {+ fontFamily: '"Helvetica New", Helvetica, sans-serif',+ width: '321px',+ primaryColor: '#0577CA',+ },+}++const StytchLogin = ({ publicToken }) => {+ return (+ <Stytch+ publicToken={publicToken}+ loginOrSignupView={stytchConfig.loginOrSignupView}+ style={stytchConfig.style}+ />+ )+}++export default StytchLogin+```++We also need to make an adjustment to the function `authenticateTokenStartSession` in `stytchLogic.js`. Stytch has separate authentication endpoints for Email magic links and OAuth, so we need to route our token correctly.++```jsx+// utils/stytchLogic.js++// leave the rest of the file contents as is+export const authenticateTokenStartSession = async (req, res) => {+ const { token, type } = req.query+ let sessionToken+ try {+ const stytchClient = loadStytch()+ if (type == 'oauth') {+ const resp = await stytchClient.oauth.authenticate(token, {+ session_duration_minutes: 30,+ session_management_type: 'stytch',+ })+ sessionToken = resp.session.stytch_session.session_token+ } else {+ const resp = await stytchClient.magicLinks.authenticate(token, {+ session_duration_minutes: 30,+ })+ sessionToken = resp.session_token+ }+ } catch (error) {+ console.log(error)+ const errorString = JSON.stringify(error)+ return res.status(400).json({ errorString })+ }++ setCookies(SESSION_COOKIE, sessionToken, {+ req,+ res,+ maxAge: 60 * 60 * 24,+ secure: true,+ })++ return res.redirect('/')+}+```++With these two changes you will now have a working Google One Tap authentication method along with email magic links.++++## Resources++- [Stytch blog](https://stytch.com/blog?utm_source=supabase&utm_medium=guide)+- [Stytch documentation](https://stytch.com/docs?utm_source=supabase&utm_medium=guide)diff --git a/apps/temp-docs/docs/guides/integrations/supertokens.mdx b/apps/temp-docs/docs/guides/integrations/supertokens.mdxnew file mode 100644index 00000000000..c532f3b0d14--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/supertokens.mdx@@ -0,0 +1,402 @@+---+id: supertokens+title: 'SuperTokens'+description: 'Create a Next.js application secured by SuperTokens and PostgreSQL Row Level Security.'+---++[SuperTokens](https://www.supertokens.com) is an open source authentication solution which provides many stratergies for authenticating and managing users. You can use the managed service for easy setup or you can self host the solution to have complete control over your data.++In this guide we will build a simple web application using SuperTokens, Supabase, and Next.js. You will be able to sign up using SuperTokens and your email and user ID will be stored in Supabase. Once authenticated the frontend will be able to query Supabase and retrieve the user's email. Our example app will be using the [Email-Password and Social Login](https://supertokens.com/docs/thirdpartyemailpassword/introduction) recipe for authentication and session management.++We will use Supabase to store and authorize access to user data. Supabase makes it simple to setup Row Level Security(RLS) policies which ensure users can only read and write data that belongs to them.++### Demo App++You can find a demo app using SuperTokens, Supabase and Nexts.js on [Github](https://github.com/supertokens/supertokens-auth-react/tree/master/examples/with-supabase)++## Step 1: Create a new Supabase project++From your [Supabase dashboard](https://app.supabase.com/), click `New project`.++Enter a `Name` for your Supabase project.++Enter a secure `Database Password`.++Select the same `Region` you host your app's backend in.++Click `Create new project`.++++## Step 2: Creating tables in Supabase++From the sidebar menu in the [Supabase dashboard](https://app.supabase.com/), click `Table editor`, then `New table`.++Enter `users` as the `Name` field.++Select `Enable Row Level Security (RLS)`.++Remove the default columns++Create two new columns:++- `user_id` as `varchar` as primary key+- `email` as `varchar`++Click `Save` to create the new table.++++## Step 3: Setup your Next.js App with SuperTokens.++Since the scope of this guide is limited to the intergration between SuperTokens and Supabase, you can refer to the SuperTokens website to see [how to setup your Next.js app with SuperTokens](https://supertokens.com/docs/thirdpartyemailpassword/nextjs/about).++Once you finish setting up your app, you will be greeted with the following screen++++## Step 4: Creating a Supabase JWT to access Supabase++In our Nextjs app when a user signs up, we want to store the user's email in Supabase. We would then retrieve this email from Supabase and display it on our frontend.++To use the Supabase client to query the database we will need to create a JWT signed with your Supabase app's signing secret. This JWT will also need to contain the user's userId so Supabase knows an authenticated user is making the request.++To create this flow we will need to modify SuperTokens so that, when a user signs up or signs in, a JWT signed with Supabase's signing secret is created and attached to the user's session. Attaching the JWT to the user's session will allow us to retrieve the Supabase JWT on the frontend and backend (post session verification), using which we can query Supabase.++We want to create a Supabase JWT when we are creating a SuperTokens' session. This can be done by overriding the `createNewSession` function in your backend config.++```ts+// config/backendConfig.ts++import ThirdPartyEmailPasswordNode from "supertokens-node/recipe/thirdpartyemailpassword";+import SessionNode from "supertokens-node/recipe/session";+import { TypeInput } from "supertokens-node/lib/build/types";+import { appInfo } from "./appInfo";+import jwt from "jsonwebtoken";++let backendConfig = (): TypeInput => {+ return {+ framework: "express",+ supertokens: {+ connectionURI: "https://try.supertokens.com",+ },+ appInfo,+ recipeList: [+ ThirdPartyEmailPasswordNode.init({...}),+ SessionNode.init({+ override: {+ functions: (originalImplementation) => {+ return {+ ...originalImplementation,+ // We want to create a JWT which contains the users userId signed with Supabase's secret so+ // it can be used by Supabase to validate the user when retrieving user data from their service.+ // We store this token in the accessTokenPayload so it can be accessed on the frontend and on the backend.+ createNewSession: async function (input) {+ const payload = {+ userId: input.userId,+ exp: Math.floor(Date.now() / 1000) + 60 * 60,+ };++ const supabase_jwt_token = jwt.sign(payload, process.env.SUPABASE_SIGNING_SECRET);++ input.accessTokenPayload = {+ ...input.accessTokenPayload,+ supabase_token: supabase_jwt_token,+ };++ return await originalImplementation.createNewSession(input);+ },+ };+ },+ },+ }),+ ],+ isInServerlessEnv: true,+ };+};++```++As seen above, we will be using the `jsonwebtoken` library to create a JWT signed with Supabase's signing secret whose payload contains the user's userId.++We will be storing this token in the `accessTokenPayload` which will essentially allow us to access the `supabase_token` on the frontend and backend whilst the user is logged in.++## Step 5: Creating a Supabase client++Create a new file called `utils/supabase.ts` and add the following:++```ts+// utils/supabase.ts++import { createClient } from '@supabase/supabase-js'++const getSupabase = (access_token) => {+ const supabase = createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.NEXT_PUBLIC_SUPABASE_KEY+ )++ supabase.auth.session = () => ({+ access_token,+ })++ return supabase+}++export { getSupabase }+```++This will be our client for talking to Supabase. We can pass it an `access_token` and it will be attached to our request. This `access_token` is the same as the `supabase_token` we had created earlier.++## Step 6: Inserting users into Supabase when they sign up:++In our example app there are two ways for signing up a user. Email-Password and Social Login based authentication. We will need to override both these APIs such that when a user signs up, their email mapped to their userId is stored in Supabase.++```ts+// config/backendConfig.ts++import ThirdPartyEmailPasswordNode from "supertokens-node/recipe/thirdpartyemailpassword";+import SessionNode from "supertokens-node/recipe/session";+import { TypeInput } from "supertokens-node/lib/build/types";+import { appInfo } from "./appInfo";+import jwt from "jsonwebtoken";+import { getSupabase } from "../utils/supabase";++let backendConfig = (): TypeInput => {+ return {+ framework: "express",+ supertokens: {+ connectionURI: "https://try.supertokens.com",+ },+ appInfo,+ recipeList: [+ ThirdPartyEmailPasswordNode.init({+ providers: [...],+ override: {+ apis: (originalImplementation) => {+ return {+ ...originalImplementation,+ // the thirdPartySignInUpPost function handles sign up/in via Social login+ thirdPartySignInUpPOST: async function (input) {+ if (originalImplementation.thirdPartySignInUpPOST === undefined) {+ throw Error("Should never come here");+ }++ // call the sign up/in api for social login+ let response = await originalImplementation.thirdPartySignInUpPOST(input);++ // check that there is no issue with sign up and that a new user is created+ if (response.status === "OK" && response.createdNewUser) {++ // retrieve the accessTokenPayload from the user's session+ const accessTokenPayload = response.session.getAccessTokenPayload();++ // create a supabase client with the supabase_token from the accessTokenPayload+ const supabase = getSupabase(accessTokenPayload.supabase_token);++ // store the user's email mapped to their userId in Supabase+ const { error } = await supabase+ .from("users")+ .insert({ email: response.user.email, user_id: response.user.id });++ if (error !== null) {++ throw error;+ }+ }++ return response;+ },+ // the emailPasswordSignUpPOST function handles sign up via Email-Password+ emailPasswordSignUpPOST: async function (input) {+ if (originalImplementation.emailPasswordSignUpPOST === undefined) {+ throw Error("Should never come here");+ }++ let response = await originalImplementation.emailPasswordSignUpPOST(input);++ if (response.status === "OK") {++ // retrieve the accessTokenPayload from the user's session+ const accessTokenPayload = response.session.getAccessTokenPayload();++ // create a supabase client with the supabase_token from the accessTokenPayload+ const supabase = getSupabase(accessTokenPayload.supabase_token);++ // store the user's email mapped to their userId in Supabase+ const { error } = await supabase+ .from("users")+ .insert({ email: response.user.email, user_id: response.user.id });++ if (error !== null) {++ throw error;+ }+ }++ return response;+ },+ };+ },+ },+ }),+ SessionNode.init({...}),+ ],+ isInServerlessEnv: true,+ };+};++```++As seen above, we will be overriding the `emailPasswordSignUpPOST` and `thirdPartySignInUpPOST` APIs such that if a user signs up, we retrieve the Supabase JWT (which we created in the `createNewSession` function) from the user's accessTokenPayload and send a request to Supabase to insert the email-userid mapping.++## Step 7: Retrieving the user's email on the frontend++Now that our backend is setup we can modify our frontend to retrieve the user's email from Supabase.++```tsx+// pages/index.tsx++import React, { useState, useEffect } from 'react'+import Head from 'next/head'+import styles from '../styles/Home.module.css'+import ThirdPartyEmailPassword, {+ ThirdPartyEmailPasswordAuth,+} from 'supertokens-auth-react/recipe/thirdpartyemailpassword'+import dynamic from 'next/dynamic'+import { useSessionContext } from 'supertokens-auth-react/recipe/session'+import { getSupabase } from '../utils/supabase'++export default function Home() {+ return (+ // We will wrap the ProtectedPage component with ThirdPartyEmailPasswordAuth so only an+ // authenticated user can access it. This will also allow us to access the users session information+ // within the component.+ <ThirdPartyEmailPasswordAuth>+ <ProtectedPage />+ </ThirdPartyEmailPasswordAuth>+ )+}++function ProtectedPage() {+ // retrieve the authenticated user's accessTokenPayload and userId from the sessionContext+ const { accessTokenPayload, userId } = useSessionContext()++ if (sessionContext.loading === true) {+ return null+ }++ const [userEmail, setEmail] = useState('')+ useEffect(() => {+ async function getUserEmail() {+ // retrieve the supabase client who's JWT contains users userId, this will be+ // used by supabase to check that the user can only access table entries which contain their own userId+ const supabase = getSupabase(accessTokenPayload.supabase_token)++ // retrieve the user's name from the users table whose email matches the email in the JWT+ const { data } = await supabase+ .from('users')+ .select('email')+ .eq('user_id', userId)++ if (data.length > 0) {+ setEmail(data[0].email)+ }+ }+ getUserEmail()+ }, [])++ return (+ <div className={styles.container}>+ <Head>+ <title>SuperTokens 💫</title>+ <link rel="icon" href="/favicon.ico" />+ </Head>++ <main className={styles.main}>+ <p className={styles.description}>+ You are authenticated with SuperTokens! (UserId: {userId})+ <br />+ Your email retrieved from Supabase: {userEmail}+ </p>+ </main>+ </div>+ )+}+```++As seen above we will be using SuperTokens `useSessionContext` hook to retrieve the authenticated user's `userId` and `accessTokenPayload`. Using React's `useEffect` hook we can use the Supabase client to retrieve the user's email from Supabase using the JWT retrieved from the user's `accessTokenPayload` and their `userId`.++## Step 8: Create Policies to enforce Row Level Security for Select and Insert requests++To enforce Row Level Security for the `Users` table we will need to create policies for Select and Insert requests.++These polices will retrieve the userId from the JWT and check if it matches the userId in the Supabase table++To do this we will need a PostgreSQL function to extract the userId from the JWT.++The payload in the JWT will have the following structure:++```+// JWT payload+{+ userId,+ exp+}+```++To create the PostgreSQL function, lets navigate back to the Supabase dashboard, select `SQL` from the sidebar menu, and click `New query`. This will create a new query called `new sql snippet`, which will allow us to run any SQL against our Postgres database.++Write the following and click `Run`.++```sql+create or replace function auth.user_id() returns text as $$+ select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text;+$$ language sql stable;+```++This will create a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload.++### SELECT query policy++Our first policy will check whether the user is the owner of the email.++Select `Authentication` from the Supabase sidebar menu, click `Policies`, and then `New Policy` on the `Users` table.++++From the modal, select `Create a policy from scratch` and add the following.++++This policy is calling the PostgreSQL function we just created to get the currently logged in user's ID `auth.user_id()` and checking whether this matches the `user_id` column for the current `email`. If it does, then it will allow the user to select it, otherwise it will continue to deny.++Click `Review` and then `Save policy`.++### INSERT query policy++Our second policy will check whether the `user_id` being inserted is the same as the `userId` in the JWT.++Create another policy and add the following:++++Similar to the previous policy we are calling the PostgreSQL function we created to get the currently logged in user's ID `auth.user_id()` and check whether this matches the `user_id` column for the row we are trying to insert. If it does, then it will allow the user to insert the row, otherwise it will continue to deny.++Click `Review` and then `Save policy`.++## Step 9: Test your changes++You can now sign up and you should see the following screen:++++If you navigate to your table you should see a new row with the user's `user_id` and `email`.++++## Resources++- [SuperTokens](https://supertokens.com/) official website.+- [SuperTokens community](https://supertokens.com/discord).+- [SuperTokens documentation](https://supertokens.com/docs/guides).diff --git a/apps/temp-docs/docs/guides/integrations/vercel.mdx b/apps/temp-docs/docs/guides/integrations/vercel.mdxnew file mode 100644index 00000000000..846a4bec3cb--- /dev/null+++ b/apps/temp-docs/docs/guides/integrations/vercel.mdx@@ -0,0 +1,241 @@+---+id: vercel+title: 'Vercel'+description: The fastest way to get up and running with an application that uses Supabase is with Vercel's Next.js starter and Supabase integration.+---++This guide steps through using Vercel's dashboard to create a Next.js project integrated with Supabase. To further streamline the process, we will be using the Next.js starter template, which can be automatically forked to a new GitHub repo, without leaving the dashboard!++If you don’t have a Vercel account, create one [here](https://vercel.com/signup).++## Step 1: Create a Supabase project++This guide could use an existing Supabase project, but to create the `todo` demo from scratch, navigate to [Supabase](https://app.supabase.com/), click `Sign In` and authenticate with GitHub to login or register a new account.++From the Supabase dashboard, click `New project` and select an organization.++> Note: You may need to create an organization first.++Give your project a `name`, `password`, select a `region` close to your potential users and click `Create new project`.++++Supabase will take a couple of minutes to configure the infrastructure.++Once this is finished, navigate to `SQL Editor` from the sidebar menu and click `New query`.++This will create a new SQL snippet called "New Query". Copy and paste the following and click `Run`.++```sql+create table todos (+ id bigint generated by default as identity primary key,+ title text,+ is_complete boolean default false,+ created_at timestamp with time zone default timezone('utc'::text, now()) not null+);++alter table todos enable row level security;++create policy "Anyone can view todos" on todos for+ select using (true);++create policy "Anyone can add new todos" on todos for+ insert with check (true);++insert into todos(title)+values+ ('Create Supabase project'),+ ('Create Vercel project'),+ ('Install Supabase integration');+```++This will create a new todos table, enable row level security, add policies for selecting and inserting data, and add some example rows.++> Note: To simplify this example, we are allowing anyone to `select` and `insert` rows on the `todos` table. Usually, these actions would be locked down to only allow logged in users to perform them. Check out [this video](https://www.youtube.com/watch?v=Ow_Uzedfohk) to learn more about Row Level Security and policies.++## Step 2: Create Vercel project++From your [Vercel dashboard](https://vercel.com/dashboard), click `New Project`.++++Under the `Clone Template` menu, click `Next.js`.++++In the `Create Git Repository` section, click `GitHub`, select your username under `GIT SCOPE`, enter a name for your project, choose whether you want your repo `private` or `public`, and click `Create`.++++This will create a new GitHub repository, clone and commit the Next.js starter project, then build and deploy your new project to Vercel.++Once you have been redirected to the `Congratulations` screen, click `Go to Dashboard`.++Navigate to `Settings`, `Integrations`, then click `Browse Marketplace`.++Search for `Supabase` and click the Supabase integration.++++Click `Add Integration`. Select your account from the `Vercel Scope` dropdown, and click `CONTINUE`.++++Choose `Specific Projects` and select your new Vercel project from the dropdown, and click `Add Integration`.++++From the Supabase popup, select your new Vercel Project and Supabase project from the dropdowns.++++## Step 3: Clone GitHub repo++The fastest way to get this project running locally is to clone the repo that Vercel created for us.++Navigate back to the Vercel project `Overview` page, and click `View Git Repository`.++++This will open the GitHub repo. From here, click the arrow next to `Code` and copy the url from the dropdown.++++Open a terminal window or CLI and run the following command to clone the GitHub repo.++```bash+git clone your-repo-url.git+```++Open the project in your code editor of choice, and update the contents of `pages/index.js` to the following:++```jsx+import styles from '../styles/Home.module.css'++export default function Home() {+ return <div className={styles.container}>working</div>+}+```++Run a local development server.++```bash+npm run dev+```++Navigate to `http://localhost:3000` to confirm the project is "working".++## Step 4: Pull environment variables from Vercel++First, we need to login to Vercel using their CLI tool.++```bash+npx vercel login+```++This will ask if we are happy to install `vercel`. Type `y` and hit `Enter`.++We will then need to authenticate Vercel by selecting `Continue with GitHub`.++This will open a browser window where you need to authenticate with your GitHub account.++Next, we need to link our Vercel project.++```bash+npx vercel link+```++Step through the prompts to link the Vercel project.++++Copy the environment variables from our Vercel project.++```bash+npx vercel env pull+```++This will create a `.env` file containing our Supabase environment variables. Rename this file to `.env.local` to automatically ignore it from git.++## Step 5: Install Supabase.js++Install the `supabase-js` library.++```bash+npm i @supabase/supabase-js+```++Create a new file called `/utils/supabase.js` and add the following.++```jsx+import { createClient } from '@supabase/supabase-js'++export default createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY+)+```++Create a new file called `/components/NewTodo.js` and add the following.++```jsx+import { useState } from 'react'+import supabase from '../utils/supabase'++export default ({ reload }) => {+ const [title, setTitle] = useState('')++ const addTodo = async (e) => {+ e.preventDefault()+ await supabase.from('todos').insert({ title })+ reload()+ setTitle('')+ }++ return (+ <form onSubmit={addTodo}>+ <input value={title} onChange={(e) => setTitle(e.target.value)} />+ </form>+ )+}+```++This component will be responsible for writing a new `todo` to Supabase.++Let's import our new component in `pages/index.js` and display a list of todos.++```jsx+import { useState, useEffect } from 'react'+import styles from '../styles/Home.module.css'+import supabase from '../utils/supabase'+import NewTodo from '../components/NewTodo'++export default function Home() {+ const [todos, setTodos] = useState([])++ const fetchTodos = async () => {+ const { data } = await supabase.from('todos').select('*')+ setTodos(data)+ }++ useEffect(() => {+ fetchTodos()+ }, [])++ return (+ <div className={styles.container}>+ <NewTodo reload={fetchTodos} />+ {todos.map((todo) => (+ <p key={todo.id}>{todo.title}</p>+ ))}+ </div>+ )+}+```++## Resources++- [Vercel official website](https://vercel.com).+- [Vercel blog](https://vercel.com/blog).+- [Vercel docs](https://vercel.com/docs).+- [Vercel Integration docs](https://vercel.com/docs/integrations)diff --git a/apps/temp-docs/docs/guides/migrations/firebase-auth.mdx b/apps/temp-docs/docs/guides/migrations/firebase-auth.mdxnew file mode 100644index 00000000000..d4e4d7e55df--- /dev/null+++ b/apps/temp-docs/docs/guides/migrations/firebase-auth.mdx@@ -0,0 +1,90 @@+---+id: firebase-auth+title: 'Firebase Auth Migration'+description: 'Migrate Firebase auth users to a Supabase project.'+sidebar_label: Firebase Auth+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++Supabase provides several [tools](https://github.com/supabase-community/firebase-to-supabase/tree/main/auth) to help migrate auth users from a Firebase project to a Supabase project. There are two parts to the migration process:++- `firestoreusers2json` ([TypeScript](https://github.com/supabase-community/firebase-to-supabase/blob/main/auth/firestoreusers2json.ts), [JavaScript](https://github.com/supabase-community/firebase-to-supabase/blob/main/auth/firestoreusers2json.js)) exports users from an existing Firebase project to a `.json` file on your local system.+- `import_users` ([TypeScript](https://github.com/supabase-community/firebase-to-supabase/blob/main/auth/import_users.ts), [JavaScript](https://github.com/supabase-community/firebase-to-supabase/blob/main/auth/import_users.js)) imports users from a saved `.json` file into your Supabase project (inserting those users into the `auth.users` table of your `PostgreSQL` database instance).++## Set up the migration tool {#set-up-migration-tool}++1. Clone the [firebase-to-supabase](https://github.com/supabase-community/firebase-to-supabase) repository:++```+git clone https://github.com/supabase-community/firebase-to-supabase.git+```++1. In the `/auth` directory, create a file named `supabase-service.json` with the following contents:++```json+{+ "host": "database.server.com",+ "password": "secretpassword",+ "user": "postgres",+ "database": "postgres",+ "port": 5432+}+```++1. Go to the [Database settings](https://app.supabase.com/project/_/settings/database) for your project in the Supabase Dashboard.+1. Under **Connection Info**, copy the Host string and replace the entry in your `supabase-service.json` file.+1. Enter the password you used when you created your Supabase project in the `password` entry in the `supabase-service.json` file.++## Generate a Firebase private key {#generate-firebase-private-key}++1. Log in to your [Firebase Console](https://console.firebase.google.com/project) and open your project.+1. Click the gear icon next to **Project Overview** in the sidebar and select **Project Settings**.+1. Click **Service Accounts** and select **Firebase Admin SDK**.+1. Click **Generate new private key**.+1. Rename the downloaded file to `firebase-service.json`.++## Save your Firebase password hash parameters {#save-firebase-hash-parameters}++1. Log in to your [Firebase Console](https://console.firebase.google.com/project) and open your project.+1. Select **Authentication** (Build section) in the sidebar.+1. Select **Users** in the top menu.+1. At the top right of the users list, open the menu (3 dots) and click **Password hash parameters**.+1. Copy and save the parameters for `base64_signer_key`, `base64_salt_separator`, `rounds`, and `mem_cost`.++```bash title="Sample password hash parameters"+hash_config {+ algorithm: SCRYPT,+ base64_signer_key: XXXX/XXX+XXXXXXXXXXXXXXXXX+XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==,+ base64_salt_separator: Aa==,+ rounds: 8,+ mem_cost: 14,+}+```++## Command line options++### Dump Firestore users to a JSON file {#dump-firestore-users}++`node firestoreusers2json.js [<filename.json>] [<batch_size>]`++- `filename.json`: (optional) output filename (defaults to `./users.json`)+- `batchSize`: (optional) number of users to fetch in each batch (defaults to 100)++### Import JSON users file to Supabase Auth (PostgreSQL: auth.users) {#import-json-users-file}++`node import_users.js <path_to_json_file> [<batch_size>]`++- `path_to_json_file`: full local path and filename of .json input file (of users)+- `batch_size`: (optional) number of users to process in a batch (defaults to 100)++## Notes++For more advanced migrations, including the use of a middleware server component for verifying a user's existing Firebase password and updating that password in your Supabase project the first time a user logs in, see the [firebase-to-supabase repo](https://github.com/supabase-community/firebase-to-supabase/tree/main/auth).++## Resources++- [Supabase vs Firebase](https://supabase.com/alternatives/supabase-vs-firebase)+- [Firestore Data Migration](https://supabase.com/docs/guides/migrations/firestore-data)+- [Firestore Storage Migration](https://supabase.com/docs/guides/migrations/firebase-storage)diff --git a/apps/temp-docs/docs/guides/migrations/firebase-storage.mdx b/apps/temp-docs/docs/guides/migrations/firebase-storage.mdxnew file mode 100644index 00000000000..6b2904b70f5--- /dev/null+++ b/apps/temp-docs/docs/guides/migrations/firebase-storage.mdx@@ -0,0 +1,64 @@+---+id: firebase-storage+title: 'Firebase Storage Migration'+description: 'Migrate Firebase Storage files to Supabase Storage.'+sidebar_label: Firebase Storage+---++Supabase provides several [tools](https://github.com/supabase-community/firebase-to-supabase/tree/main/storage) to convert storage files from Firebase Storage to Supabase Storage. Conversion is a two-step process:++1. Files are downloaded from a Firebase storage bucket to a local filesystem.+2. Files are uploaded from the local filesystem to a Supabase storage bucket.++## Set up the migration tool {#set-up-migration-tool}++1. Clone the [firebase-to-supabase](https://github.com/supabase-community/firebase-to-supabase) repository:++```+git clone https://github.com/supabase-community/firebase-to-supabase.git+```++1. In the `/storage` directory, rename [supabase-keys-sample.js](https://github.com/supabase-community/firebase-to-supabase/blob/main/storage/supabase-keys-sample.js) to `supabase-keys.js`.+1. Go to your Supabase project's [API settings](https://app.supabase.com/project/_/settings/api) in the Dashboard.+1. Copy the **Project URL** and update the `SUPABASE_URL` value in `supabase-keys.js`.+1. Under **Project API keys**, copy the **service_role** key and update the `SUPABASE_KEY` value in `supabase-keys.js`.++## Generate a Firebase private key {#generate-firebase-private-key}++1. Log in to your [Firebase Console](https://console.firebase.google.com/project) and open your project.+1. Click the gear icon next to **Project Overview** in the sidebar and select **Project Settings**.+1. Click **Service Accounts** and select **Firebase Admin SDK**.+1. Click **Generate new private key**.+1. Rename the downloaded file to `firebase-service.json`.++## Command line options++### Download Firestore Storage bucket to a local filesystem folder {#download-firestore-storage-bucket}++`node download.js <prefix> [<folder>] [<batchSize>] [<limit>] [<token>]`++- `<prefix>`: The prefix of the files to download. To process the root bucket, use an empty prefix: "".+- `<folder>`: (optional) Name of subfolder for downloaded files. The selected folder is created as a subfolder of the current folder (e.g., `./downloads/`). The default is `downloads`.+- `<batchSize>`: (optional) The default is 100.+- `<limit>`: (optional) Stop after processing this many files. For no limit, use `0`.+- `<token>`: (optional) Begin processing at this pageToken.++To process in batches using multiple command-line executions, you must use the same parameters with a new `<token>` on subsequent calls. Use the token displayed on the last call to continue the process at a given point.++### Upload files to Supabase Storage bucket {#upload-to-supabase-storage-bucket}++`node upload.js <prefix> <folder> <bucket>`++- `<prefix>`: The prefix of the files to download. To process all files, use an empty prefix: "".+- `<folder>`: Name of subfolder of files to upload. The selected folder is read as a subfolder of the current folder (e.g., `./downloads/`). The default is `downloads`.+- `<bucket>`: Name of the bucket to upload to.++:::note+If the bucket doesn't exist, it's created as a `non-public` bucket. You must set permissions on this new bucket in the [Supabase Dashboard](https://app.supabase.com/project/_/storage/buckets) before users can download any files.+:::++## Resources++- [Supabase vs Firebase](https://supabase.com/alternatives/supabase-vs-firebase)+- [Firestore Data Migration](https://supabase.com/docs/guides/migrations/firestore-data)+- [Firebase Auth Migration](https://supabase.com/docs/guides/migrations/firebase-auth)diff --git a/apps/temp-docs/docs/guides/migrations/firestore-data.mdx b/apps/temp-docs/docs/guides/migrations/firestore-data.mdxnew file mode 100644index 00000000000..66c01fd1405--- /dev/null+++ b/apps/temp-docs/docs/guides/migrations/firestore-data.mdx@@ -0,0 +1,210 @@+---+id: firestore-data+title: 'Firestore Data Migration'+description: 'Migrate your Firebase Firestore database to a Supabase Postgres database.'+sidebar_label: Firestore Data+---++Supabase provides several [tools](https://github.com/supabase-community/firebase-to-supabase/tree/main/firestore) to convert data from a Firebase Firestore database to a Supabase PostgreSQL database. The process copies the entire contents of a single Firestore `collection` to a single PostgreSQL `table`.++The Firestore `collection` is "flattened" and converted to a table with basic columns of one of the following types: `text`, `numeric`, `boolean`, or `jsonb`. If your structure is more complex, you can write a program to split the newly-created `json` file into multiple, related tables before you import your `json` file(s) to Supabase.++## Set up the migration tool {#set-up-migration-tool}++1. Clone the [firebase-to-supabase](https://github.com/supabase-community/firebase-to-supabase) repository:++```+git clone https://github.com/supabase-community/firebase-to-supabase.git+```++1. In the `/firestore` directory, create a file named `supabase-service.json` with the following contents:++```json+{+ "host": "database.server.com",+ "password": "secretpassword",+ "user": "postgres",+ "database": "postgres",+ "port": 5432+}+```++1. Go to the [Database settings](https://app.supabase.com/project/_/settings/database) for your project in the Supabase Dashboard.+1. Under **Connection Info**, copy the Host string and replace the entry in your `supabase-service.json` file.+1. Enter the password you used when you created your Supabase project in the `password` entry in the `supabase-service.json` file.++## Generate a Firebase private key {#generate-firebase-private-key}++1. Log in to your [Firebase Console](https://console.firebase.google.com/project) and open your project.+1. Click the gear icon next to **Project Overview** in the sidebar and select **Project Settings**.+1. Click **Service Accounts** and select **Firebase Admin SDK**.+1. Click **Generate new private key**.+1. Rename the downloaded file to `firebase-service.json`.++## Command line options++### List all Firestore collections++`node collections.js`++### Dump Firestore collection to JSON file++`node firestore2json.js <collectionName> [<batchSize>] [<limit>]`++- `batchSize` (optional) defaults to 1000+- output filename is `<collectionName>.json`+- `limit` (optional) defaults to 0 (no limit)++#### Customize the JSON file with hooks++You can customize the way your JSON file is written using a [custom hook](#custom-hooks). A common use for this is to "flatten" the JSON file, or to split nested data into separate, related database tables. For example, you could take a Firestore document that looks like this:++```json title="Firestore document"+[{ "user": "mark", "score": 100, "items": ["hammer", "nail", "glue"] }]+```++And split it into two files (one table for users and one table for items):++```json title="Users table"+[{ "user": "mark", "score": 100 }]+```++```json title="Items table"+[+ { "user": "mark", "item": "hammer" },+ { "user": "mark", "item": "nail" },+ { "user": "mark", "item": "glue" }+]+```++### Import JSON file to Supabase (PostgreSQL) {#import-to-supabase}++`node json2supabase.js <path_to_json_file> [<primary_key_strategy>] [<primary_key_name>]`++- `<path_to_json_file>` The full path of the file you created in the previous step (`Dump Firestore collection to JSON file `), such as `./my_collection.json`+- `[<primary_key_strategy>]` (optional) Is one of:+ - `none` (default) No primary key is added to the table.+ - `smallserial` Creates a key using `(id SMALLSERIAL PRIMARY KEY)` (autoincrementing 2-byte integer).+ - `serial` Creates a key using `(id SERIAL PRIMARY KEY)` (autoincrementing 4-byte integer).+ - `bigserial` Creates a key using `(id BIGSERIAL PRIMARY KEY)` (autoincrementing 8-byte integer).+ - `uuid` Creates a key using `(id UUID PRIMARY KEY DEFAULT uuid_generate_v4())` (randomly generated UUID).+ - `firestore_id` Creates a key using `(id TEXT PRIMARY KEY)` (uses existing `firestore_id` random text as key).+- `[<primary_key_name>]` (optional) Name of primary key. Defaults to "id".++## Custom hooks++Hooks are used to customize the process of exporting a collection of Firestore documents to JSON. They can be used for:++- Customizing or modifying keys+- Calculating data+- Flattening nested documents into related SQL tables++### Write a custom hook++#### Create a .js file for your collection++If your Firestore collection is called `users`, create a file called `users.js` in the current folder.++#### Construct your .js file++The basic format of a hook file looks like this:++```js+module.exports = (collectionName, doc, recordCounters, writeRecord) => {+ // modify the doc here+ return doc+}+```++##### Parameters++- `collectionName`: The name of the collection you are processing.+- `doc`: The current document (JSON object) being processed.+- `recordCounters`: An internal object that keeps track of how many records have been processed in each collection.+- `writeRecord`: This function automatically handles the process of writing data to other JSON files (useful for "flatting" your document into separate JSON files to be written to separate database tables). `writeRecord` takes the following parameters:+ - `name`: Name of the JSON file to write to.+ - `doc`: The document to write to the file.+ - `recordCounters`: The same `recordCounters` object that was passed to this hook (just passes it on).++### Examples++#### Add a new (unique) numeric key to a collection++```js+module.exports = (collectionName, doc, recordCounters, writeRecord) => {+ doc.unique_key = recordCounter[collectionName] + 1+ return doc+}+```++#### Add a timestamp of when this record was dumped from Firestore++```js+module.exports = (collectionName, doc, recordCounters, writeRecord) => {+ doc.dump_time = new Date().toISOString()+ return doc+}+```++#### Flatten JSON into separate files++Flatten the `users` collection into separate files:++```json+[+ {+ "uid": "abc123",+ "name": "mark",+ "score": 100,+ "weapons": ["toothpick", "needle", "rock"]+ },+ {+ "uid": "xyz789",+ "name": "chuck",+ "score": 9999999,+ "weapons": ["hand", "foot", "head"]+ }+]+```++The `users.js` hook file:++```js+module.exports = (collectionName, doc, recordCounters, writeRecord) => {+ for (let i = 0; i < doc.weapons.length; i++) {+ const weapon = {+ uid: doc.uid,+ weapon: doc.weapons[i],+ }+ writeRecord('weapons', weapon, recordCounters)+ }+ delete doc.weapons // moved to separate file+ return doc+}+```++The result is two separate JSON files:++```json title="users.json"+[+ { "uid": "abc123", "name": "mark", "score": 100 },+ { "uid": "xyz789", "name": "chuck", "score": 9999999 }+]+```++```json title="weapons.json"+[+ { "uid": "abc123", "weapon": "toothpick" },+ { "uid": "abc123", "weapon": "needle" },+ { "uid": "abc123", "weapon": "rock" },+ { "uid": "xyz789", "weapon": "hand" },+ { "uid": "xyz789", "weapon": "foot" },+ { "uid": "xyz789", "weapon": "head" }+]+```++## Resources++- [Supabase vs Firebase](https://supabase.com/alternatives/supabase-vs-firebase)+- [Firestore Storage Migration](https://supabase.com/docs/guides/migrations/firebase-storage)+- [Firebase Auth Migration](https://supabase.com/docs/guides/migrations/firebase-auth)diff --git a/apps/temp-docs/docs/guides/migrations/heroku.mdx b/apps/temp-docs/docs/guides/migrations/heroku.mdxnew file mode 100644index 00000000000..1cc4d043521--- /dev/null+++ b/apps/temp-docs/docs/guides/migrations/heroku.mdx@@ -0,0 +1,73 @@+---+id: heroku+title: 'Migrate from Heroku to Supabase'+description: 'Migrate your Heroku Postgres database to Supabase.'+sidebar_label: Heroku+---++Supabase is one of the best [free alternatives to Heroku Postgres](https://supabase.com/alternatives/supabase-vs-heroku-postgres). This guide shows how to migrate your Heroku Postgres database to Supabase. This migration requires the [pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html) and [psql](https://www.postgresql.org/docs/current/app-psql.html) CLI tools, which are installed automatically as part of the complete PostgreSQL installation package.++Alternatively, use the [Heroku to Supabase migration tool](https://migrate.supabase.com/) to migrate in just a few clicks.++## Quick demo++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/xsRhPMphtZ4"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Retrieve your Heroku database credentials {#retrieve-heroku-credentials}++1. Log in to your [Heroku account](https://heroku.com) and select the project you want to migrate.+1. Click **Resources** in the menu and select your **Heroku Postgres** database.+1. Click **Settings** in the menu.+1. Click **View Credentials** and save the following information:+ - Host (`$HEROKU_HOST`)+ - Database (`$HEROKU_DATABASE`)+ - User (`$HEROKU_USER`)+ - Password (`$HEROKU_PASSWORD`)++## Retrieve your Supabase Host {#retrieve-supabase-host}++1. If you're new to Supabase, [create a project](https://app.supabase.com).+1. Go to the [Database settings](https://app.supabase.com/project/_/settings/database) for your project in the Supabase Dashboard.+1. Under **Connection Info**, note your Host (`$SUPABASE_HOST`).++## Export your Heroku database to a file {#export-heroku-database}++Use `pg_dump` with your Heroku credentials to export your Heroku database to a file (e.g., `heroku_dump.sql`).++```+pg_dump --clean --if-exists --quote-all-identifiers \+ -h $HEROKU_HOST -U $HEROKU_USER -d $HEROKU_DATABASE \+ --no-owner --no-privileges > heroku_dump.sql+```++## Import the database to your Supabase project {#import-database-to-supabase}++Use `psql` to import the Heroku database file to your Supabase project.++```+psql -h $SUPABASE_HOST -U postgres -f heroku_dump.sql+```++## (Optional) Post processing {#post-processing}++If you're using GraphQL with your Supabase project, you may need to run the following SQL command in the Supabase Dashboard (SQL Editor) to make sure the new tables show up:++```sql+select graphql.rebuild_schema();+```++## Additional options++- To only migrate a single database schema, add the `--schema=PATTERN` parameter to your `pg_dump` command.+- To exclude a schema: `--exclude-schema=PATTERN`.+- To only migrate a single table: `--table=PATTERN`.+- To exclude a table: `--exclude-table=PATTERN`.++Run `pg_dump --help` for a full list of options.diff --git a/apps/temp-docs/docs/guides/platform/custom-domains.mdx b/apps/temp-docs/docs/guides/platform/custom-domains.mdxnew file mode 100644index 00000000000..bde2c3b847f--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/custom-domains.mdx@@ -0,0 +1,86 @@+---+id: custom-domains+title: Custom Domains+description: Configuring a Custom Domain for your Supabase project.+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'++:::note++Custom Domains are currently in beta, and are being slowly made available to projects.++:::++Custom domains allow you to present a branded experience to your users. You can also use a subdomain for the purposes of this guide.++To get started:++1. [Install](/docs/guides/cli) the Supabase CLI 1.10.1+.+1. [Log in](/docs/guides/cli/local-development#log-in-to-the-supabase-cli) to your Supabase account using the CLI.+1. Enable the Custom Domains add-on in the Billing page of the Dashboard.++## Configure a Custom Domain++This example assumes your Supabase project is `foobar` with a corresponding API URL `foobar.supabase.co` and configures a custom domain at `api.example.com`.++### <a id="cname-configure"></a>Configure a CNAME++Set up a CNAME record for `api.example.com`, resolving to `foobarbaz.supabase.co.`, with as low a TTL as possible.++### Configure TXT Verification++Use the `create` subcommand of the CLI to notify Supabase of your domain and retrieve TXT verification records:++```bash+supabase custom-hostname create --project-ref foobar --custom-hostname api.example.com --experimental+```++The output of the `create` command includes two TXT records[^1] you will need to set up, in order to verify your control over the domain in question,+and for us to issue SSL certificates for it. For example:++```+[...]+Required outstanding validation records:+ _cf-custom-hostname.api.example.com TXT -> 46BBC14D-D50A-409C-8DB5-F862CF5BA660+ api.example.com TXT -> ca3-F1HvR9i938OgVwpCFwi1jTsbhe1hvT0Ic3efPY3Q+```++[^1] One of the records requires you to *replace* the CNAME record set up in [the first step](#cname-configure) with a TXT record. You'll be able to restore it back to the CNAME after the verification process has been completed.++### Verify your domain++Set up both records as instructed, and then use the `reverify` command for the Supabase Platform to verify the records:++```bash+supabase custom-hostname reverify --project-ref foobarbaz --experimental+```++You might need to wait a few minutes before your updated DNS records are propagated, especially if the older records were using a high TTL.++### Activate your domain++The final activation step reconfigures your project to start serving traffic on your custom domain (`api.example.com`).+The auth service, in particular, will no longer work with the original URL (`foobar.supabase.co`).+As such, it is recommended that you schedule a downtime window of 20-30 minutes, depending on the complexity of your project, to update all the services that need to know about your custom domain:++- any client code (e.g., frontends, mobile apps)+- any OAuth providers (e.g., google, github)++Additionally, update the DNS configuration for `api.example.com` to once more use a CNAME record that resolves to `foobarbaz.supabase.co`.+Finally, you can use the `activate` subcommand to reconfigure your project:++```bash+supabase custom-hostname activate --project-ref foobarbaz --experimental+```++## Remove a Custom Domain++If you have a custom domain (`api.example.com`) set up for your Supabase project (ref `foobarbaz`, with assigned endpoints at `foobarbaz.supabase.co`), and would like to go back to using the Supabase-provisioned endpoints (`foobarbaz.supabase.co`), you can use the `delete` subcommand:++```bash+supabase custom-hostname delete --project-ref foobarbaz --experimental+```++As with the final activation stage of the process for setting up a custom domain, you'll need to update any references in your client code and OAuth providers from the custom domain to the Supabase-provisioned endpoints.diff --git a/apps/temp-docs/docs/guides/platform/disk-usage.mdx b/apps/temp-docs/docs/guides/platform/disk-usage.mdxnew file mode 100644index 00000000000..7c7854cf43b--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/disk-usage.mdx@@ -0,0 +1,25 @@+---+id: disk-usage+title: Disk space usage+description: Learn how database disk space usage is reported.+---++Database disk space usage refers to the _monthly average disk usage_, as reported by Postgres. This metric is reported in your project's [billing page](https://app.supabase.com/project/_/settings/billing) and is updated daily.++For an instantaneous live view of the DB disk space being used by your project, you can execute in Postgres:++```sql+SELECT SUM(pg_database_size(pg_database.datname)) / (1024 * 1024) as db_size_mb FROM pg_database;+```++This value is also reported in the [database settings page](https://app.supabase.com/project/_/settings/database).++## Vacuum operations++Postgres does not immediately reclaim the physical space used by dead tuples (i.e., deleted rows) in the DB. Instead, they are internally marked as removed until a [vacuum operation](https://www.postgresql.org/docs/current/routine-vacuuming.html) is executed. As a result, deleting data from your DB may not immediately reduce the reported disk usage.++:::note+Vacuum operations can temporarily increase resource utilization, which can adversely impact the observed performance of your project until the maintenance is completed.+:::++Supabase projects have automatic vacuuming enabled, which ensures that these operations are performed regularly to keep the database healthy and performant. However, it can be necessary to either [fine-tune](https://www.percona.com/blog/2018/08/10/tuning-autovacuum-in-postgresql-and-autovacuum-internals/) [the autovacuum parameters](https://www.enterprisedb.com/blog/postgresql-vacuum-and-analyze-best-practice-tips), or [manually initiate](https://www.postgresql.org/docs/current/sql-vacuum.html) vacuum operations. For example, running a manual vacuum after deleting large amounts of data from your DB could help reduce the reported disk usage by Postgres.diff --git a/apps/temp-docs/docs/guides/platform/logs.mdx b/apps/temp-docs/docs/guides/platform/logs.mdxnew file mode 100644index 00000000000..6810cce4433--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/logs.mdx@@ -0,0 +1,240 @@+---+id: logs+title: Logging+description: Getting started with Supabase Platform Log Browser+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import ThemedImage from '@theme/ThemedImage'+import useBaseUrl from '@docusaurus/useBaseUrl'++The Supabase Platform includes a Logs Explorer that allows log tracing and debugging. Log retention is based on your [project's pricing plan](https://supabase.com/pricing).++:::note+These features are not currently available for self-hosting and local development.<br/>+This is on the roadmap and you can follow the progress in the [Logflare repository](https://github.com/Logflare/logflare).+:::++## Product Logs++Supabase provides a logging interface specific to each product. You can use simple regular expressions for keywords and patterns to search log event messages. You can also export and download the log events matching your query as a spreadsheet.++<!--+To update the screenshots, ensure that at least one log line is selected to display the metadata. Can use meme.town as an example.+-->++<Tabs>+ <TabItem value="api" label="API" default>++[API logs](https://app.supabase.com/project/_/database/api-logs) show all network requests and response for the REST and GraphQL [APIs](../../guides/api).++++ </TabItem>+ <TabItem value="postgres" label="Postgres">++[Postgres logs](https://app.supabase.com/project/_/database/postgres-logs) show queries and activity for your [database](../../guides/database).++By default, query logs are disabled for all new Supabase projects, as they can reveal metadata about the contents of your database (e.g. table and column names). If you'd like to enable query logs, you can enable and configure the [pgAudit extension](https://www.pgaudit.org/):++- [Enable the pgAudit extension for your project](https://app.supabase.com/project/_/database/extensions)+- [Reboot the DB](https://app.supabase.com/project/_/settings/general); a "Fast database reboot" is sufficient, and faster than a full project restart+- Configure `pgaudit.log` to the [appropriate value](https://github.com/pgaudit/pgaudit/blob/master/README.md#pgauditlog)+- You should be able to view query logs in your [log explorer](https://app.supabase.com/project/_/database/postgres-logs) now++As an example, if you wanted to enable logs for writes and DDL statements for a single session, you could execute within the session:++```sql+set pgaudit.log = 'write, ddl';+```++To _permanently_ enable logs for all statements that relate to roles and privileges, you could execute (followed by a db reboot):++```sql+alter system set pgaudit.log to 'role';+```++To remove a system-wide setting, you can use (followed by a db reboot):++```sql+alter system reset pgaudit.log+```++++ </TabItem>+ <TabItem value="auth" label="Auth">++[Auth logs](https://app.supabase.com/project/_/auth/logs) show all server logs for your [Auth usage](../../guides/auth).++++ </TabItem>+ <TabItem value="storage" label="Storage">++[Storage logs](https://app.supabase.com/project/_/storage/logs) shows all server logs for your [Storage API](../../guides/storage).++++ </TabItem>+ <TabItem value="realtime" label="Realtime">++[Realtime logs](https://app.supabase.com/project/_/database/realtime-logs) show all server logs for your [Realtime API usage](../../guides/realtime).++++ </TabItem>+ <TabItem value="functions" label="Edge Functions">++For each [Edge Function](https://app.supabase.com/project/_/functions), logs are available under the following tabs:++**Invocations**++The Invocations tab displays the edge logs of function calls.++++**Logs**++The Logs tab displays logs emitted during function execution.++++ </TabItem>+</Tabs>++## Logs Explorer++The [Logs Explorer](https://app.supabase.com/project/_/logs-explorer) exposes logs from each part of the Supabase stack as a separate table that can be queried and joined using SQL.++++You can access the following logs from the **Sources** drop-down:++- `auth_logs`: GoTrue server logs, containing authentication/authorization activity.+- `edge_logs`: Edge network logs, containing request and response metadata retrieved from Cloudflare.+- `function_edge_logs`: Edge network logs for only edge functions, containing network requests and response metadata for each execution.+- `function_logs`: Function internal logs, containing any `console` logging from within the edge function.+- `postgres_logs`: Postgres database logs, containing statements executed by connected applications.+- `realtime_logs`: Realtime server logs, containing client connection information.+- `storage_logs`: Storage server logs, containing object upload and retrieval information.++## Querying with the Logs Explorer++The Logs Explorer uses BigQuery and supports all [available SQL functions and operators](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators).++### Timestamp Display and Behavior++Each log entry is stored with a `timestamp` as a `TIMESTAMP` data type. Use the appropriate [timestamp function](https://cloud.google.com/bigquery/docs/reference/standard-sql/timestamp_functions#timestamp) to utilize the `timestamp` field in a query.++Raw top-level timestamp values are rendered as unix microsecond. To render the timestamps in a human-readable format, use the `DATETIME()` function to convert the unix timestamp display into an ISO-8601 timestamp.++```sql+-- timestamp column without datetime()+select timestamp from ....+-- 1664270180000++-- timestamp column with datetime()+select datetime(timestamp) from ....+-- 2022-09-27T09:17:10.439Z+```++### Unnesting Arrays++Each log event stores metadata an array of objects with multiple levels, and can be seen by selecting single log events in the Logs Explorer. To query arrays, use `unnest()` on each array field and add it to the query as a join. This allows you to reference the nested objects with an alias and select their individual fields.++For example, to query the edge logs without any joins:++```sql+select timestamp, metadata from edge_logs t+```++The resulting `metadata` key is rendered as an array of objects in the Logs Explorer. In the following diagram, each box represents a nested array of objects:++<!-- Scene is here https://app.excalidraw.com/s/8gj16loJfGZ/3HzccK9MyLx -->++<ThemedImage+ alt="Without Unnesting"+ sources={{+ light: useBaseUrl('/img/guides/platform/logs/unnesting-none.png'),+ dark: useBaseUrl('/img/guides/platform/logs/unnesting-none-dark.png'),+ }}+ style={{ maxHeight: 200 }}+/>++Perform a `cross join unnest()` to work with the keys nested in the `metadata` key.++To query for a nested value, add a join for each array level:++```sql+select timestamp, request.method, header.cf_ipcountry+from edge_logs t+cross join unnest(t.metadata) as metadata+cross join unnest(metadata.request) as request+cross join unnest(request.headers) as header+```++This surfaces the following columns available for selection:++<ThemedImage+ alt="With Two Level Unnesting"+ sources={{+ light: useBaseUrl('/img/guides/platform/logs/unnesting-2.png'),+ dark: useBaseUrl('/img/guides/platform/logs/unnesting-2-dark.png'),+ }}+ style={{ maxHeight: 200 }}+/>++This allows you to select the `method` and `cf_ipcountry` columns. In JS dot notation, the full paths for each selected column are:++- `metadata[].request[].method`+- `metadata[].request[].headers[].cf_ipcountry`++### LIMIT and Result Row Limitations++The Logs Explorer has a maximum of 1000 rows per run. Use `LIMIT` to optimize your queries by reducing the number of rows returned further.++### Best Practices++1. Include a filter over **timestamp**++Querying your entire log history might seem appealing. For **Enterprise** customers that have a large retention range, you run the risk of timeouts due additional time required to scan the larger dataset.++2. Avoid selecting large nested objects. Select individual values instead.++When querying large objects, the columnar storage engine selects each column associated with each nested key, resulting in a large number of columns being selected. This inadvertently impacts the query speed and may result in timeouts or memory errors, especially for projects with a lot of logs.++Instead, select only the values required.++```sql+-- ❌ Avoid doing this+select+ datetime(timestamp),+ m as metadata -- <- metadata contains many nested keys+from edge_logs t+cross join unnest(t.metadata) as m;++-- ✅ Do this+select+datetime(timestamp),+r.method -- <- select only the required values+from edge_logs t+cross join unnest(t.metadata) as m+cross join unnest(m.request) as r+```++### Examples and Templates++The Logs Explorer includes **Templates** (available in the Templates tab or the dropdown in the Query tab) to help you get started.++For example, you can enter the following query in the SQL Editor to retrieve each user's IP address:++```sql+select datetime(timestamp), h.x_real_ip+from edge_logs+ cross join unnest(metadata) as m+ cross join unnest(m.request) AS r+ cross join unnest(r.headers) AS h+where h.x_real_ip is not null and r.method = "GET"+```diff --git a/apps/temp-docs/docs/guides/platform/metrics.mdx b/apps/temp-docs/docs/guides/platform/metrics.mdxnew file mode 100644index 00000000000..8fba89eace9--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/metrics.mdx@@ -0,0 +1,31 @@+---+id: metrics+title: Metrics+description: Observability for your Supabase project+---++In addition to the reports and charts built in to the Supabase dashboard, each project hosted on the Supabase platform comes with a [Prometheus](https://prometheus.io/)-compatible metrics endpoint, which can be used to gather insight into the health and status of your project.++You can use this endpoint to ingest data into your own monitoring and alerting infrastructure, as long as it is capable of scraping Prometheus-compatible endpoints, in order to set up custom rules beyond those supported by the Supabase dashboard.++:::note++The endpoint discussed in this article is in beta, and the metrics returned by it might evolve or be changed in the future to increase its utility.++:::++:::note++The endpoint discussed in this article is not available on self-hosted.++:::++## Accessing the metrics endpoint++Your project's metrics endpoint is accessible at `https://<project-ref>.supabase.co/customer/v1/privileged/metrics`. Access to the endpoint is secured via HTTP Basic Auth; the username is `service_role`, while the password is the service role JWT available through the Supabase dashboard.++```shell+> curl https://<project-ref>.supabase.co/customer/v1/privileged/metrics --user 'service_role:<service-role-jwt>'+```++Additionally, we [maintain a guide](https://github.com/supabase/grafana-agent-fly-example/) on quickly setting up a scraping agent to work with Grafana Cloud.diff --git a/apps/temp-docs/docs/guides/platform/performance.mdx b/apps/temp-docs/docs/guides/platform/performance.mdxnew file mode 100644index 00000000000..07dfa92dc61--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/performance.mdx@@ -0,0 +1,90 @@+---+id: performance+title: Performance Tuning+description: Getting the best results out of your Supabase project+---++The Supabase platform automatically optimizes your Postgres database to take advantage of the compute resources of the tier your project is on. However, these optimizations are based on assumptions about the type of workflow the project is being utilized for, and it is likely that better results can be obtained by tuning the database for your particular workflow.++## Optimizing the number of connections++By default, the number of connections allowed to Postgres and PgBouncer is configured based on the resources available to the database.++| Compute Add-on | Postgresql connections | PGBouncer connections |+| -------------- | ---------------------- | --------------------- |+| None | 60 | 200 |+| Small | 90 | 200 |+| Medium | 120 | 200 |+| Large | 160 | 300 |+| XL | 240 | 700 |+| 2XL | 380 | 1500 |+| 4XL | 480 | 3000 |+| 8XL | 490 | 6000 |+| 12XL | 500 | 9000 |+| 16XL | 500 | 12000 |++If the number of connections is insufficient, you will receive the following error upon connecting to the DB:++```shell+$ psql -U postgres -h ...+FATAL: remaining connection slots are reserved for non-replication superuser connections+```++In such a scenario, you can consider:++- [upgrading to a larger compute add-on](https://app.supabase.com/project/_/settings/billing)+- configuring your clients to use fewer connections+- manually configuring the database for a higher number of connections++### Configuring clients to use fewer connections++You can use the [pg_stat_activity](https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW) view to debug which clients are holding open connections on your DB. `pg_stat_activity` only exposes information on direct connections to the database. Information on the number of connections to pgbouncer is available [via the metrics endpoint](../platform/metrics).++Depending on the clients involved, you might be able to configure them to work with fewer connections (e.g. by imposing a limit on the maximum number of connections they're allowed to use), or shift specific workloads to connect via [pgbouncer](/docs/guides/database/connecting-to-postgres#connection-pool) instead. Transient workflows, which can quickly scale up and down in response to traffic (e.g. serverless functions), can especially benefit from using a connection pooler rather than connecting to the DB directly.++### Allowing higher number of connections++You can configure Postgres by executing the following statement, followed by a server restart:++```sql+alter system set max_connections = '<val-here>';+```++Note that [the default configuration used by the Supabase platform](https://github.com/supabase/supabase-admin-api/blob/master/optimizations/postgres.go) optimizes the database to maximize resource utilization, and as a result, you might also need to configure other options (e.g. `work_mem`, `shared_buffers`, `maintenance_work_mem`) in order to tune them towards your use-case, and to avoid causing instability in your database.++Once overridden, the Supabase platform will continue to respect your manually configured value (even if the add-on size is changed), unless the override is removed with the following statement, followed by a server restart:++```sql+alter system reset max_connections;+alter system reset <other-overridden-conf>;+...+```++Configuring the number of PgBouncer connections is not supported at this time.++## Examining Query Performance++Every Supabase project has [the pg_stat_statements extension](https://www.postgresql.org/docs/14/pgstatstatements.html) enabled by default. This extension records query execution performance details and is the best way to find queries that take the most time to execute. This information can be combined with the Postgres query plan analyzer to develop more efficient queries.++Obtaining information from pg_stat_statements:++```sql+select mean_exec_time + stddev_exec_time, * from pg_stat_statements order by 1 desc;+```++Using the query plan analyzer on your expensive queries:++```sql+explain analyze <query-statement-here>;+```++Be careful using `explain analyze` with `insert`/`update`/`delete` queries, because the query will actually run, and could have unintended side-effects.++Using the query plan analyzer to optimize your queries is a large topic, with a number of online resources available:++- [Official docs.](https://www.postgresql.org/docs/current/using-explain.html)+- [The Art of PostgreSQL.](https://theartofpostgresql.com/explain-plan-visualizer/)+- [Postgres Wiki.](https://wiki.postgresql.org/wiki/Using_EXPLAIN)+- [Enterprise DB.](https://www.enterprisedb.com/blog/postgresql-query-optimization-performance-tuning-with-explain-analyze)++You can pair the information available from `pg_stat_statements` with the detailed system metrics available [via your metrics endpoint](../platform/metrics) to better understand the behavior of your DB and the queries you're executing against it.diff --git a/apps/temp-docs/docs/guides/platform/permissions.mdx b/apps/temp-docs/docs/guides/platform/permissions.mdxnew file mode 100644index 00000000000..c3fbf719d23--- /dev/null+++ b/apps/temp-docs/docs/guides/platform/permissions.mdx@@ -0,0 +1,14 @@+---+id: permissions+title: Permissions+description: Permissions requirements for the Supabase Cloud hosting environment+---++The Supabase platform offers additional services (e.g. Storage) on top of the Postgres database that comes with each project. These services default to storing their operational data within your database, to ensure that you retain complete control over it.++However, these services assume a base level of access to their data, in order to e.g. be able to run migrations over it. Breaking these assumptions runs the risk of rendering these services inoperational for your project:++- all entitites under the `storage` schema are owned by `supabase_storage_admin`+- all entitites under the `auth` schema are owned by `supabase_auth_admin`++It is possible for violations of these assumptions to not cause an immediate outage, but take effect at a later time when a newer migration becomes available.diff --git a/apps/temp-docs/docs/guides/realtime.mdx b/apps/temp-docs/docs/guides/realtime.mdxnew file mode 100644index 00000000000..12cc7c97fac--- /dev/null+++ b/apps/temp-docs/docs/guides/realtime.mdx@@ -0,0 +1,51 @@+---+id: realtime+title: Realtime+description: Supabase Realtime with Broadcast, Presence, and Postgres CDC.+sidebar_label: Overview+---++Supabase provides a globally distributed cluster of [Realtime](https://github.com/supabase/realtime) servers that enable the following functionality:++- [Broadcast](#broadcast): Send ephemeral messages from client to clients with low latency.+- [Presence](#presence): Track and synchrononize shared state between clients.+- [Postgres CDC](#postgres-cdc): Listen to Postgres database changes and send them to authorized clients.++A [channel](https://hexdocs.pm/phoenix/channels.html) is the basic building block of Realtime and narrows the scope of data flow to subscribed clients. You can think of a channel as a chatroom where participants are able to see who's online and send and receive messages; similar to a Discord or Slack channel.++All clients can connect to a channel and take advantage of the built-in features, Broadcast and Presence, while extenstions, like Postgres CDC, must be enabled prior to use.++## Broadcast++Broadcast follows the [publish-subscribe pattern](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) where a client publishes messages to a channel with a unique identifier. For example, a user could send a message to a channel with id `room-1`.++Other clients can elect to receive the message in real-time by subscribing to the channel with id `room-1`. If these clients are online and subscribed then they will receive the message.++Broadcast works by connecting your client to the nearest Realtime server, which will communicate with other servers to relay messages to other clients.++A common use-case is sharing a user's cursor position with other clients in an online game.++## Presence++Presence utilizes an in-memory conflict-free replicated data type (CRDT) to track and synchronize shared state in an eventually consistent manner. It computes the difference between existing state and new state changes and sends the necessary updates to clients via Broadcast.++When a new client subscribes to a channel, it will immediately receive the channel's latest state in a single message instead of waiting for all other clients to send their individual states.++Clients are free to come-and-go as they please, and as long as they are all subscribed to the same channel then they will all have the same Presence state as each other.++The neat thing about Presence is that if a client is suddenly disconnected (for example, they go offline), their state will be automatically removed from the shared state. If you've ever tried to build an “I'm online” feature which handles unexpected disconnects, you'll appreciate how useful this is.++## Postgres CDC++Postgres Change Data Capture (CDC) enables you to listen to database changes and have them broadcast to authorized clients based on [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies.++This works by Realtime polling your database's logical replication slot for changes, passing those changes to the [apply_rls](https://github.com/supabase/walrus#reading-wal) SQL function to determine which clients have permission, and then using Broadcast to send those changes to clients.++Realtime requires a publication called `supabase_realtime` to determine which tables to poll. You must add tables to this publication prior to clients subscribing to channels that want to listen for database changes.++We strongly encourage you to enable RLS on your database tables and have RLS policies in place to prevent unauthorized parties from accessing your data.++## See Also++- [Realtime quickstart](/docs/guides/realtime/quickstart)+- [Realtime: Multiplayer Edition](https://supabase.com/blog/supabase-realtime-multiplayer-general-availability) blog postdiff --git a/apps/temp-docs/docs/guides/realtime/postgres-cdc.mdx b/apps/temp-docs/docs/guides/realtime/postgres-cdc.mdxnew file mode 100644index 00000000000..5752274dbbc--- /dev/null+++ b/apps/temp-docs/docs/guides/realtime/postgres-cdc.mdx@@ -0,0 +1,124 @@+---+id: postgres-cdc+title: Postgres CDC+description: Getting started with Realtime's Postgres CDC feature+---++Realtime's Postgres Change Data Capture (CDC) feature listens for database changes and sends them to clients. Clients are required to subscribe with a JWT dictating which changes they are allowed to receive based on the database's [Row Level Security](/docs/guides/auth/row-level-security).++Anyone with access to a valid JWT signed with the project's JWT secret is able to listen to your database's changes, unless tables have [Row Level Security](/docs/guides/auth/row-level-security) enabled and policies in place.++Clients can choose to receive `INSERT`, `UPDATE`, `DELETE`, or `*` (all) changes for all changes in a schema, a table in a schema, or a column's value in a table. Your clients should only listen to tables in the `public` schema and you must first enable the tables you want your clients to listen to.++Postgres CDC works out of the box for tables in the `public` schema. You can listen to tables in your private schemas by granting table `SELECT` permissions to the database role found in your access token. You can run a query similar to the following:++```sql+GRANT SELECT ON "private_schema"."table" TO authenticated;+```++:::caution+We strongly encourage you to enable RLS and create policies for tables in private schemas. Otherwise, any role you grant access to will have unfettered read access to the table.+:::++You can do this in the [Replication](https://app.supabase.com/project/_/database/replication) section in the Dashboard or with the [SQL editor](https://app.supabase.com/project/_/sql):++```sql+begin;+ -- remove the supabase_realtime publication+ drop publication if exists supabase_realtime;++ -- re-create the supabase_realtime publication with no tables+ create publication supabase_realtime;+commit;++-- add a table to the publication+alter publication supabase_realtime add table messages;+```++By default, only `new` record changes are sent but if you want to receive the `old` record (previous values) whenever you `UPDATE` or `DELETE` a record,+you can set the `replica identity` of your table to `full`:++```sql+alter table messages replica identity full;+```++To listen to all changes in the `public` schema:++```js+const { createClient } = require('@supabase/supabase-js')++const supabase = createClient(+ process.env.SUPABASE_URL,+ process.env.SUPABASE_KEY+)++/*+ Channel name can be any string.+ Event name can can be one of:+ - INSERT+ - UPDATE+ - DELETE+ - *+*/+const channel = supabase+ .channel('schema-db-changes')+ .on('postgres_changes', { event: '*', schema: 'public' }, (payload) =>+ console.log(payload)+ )+ .subscribe()+```++To listen to changes on a table in the `public` schema:++```js+// Supabase client setup++const channel = supabase+ .channel('table-db-changes')+ .on(+ 'postgres_changes',+ { event: 'INSERT', schema: 'public', table: 'messages' },+ (payload) => console.log(payload)+ )+ .subscribe()+```++To listen to changes when a column's value in a table matches a client-specified value:++```js+// Supabase client setup++const channel = supabase+ .channel('value-db-changes')+ .on(+ 'postgres_changes',+ {+ event: 'UPDATE',+ schema: 'public',+ table: 'messages',+ filter: 'body=eq.hey',+ },+ (payload) => console.log(payload)+ )+ .subscribe()+```++To listen to different events and schema/tables/filters combinations with the same channel:++```js+// Supabase client setup++const channel = supabase+ .channel('db-changes')+ .on(+ 'postgres_changes',+ { event: '*', schema: 'public', table: 'messages', filter: 'body=eq.bye' },+ (payload) => console.log(payload)+ )+ .on(+ 'postgres_changes',+ { event: 'INSERT', schema: 'public', table: 'users' },+ (payload) => console.log(payload)+ )+ .subscribe()+```diff --git a/apps/temp-docs/docs/guides/realtime/quickstart.mdx b/apps/temp-docs/docs/guides/realtime/quickstart.mdxnew file mode 100644index 00000000000..47a77610d94--- /dev/null+++ b/apps/temp-docs/docs/guides/realtime/quickstart.mdx@@ -0,0 +1,258 @@+---+id: quickstart+title: Realtime Quickstart+description: Getting started with Realtime's Features+sidebar_label: Quickstart+---++Learn how to build [multiplayer.dev](https://multiplayer.dev), a collaborative app that demonstrates Broadcast, Presence, and Postgres CDC using [Realtime](/docs/guides/realtime).++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/BelYEMJ2N00"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Install `supabase-js` Client++```bash+npm install @supabase/supabase-js+```++## Cursor Positions++[Broadcast](/docs/guides/realtime#broadcast) allows a client to send messages and multiple clients to receive the messages. The broadcasted messages are ephemeral. They are not persisted to the database and are directly relayed through the Realtime servers. This is ideal for sending information like cursor positions where minimal latency is important, but persisting them is not.++In [multiplayer.dev](https://multiplayer.dev), client's cursor positions are sent to other clients in the room. However, cursor positions will be randomly generated for this example.++You need to get the public `anon` access token from your project's [API settings](https://app.supabase.com/project/_/settings/api). Then you can set up the Suapbase client and start sending a client's cursor positions to other clients in channel `room1`:++```js+const { createClient } = require('@supabase/supabase-js')++const supabase = createClient(+ 'https://your-project-ref.supabase.co',+ 'anon-key',+ {+ realtime: {+ params: {+ eventsPerSecond: 10,+ },+ },+ }+)++// Channel name can be any string.+// Create channels with the same name for both the broadcasting and receiving clients.+const channel = supabase.channel('room1')++// Subscribe registers your client with the server+channel.subscribe((status) => {+ if (status === 'SUBSCRIBED') {+ // now you can start broadcasting cursor positions+ setInterval(() => {+ channel.send({+ type: 'broadcast',+ event: 'cursor-pos',+ payload: { x: Math.random(), y: Math.random() },+ })+ console.log(status)+ }, 100)+ }+})+```++:::info+JavaScript client has a default rate limit of 1 Realtime event every 100 milliseconds that's configured by `eventsPerSecond`.+:::++Another client can subscribe to channel `room1` and receive cursor positions:++```js+// Supabase client setup++// Listen to broadcast messages.+supabase+ .channel('room1')+ .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))+ .subscribe((status) => {+ if (status === 'SUBSCRIBED') {+ // your callback function will now be called with the messages broadcast by the other client+ }+ })+```++:::info+`type` must be `broadcast` and the `event` must match for clients subscribed to the channel.+:::++## Roundtrip Latency++You can also configure the channel so that the server must return an acknowledgement that it received the `broadcast` message. This is useful if you want to measure the roundtrip latency:++```js+// Supabase client setup++const channel = supabase.channel('calc-latency', {+ config: {+ broadcast: { ack: true }+ }+})++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const begin = performance.now()++ await channel.send({+ type: 'broadcast',+ event: 'latency',+ payload: {},+ })++ const end = performance.now()++ console.log(`Latency is ${end - begin} milliseconds`)+ }+ })+```++## Track and display which users are online++[Presence](/docs/guides/realtime#presence) stores and synchronize shared state across clients. The `sync` event is triggered whenever the shared state changes. The `join` event is triggered when new clients join the channel and `leave` event is triggered when clients leave.++Each client can use the channel's `track` method to store an object in shared state. Each client can only track one object, and if `track` is called again by the same client, then the new object overwrites the previously tracked object in the shared state. You can use one client to track and display users who are online:++```js+// Supabase client setup++const channel = supabase.channel('online-users', {+ config: {+ presence: {+ key: 'user1',+ },+ },+})++channel.on('presence', { event: 'sync' }, () => {+ console.log('Online users: ', channel.presenceState())+})++channel.on('presence', { event: 'join' }, ({ newPresences }) => {+ console.log('New users have joined: ', newPresences)+})++channel.on('presence', { event: 'leave' }, ({ leftPresences }) => {+ console.log('Users have left: ', newPresences)+})++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const status = await channel.track({ online_at: new Date().toISOString() })+ console.log(status)+ }+})+```++Then you can use another client to add another user to the channel's Presence state:++```js+// Supabase client setup++const channel = supabase.channel('online-users', {+ config: {+ presence: {+ key: 'user2',+ },+ },+})++// Presence event handlers setup++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const status = await channel.track({ online_at: new Date().toISOString() })+ console.log(status)+ }+})+```++If a channel is set up without a presence key, the server generates a random UUID. `type` must be `presence` and `event` must be either `sync`, `join`, or `leave`.++## Insert and Receive Persisted Messages++[Postgres Change Data Capture (CDC)](/docs/guides/realtime#postgres-cdc) enables your client to insert, update, or delete database records and send the changes to clients. Create a `messages` table to keep track of messages created by users in specific rooms:++```sql+create table messages (+ id serial primary key,+ message text,+ user_id text,+ room_id text,+ created_at timestamptz default now()+)++alter table messages enable row level security;++create policy "anon_ins_policy"+ON messages+for insert+to anon+with check (true);++create policy "anon_sel_policy"+ON messages+for select+to anon+using (true);+```++If it doesn't already exist, create a `supabase_realtime` publication and add `messages` table to the publication:++```sql+begin;+ -- remove the supabase_realtime publication+ drop publication if exists supabase_realtime;++ -- re-create the supabase_realtime publication with no tables and only for insert+ create publication supabase_realtime with (publish = 'insert');+commit;++-- add a table to the publication+alter publication supabase_realtime add table messages;+```++You can then have a client listen for changes on the `messages` table for a specific room and send and receive persisted messages:++```js+// Supabase client setup++const channel = supabase.channel('db-messages')++const roomId = 'room1'+const userId = 'user1'++channel.on(+ 'postgres_changes',+ {+ event: 'INSERT',+ schema: 'public',+ table: 'messages',+ filter: `room_id=eq.${roomId}`,+ },+ (payload) => console.log(payload)+)++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const res = await supabase.from('messages').insert({+ room_id: roomId,+ user_id: userId,+ message: 'Welcome to Realtime!',+ })+ console.log(res)+ }+})+```diff --git a/apps/temp-docs/docs/guides/storage-cdn.mdx b/apps/temp-docs/docs/guides/storage-cdn.mdxnew file mode 100644index 00000000000..c4b918880fe--- /dev/null+++ b/apps/temp-docs/docs/guides/storage-cdn.mdx@@ -0,0 +1,34 @@+---+id: storage-cdn+title: Storage CDN+description: How Supabase Storage caches objects with a CDN+sidebar_label: CDN+---++## CDN basics++All assets uploaded to storage are cached on a Content Delivery Network (CDN).++To improve the latency for users all around the world, Supabase uses a CDN. CDNs are a geographically distributed set of servers or **nodes** which caches content from an **origin server**. For Supabase Storage, the origin is the storage server running in the [same region as your project](https://app.supabase.com/project/_/settings/general).++Let’s walk through an example of how a CDN helps with performance. A new bucket is created for a Supabase project launched in Singapore. All requests to the Supabase Storage API first hit the CDN. A user from the United States requests an object and is routed to the U.S. CDN. At this point, that CDN node does not have the object in its cache and pings the origin server in Singapore. Another user, also in the United States, requests the same object and is served directly from the CDN cache in the United States instead of routing the request back to Singapore.++Aside from performance, CDNs also help with security and availability by mitigating Distributed Denial of Service and other application attacks.++## Cache duration++By default, assets are cached both in the CDN and in the user’s browser for 1 hour. After this, the CDN nodes ping the storage server to see if an object has been updated.++You can modify this cache time when you are [uploading](https://supabase.com/docs/reference/javascript/storage-from-upload) or [updating](https://supabase.com/docs/reference/javascript/storage-from-update) an object by modifying the `cacheControl` parameter.++If you expect the object to not change at a given URL, setting a longer cache duration is preferable.++If you need to update the version of the object stored in the CDN, there are various cache-busting techniques you can use. The most common way to do this is to add a version query parameter in the URL. For example, you can use a URL like `/storage/v1/object/sign/profile-pictures/cat.jpg?token=eyJh...&version=1` in your applications and set a long cache time of 1 year. When you want to update the cat picture, you can increment the version query parameter in the URL. The CDN will treat `/storage/v1/object/sign/profile-pictures/cat.jpg?token=eyJh...&version=2` as a new object and pings the origin for the updated version.++Note that CDNs might still evict your object from their cache if it has not been requested for a while from a specific region. For example, if no user from United States requests your object, it will be removed from the CDN cache even if you set a very long cache control duration.++The cache status of a particular request is sent in the `cf-cache-status` header. A cache status of `MISS` indicates that the CDN node did not have the object in its cache and had to ping the origin to get it. A cache status of `HIT` indicates that the object was sent directly from the CDN.++## Public vs Private Buckets++Objects in public buckets do not require any Authorization to access objects. This leads to a better cache hit rate compared to private buckets. For private buckets, permissions for accessing each object is checked on a per user level. For example, if two different users access the same object in a private bucket from the same region, it results in a cache miss for both the users since they might have different security policies attached to them. On the other hand, if two different users access the same object in a public bucket from the same region, it results in a cache hit for the second user.diff --git a/apps/temp-docs/docs/guides/storage.mdx b/apps/temp-docs/docs/guides/storage.mdxindex 32001b0b5d6..566802059b7 100644--- a/apps/temp-docs/docs/guides/storage.mdx+++ b/apps/temp-docs/docs/guides/storage.mdx@@ -1,11 +1,12 @@----title: 'Storage'-description: 'Supabase Storage'+id: storage+title: Storage+description: Use Supabase to store and serve files.+sidebar_label: Overview----# Storage--## Overview+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'Supabase Storage makes it simple to store and serve large files.@@ -15,61 +16,278 @@ Files can be any sort of media file. This includes images, GIFs, and videos. It### Folders-Folders are a way to organize your files (just like on your computer). There is no right or wrong way to organize your files. You can store them in whichever folder structure suits your project.+Folders are a way to organize your files (just like on your computer).+There is no right or wrong way to+organize your files. You can store them in whichever folder structure suits your project.### Buckets-Buckets are distinct containers for files and folders. You can think of them like "super folders". Generally you would create distinct buckets for different Security and Access Rules. For example, you might keep all public files in a "public" bucket, and other files that require logged-in access in a "restricted" bucket.+Buckets are distinct containers for files and folders. You can think of them like "super folders".+Generally you would create distinct buckets for different Security and Access Rules. For example, you might+keep all video files in a "video" bucket, and profile pictures in an "avatar" bucket.++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/J9mTPY8rIXE"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>## Getting started-This is a quick guide that shows the basic functionality of Supabase Storage. Find a full [example application in GitHub](https://github.com/supabase/supabase/edit/master/examples/nextjs-ts-user-management), which you can deploy yourself.+This is a quick guide that shows the basic functionality of Supabase Storage. Find a full+[example application in GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management),+which you can deploy yourself.++[](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Fuser-management%2Fnextjs-ts-user-management&project-name=supabase-user-management&repository-name=supabase-user-management&demo-title=Supabase%20User%20Management&demo-description=An%20example%20web%20app%20using%20Supabase%20and%20Next.js&demo-url=https%3A%2F%2Fsupabase-nextjs-ts-user-management.vercel.app&demo-image=https%3A%2F%2Fi.imgur.com%2FZ3HkQqe.png&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&external-id=nextjs-user-management)-<a href="https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Fnextjs-ts-user-management&project-name=supabase-user-management&repository-name=supabase-user-management&demo-title=Supabase%20User%20Management&demo-description=An%20example%20web%20app%20using%20Supabase%20and%20Next.js&demo-url=https%3A%2F%2Fsupabase-nextjs-ts-user-management.vercel.app&demo-image=https%3A%2F%2Fi.imgur.com%2FZ3HkQqe.png&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&external-id=nextjs-user-management">- <img src="https://vercel.com/button" alt="Deploy with Vercel" />-</a>+:::note+File, Folder, and Bucket names **must follow** [AWS object key naming guidelines](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html) and avoid use of any other characters.+:::### Create a bucket-You can create a bucket using the Supabase Dashboard. Since the storage is interoperable with your Postgres database, you can also use SQL or our client libraries. Here we create a bucket called "avatars":+You can create a bucket using the Supabase Dashboard.+Since the storage is interoperable with your Postgres database, you can also use SQL or our+client libraries. Here we create a bucket called "avatars":++<Tabs+ groupId="storage-tabs"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Dart', value: 'dart'},+ ]}>+<TabItem value="dashboard">++1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard.+2. Click **New Bucket** and enter a name for the bucket.+3. Click **Create Bucket**.-<!----TODO: Get tabs to render - @supabase/ui Tabs component fails to render)---->+</TabItem>+<TabItem value="sql">++```sql+-- Use Postgres to create a bucket.++insert into storage.buckets (id, name)+values ('avatars', 'avatars');+```-[Reference](https://pub.dev/documentation/storage_client/latest/storage_client/SupabaseStorageClient/createBucket.html)+</TabItem>+<TabItem value="javascript">++```js+// Use the JS library to create a bucket.++const { data, error } = await supabase.storage.createBucket('avatars')+```++[Reference.](/docs/reference/javascript/storage-createbucket)++</TabItem>+<TabItem value="dart">++```dart+void main() async {+ final client = SupabaseClient('supabaseUrl', 'supabaseKey');++ final storageResponse = await client+ .storage+ .createBucket('avatars');+}+```++[Reference.](https://pub.dev/documentation/storage_client/latest/storage_client/SupabaseStorageClient/createBucket.html)++</TabItem>+</Tabs>### Upload a fileYou can upload a file from the Dashboard, or within a browser using our JS libraries.-<video width="99%" playsinline controls>- <source src="/videos/storage/upload.mp4" type="video/mp4" playsInline />-</video>+<Tabs+ groupId="storage-tabs"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Dart', value: 'dart'},+ ]}>+<TabItem value="dashboard">++1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard.+2. Select the bucket you want to upload the file to.+3. Click **Upload File**.+4. Select the file you want to upload.++</TabItem>+<TabItem value="javascript">++```js+const avatarFile = event.target.files[0]+const { data, error } = await supabase.storage+ .from('avatars')+ .upload('public/avatar1.png', avatarFile)+```++[Reference.](/docs/reference/javascript/storage-from-upload)++</TabItem>+<TabItem value="dart">++```dart+void main() async {+ final client = SupabaseClient('supabaseUrl', 'supabaseKey');++ // Create file `example.txt` and upload it in `public` bucket+ final file = File('example.txt');+ file.writeAsStringSync('File content');+ final storageResponse = await client+ .storage+ .from('public')+ .upload('example.txt', file);+}+```++</TabItem>+</Tabs>### Download a fileYou can download a file from the Dashboard, or within a browser using our JS libraries.-<video width="99%" playsinline controls>- <source src="/videos/storage/download.mp4" type="video/mp4" playsInline />-</video>+<Tabs+ groupId="storage-tabs"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'JavaScript', value: 'javascript'},+ {label: 'Dart', value: 'dart'},+ ]}>+<TabItem value="dashboard">++1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard.+2. Select the bucket that contains the file.+3. Select the file that you want to download.+4. Click **Download**.++</TabItem>+<TabItem value="javascript">++```js+// Use the JS library to download a file.++const { data, error } = await supabase.storage+ .from('avatars')+ .download('public/avatar1.png')+```++[Reference.](/docs/reference/javascript/storage-from-download)++</TabItem>+<TabItem value="dart">++```dart+void main() async {+ final client = SupabaseClient('supabaseUrl', 'supabaseKey');++ final storageResponse = await client+ .storage+ .from('public')+ .download('example.txt');+}+```++</TabItem>+</Tabs>### Add security rulesTo restrict access to your files you can use either the Dashboard or SQL.-<video width="99%" playsinline controls>- <source src="/videos/storage/policies.mp4" type="video/mp4" playsInline />-</video>+<Tabs+ groupId="storage-tabs"+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'}+ ]}>+<TabItem value="dashboard">++1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard.+2. Click **Policies** in the sidebar.+3. Click **Add Policies** in the `OBJECTS` table to add policies for Files. You can also create policies for Buckets.+4. Choose whether you want the policy to apply to downloads (SELECT), uploads (INSERT), updates (UPDATE), or deletes (DELETE).+5. Give your policy a unique name.+6. Write the policy using SQL.++</TabItem>+<TabItem value="sql">-### Helpers+```sql+-- Use SQL to create a policy.++create policy "Public Access"+ on storage.objects for select+ using ( bucket_id = 'public' );+```++</TabItem>+</Tabs>++## Public and Private Buckets++Storage buckets are private by default.++For private buckets, you can access objects via the [download](/docs/reference/javascript/storage-from-download) method. This corresponds to `/object/auth/` API endpoint.+Alternatively, you can create a publicly shareable URL with an expiry date using the [createSignedUrl](/docs/reference/javascript/storage-from-createsignedurl) method+which calls the `/object/sign/` API.++For public buckets, you can access the assets directly without a token or an Authorisation header. The [getPublicUrl](/docs/reference/javascript/storage-from-getpublicurl)+helper method returns the full public URL for an asset. This calls the `/object/public/` API endpoint internally. While no authorization is required for accessing objects in a public bucket, proper [access control](#access-control) is required for other operations like uploading, deleting objects from public buckets as well.++Public buckets also tend to have [better performance](/docs/guides/storage-cdn#public-vs-private-buckets).++<details>+<summary>Advanced: reverse proxy</summary>+The URLs returned are proxied through the API Proxy. They are prefixed by <code>/storage/v1</code>.++For example, on the hosted Platform they will be++<code>https://[project_ref].supabase.co/storage/v1/object/public/[id]</code>++You can access the storage API directly with the same endpoint. See the <a href="https://supabase.github.io/storage-api">API docs</a> for a full list of operations available.++</details>++---++## Access control++Supabase Storage is integrated with your [Postgres Database](/docs/guides/database).+This means that you can use the same [Row Level Security Policies](/docs/guides/auth#policies)+for managing access to your files. Supabase Storage stores metadata in the `objects` and `buckets` table in the storage schema. To allow read access to files, the RLS policy must allow users to `SELECT` the `objects` table and for uploading a new object, the RLS policy must grant users access to `INSERT` into the `objects` table and so on. The mapping between the different API calls and the database permissions required is documented in the [Reference docs](/docs/reference/javascript/storage-createbucket).++:::note-Supabase Storage is configured with database SQL helper functions which you can use in your database queries and policies.+Access control for Storage is mapped to CRUD operations on the `buckets` and `objects` table via RLS policies.-<hr />+:::++## Helpers++Supabase Storage provides SQL helper functions which you can use in your database queries and+policies.++----`storage.filename()`+#### `storage.filename()`Returns the name of a file.@@ -82,9 +300,9 @@ For example, if your file is stored in `public/subfolder/avatar.png` it would re`'avatar.png'`-<hr />+----`storage.foldername()`+#### `storage.foldername()`Returns an array path, with all of the subfolders that a file belongs to.@@ -97,9 +315,9 @@ For example, if your file is stored in `public/subfolder/avatar.png` it would re`[ 'public', 'subfolder' ]`-<hr />+----`storage.extension()`+#### `storage.extension()`Returns the extension of a file.@@ -112,17 +330,13 @@ For example, if your file is stored in `public/subfolder/avatar.png` it would re`'png'`-<hr />--### Security--Supabase Storage is integrated with your Postgres Database. This means that you can use the same Policy engine for managing access to your files.+----### Policy Examples+## Policy examples-Here are some examples to show you the power of PostgreSQL's Row Level Security. Each policy is attached to a table, and the policy is executed every time a table is accessed.+Here are some examples of storage policies.-#### Allow public access to a bucket+### Allow public access to a bucket```sql-- 1. Allow public access to any files in the "public" bucket@@ -131,7 +345,7 @@ on storage.objects for selectusing ( bucket_id = 'public' );```-#### Allow logged-in access to a bucket+### Allow logged-in access to a bucket```sql-- 1. Allow logged-in access to any files in the "restricted" bucket@@ -143,7 +357,7 @@ using ();```-#### Allow individual access to a file+### Allow individual access to a file```sql-- 1. Allow a user to access their own files@@ -152,14 +366,10 @@ on storage.objects for selectusing ( auth.uid() = owner );```-### Tips--#### Go Easy--Supabase Storage is in Beta. If you're experiencing any issues, let us know on our [GitHub](https://github.com/supabase/supabase/discussions) and we will fix it as fast as we can.--## Next steps+## See also-- Got a question? Ask here.-- Read more about storage in our blog post.-- Sign in: app.supabase.com+- Read more about Supabase Storage in the [blog post](https://supabase.com/blog/supabase-storage)+- [Supabase Storage on GitHub](https://github.com/supabase/storage-api)+- [Swagger API documentation](https://supabase.github.io/storage-api)+- Official [JavaScript](/docs/reference/javascript/storage-createbucket) and [Dart](/docs/reference/dart/storage-createbucket) documentation+- [Community libraries](https://github.com/supabase-community)diff --git a/apps/temp-docs/docs/guides/storage/storage-sample.mdx b/apps/temp-docs/docs/guides/storage/storage-sample.mdxindex da9b915620a..2e7cc678245 100644--- a/apps/temp-docs/docs/guides/storage/storage-sample.mdx+++ b/apps/temp-docs/docs/guides/storage/storage-sample.mdx@@ -1,12 +1,12 @@---id: storage-sample-title: "Storage Sample Doc"+title: 'Storage Sample Doc'description: Storage Sample Doc----import Tabs from '@theme/Tabs';-import TabsPanel from '@theme/TabsPanel';+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'## Description-Sample...\ No newline at end of file+Sample...diff --git a/apps/temp-docs/docs/guides/with-angular.mdx b/apps/temp-docs/docs/guides/with-angular.mdxindex ad0aae38d2d..2de33c1ae72 100644--- a/apps/temp-docs/docs/guides/with-angular.mdx+++ b/apps/temp-docs/docs/guides/with-angular.mdx@@ -2,142 +2,23 @@id: with-angulartitle: 'Quickstart: Angular'description: Learn how to use Supabase in your Angular App.+sidebar_label: Angular----# Quickstart: Angular+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-## Intro+<QuickstartIntro />-This example provides the steps to build a simple user management app (from scratch!) using Supabase and Angular. It includes:+-- Supabase [Database](/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/guides/auth): users can sign in with magic links (no passwords, only email).-- Supabase [Storage](/guides/storage): users can upload a photo.-- [Row Level Security](/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/guides/api): APIs will be automatically generated when you create your database tables.+### GitHub-By the end of this guide you'll have an app which allows users to login and update some basic profile details:+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/angular-user-management).---Clicking this button the application will:--- Launch and prepare the Postgres database in Supabase.-- Launch the app in Vercel.-- Fork the example into your own GitHub account.-- Prepare the deployed application with all the necessary environment variables.--If you want to do it yourself, let's get started!--### Github--Whenever you get stuck at any point, take a look at [this repo](https://github.com/angular-supa/supabase-angular-user-management).--## Project set up--Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.--### Create a project--1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.--### Set up the database schema--Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.--<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".-```--<video width="99%" muted playsInline controls="true">- <source src="/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="SQL" label="SQL">--```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,-- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);--alter table profiles enable row level security;--create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );--create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );--create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );---- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;---- Set up Storage!-insert into storage.buckets (id, name)-values ('avatars', 'avatars');--create policy "Avatar images are publicly accessible."- on storage.objects for select- using ( bucket_id = 'avatars' );--create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );-```--</TabsPanel>-</Tabs>--### Get the API Keys--Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.--<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-</Tabs>+<ProjectSetup />## Building the App@@ -161,7 +42,7 @@ npm install @supabase/supabase-jsAnd finally we want to save the environment variables in the `environment.ts` file.All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).-These variables will be exposed on the browser, and that's completely fine since we have [Row Level Security](/guides/auth#row-level-security) enabled on our Database.+These variables will be exposed on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.```ts title="environment.ts"export const environment = {@@ -175,10 +56,19 @@ Now that we have the API credentials in place, let's create a **SupabaseService*```ts title="src/app/supabase.service.ts"import { Injectable } from '@angular/core'-import { AuthChangeEvent, createClient, Session, SupabaseClient } from '@supabase/supabase-js'-import { environment } from '../environments/environment'+import {+ AuthChangeEvent,+ AuthSession,+ createClient,+ Session,+ SupabaseClient,+ User,+} from '@supabase/supabase-js'+import { environment } from 'src/environments/environment'+import { Database } from 'src/schema'export interface Profile {+ id?: stringusername: stringwebsite: stringavatar_url: string@@ -189,33 +79,38 @@ export interface Profile {})export class SupabaseService {private supabase: SupabaseClient+ _session: AuthSession | null = nullconstructor() {- this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey)- }-- get user() {- return this.supabase.auth.user()+ this.supabase = createClient(+ environment.supabaseUrl,+ environment.supabaseKey+ )}get session() {- return this.supabase.auth.session()+ this.supabase.auth.getSession().then(({ data }) => {+ this._session = data.session+ })+ return this._session}- get profile() {+ profile(user: User) {return this.supabase.from('profiles').select(`username, website, avatar_url`)- .eq('id', this.user?.id)+ .eq('id', user.id).single()}- authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {+ authChanges(+ callback: (event: AuthChangeEvent, session: Session | null) => void+ ) {return this.supabase.auth.onAuthStateChange(callback)}signIn(email: string) {- return this.supabase.auth.signIn({ email })+ return this.supabase.auth.signInWithOtp({ email })}signOut() {@@ -225,13 +120,10 @@ export class SupabaseService {updateProfile(profile: Profile) {const update = {...profile,- id: this.user?.id,updated_at: new Date(),}- return this.supabase.from('profiles').upsert(update, {- returning: 'minimal', // Don't return the value after inserting- })+ return this.supabase.from('profiles').upsert(update)}downLoadImage(path: string) {@@ -244,120 +136,136 @@ export class SupabaseService {}```-And one optional step is to update the CSS file `src/index.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/angular-supa/supabase-angular-user-management/main/src/styles.css).+Optionally, update [src/styles.css](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/angular-user-management/src/styles.css) to style the app.### Set up a Login componentLet's set up an Angular component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.Create an **AuthComponent** with `ng g c auth` Angular CLI command.-```ts title="src/app/auth.component.ts"-import { Component } from '@angular/core'-import { SupabaseService } from './supabase.service'+```ts title="src/app/auth/auth.component.ts"+import { Component, OnInit } from '@angular/core'+import { FormBuilder } from '@angular/forms'+import { SupabaseService } from '../supabase.service'@Component({selector: 'app-auth',- template: `- <div class="row flex-center flex">- <form class="col-6 form-widget">- <h1 class="header">Supabase + Angular</h1>- <p class="description">Sign in via magic link with your email below</p>- <div>- <input #input class="inputField" type="email" placeholder="Your email" />- </div>- <div>- <button- type="submit"- (click)="handleLogin(input.value)"- class="button block"- [disabled]="loading"- >- {{ loading ? 'Loading' : 'Send magic link' }}- </button>- </div>- </form>- </div>- `,+ templateUrl: './auth.component.html',+ styleUrls: ['./auth.component.css'],})-export class AuthComponent {+export class AuthComponent implements OnInit {loading = false- constructor(private readonly supabase: SupabaseService) {}+ signInForm = this.formBuilder.group({+ email: '',+ })++ constructor(+ private readonly supabase: SupabaseService,+ private readonly formBuilder: FormBuilder+ ) {}- async handleLogin(input: string) {+ ngOnInit(): void {}++ async onSubmit(): Promise<void> {try {this.loading = true- await this.supabase.signIn(input)+ const email = this.signInForm.value.email as string+ const { error } = await this.supabase.signIn(email)+ if (error) throw erroralert('Check your email for the login link!')} catch (error) {- alert(error.error_description || error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {+ this.signInForm.reset()this.loading = false}}}```-### Account page--After a user is signed in we can allow them to edit their profile details and manage their account.-Create an **AccountComponent** with `ng g c account` Angular CLI command.--```ts title="src/app/account.component.ts"-import { Component, Input, OnInit } from '@angular/core'-import { Profile, SupabaseService } from './supabase.service'-import { Session } from '@supabase/supabase-js'--@Component({- selector: 'app-account',- template: `- <div class="form-widget">+```html title="src/app/auth/auth.component.html"+<div class="row flex-center flex">+ <div class="col-6 form-widget" aria-live="polite">+ <h1 class="header">Supabase + Angular</h1>+ <p class="description">Sign in via magic link with your email below</p>+ <form [formGroup]="signInForm" (ngSubmit)="onSubmit()" class="form-widget"><div><label for="email">Email</label>- <input id="email" type="text" [value]="session?.user?.email" disabled />- </div>- <div>- <label for="username">Name</label>- <input #username id="username" type="text" [value]="profile?.username ?? ''" />- </div>- <div>- <label for="website">Website</label>- <input #website id="website" type="url" [value]="profile?.website ?? ''" />+ <input+ id="email"+ formControlName="email"+ class="inputField"+ type="email"+ placeholder="Your email"+ /></div>-<div><button- class="button primary block"- (click)="updateProfile(username.value, website.value)"+ type="submit"+ class="button block"[disabled]="loading">- {{ loading ? 'Loading ...' : 'Update' }}+ {{ loading ? 'Loading' : 'Send magic link' }}</button></div>+ </form>+ </div>+</div+```- <div>- <button class="button block" (click)="signOut()">Sign Out</button>- </div>- </div>- `,+### Account page++Users also need a way to edit their profile details and manage their accounts after signing in.+Create an **AccountComponent** with the `ng g c account` Angular CLI command.++```ts title="src/app/account/account.component.ts"+import { Component, Input, OnInit } from '@angular/core'+import { FormBuilder } from '@angular/forms'+import { AuthSession } from '@supabase/supabase-js'+import { Profile, SupabaseService } from '../supabase.service'++@Component({+ selector: 'app-account',+ templateUrl: './account.component.html',+ styleUrls: ['./account.component.css'],})export class AccountComponent implements OnInit {loading = false- profile: Profile | undefined-- @Input() session: Session | undefined+ profile!: Profile- constructor(private readonly supabase: SupabaseService) {}-- ngOnInit() {- this.getProfile()+ @Input()+ session!: AuthSession++ updateProfileForm = this.formBuilder.group({+ username: '',+ website: '',+ avatar_url: '',+ })++ constructor(+ private readonly supabase: SupabaseService,+ private formBuilder: FormBuilder+ ) {}++ async ngOnInit(): Promise<void> {+ await this.getProfile()++ const { username, website, avatar_url } = this.profile+ this.updateProfileForm.patchValue({+ username,+ website,+ avatar_url,+ })}async getProfile() {try {this.loading = true- let { data: profile, error, status } = await this.supabase.profile+ const { user } = this.session+ let { data: profile, error, status } = await this.supabase.profile(user)if (error && status !== 406) {throw error@@ -367,18 +275,34 @@ export class AccountComponent implements OnInit {this.profile = profile}} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {this.loading = false}}- async updateProfile(username: string, website: string, avatar_url: string = '') {+ async updateProfile(): Promise<void> {try {this.loading = true- await this.supabase.updateProfile({ username, website, avatar_url })+ const { user } = this.session++ const username = this.updateProfileForm.value.username as string+ const website = this.updateProfileForm.value.website as string+ const avatar_url = this.updateProfileForm.value.avatar_url as string++ const { error } = await this.supabase.updateProfile({+ id: user.id,+ username,+ website,+ avatar_url,+ })+ if (error) throw error} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {this.loading = false}@@ -390,6 +314,37 @@ export class AccountComponent implements OnInit {}```+```html title="src/app/account/account.component.html"+<form+ [formGroup]="updateProfileForm"+ (ngSubmit)="updateProfile()"+ class="form-widget"+>+ <div>+ <label for="email">Email</label>+ <input id="email" type="text" [value]="session.user.email" disabled />+ </div>+ <div>+ <label for="username">Name</label>+ <input formControlName="username" id="username" type="text" />+ </div>+ <div>+ <label for="website">Website</label>+ <input formControlName="website" id="website" type="url" />+ </div>++ <div>+ <button type="submit" class="button primary block" [disabled]="loading">+ {{ loading ? 'Loading ...' : 'Update' }}+ </button>+ </div>++ <div>+ <button class="button block" (click)="signOut()">Sign Out</button>+ </div>+</form>+```+### Launch!Now that we have all the components in place, let's update **AppComponent**:@@ -400,16 +355,12 @@ import { SupabaseService } from './supabase.service'@Component({selector: 'app-root',- template: `- <div class="container" style="padding: 50px 0 100px 0">- <app-account *ngIf="session; else auth" [session]="session"></app-account>- <ng-template #auth>- <app-auth></app-auth>- </ng-template>- </div>- `,+ templateUrl: './app.component.html',+ styleUrls: ['./app.component.css'],})export class AppComponent implements OnInit {+ title = 'angular-user-management'+session = this.supabase.sessionconstructor(private readonly supabase: SupabaseService) {}@@ -420,6 +371,41 @@ export class AppComponent implements OnInit {}```+```html title="src/app/app.component.html"+<div class="container" style="padding: 50px 0 100px 0">+ <app-account *ngIf="session; else auth" [session]="session"></app-account>+ <ng-template #auth>+ <app-auth></app-auth>+ </ng-template>+</div>+```++`app.module.ts` also needs to be modified to include the `ReactiveFormsModule` from the `@angular/forms` package.++```ts title="src/app/app.module.ts"+import { NgModule } from '@angular/core'+import { BrowserModule } from '@angular/platform-browser'++import { AppComponent } from './app.component'+import { AuthComponent } from './auth/auth.component'+import { AccountComponent } from './account/account.component'+import { ReactiveFormsModule } from '@angular/forms'+import { AvatarComponent } from './avatar/avatar.component'++@NgModule({+ declarations: [+ AppComponent,+ AuthComponent,+ AccountComponent,+ AvatarComponent,+ ],+ imports: [BrowserModule, ReactiveFormsModule],+ providers: [],+ bootstrap: [AppComponent],+})+export class AppModule {}+```+Once that's done, run this in a terminal window:```bash@@ -428,56 +414,33 @@ npm run startAnd then open the browser to [localhost:4200](http://localhost:4200) and you should see the completed app.-+## Bonus: Profile photos-Every Supabase project is configured with [Storage](/guides/storage) for managing large files like photos and videos.+Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.### Create an upload widgetLet's create an avatar for the user so that they can upload a profile photo.Create an **AvatarComponent** with `ng g c avatar` Angular CLI command.-```ts title="src/app/avatar.component.ts"-import { Component, EventEmitter, Input, Output } from '@angular/core'-import { SupabaseService } from './supabase.service'-import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'+```ts title="src/app/avatar/avatar.component.ts"+import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'+import { SafeResourceUrl, DomSanitizer } from '@angular/platform-browser'+import { SupabaseService } from '../supabase.service'@Component({selector: 'app-avatar',- template: `- <div>- <img- *ngIf="_avatarUrl"- [src]="_avatarUrl"- alt="Avatar"- class="avatar image"- style="height: 150px; width: 150px"- />- </div>- <div *ngIf="!_avatarUrl" class="avatar no-image" style="height: 150px; width: 150px"></div>- <div style="width: 150px">- <label class="button primary block" for="single">- {{ uploading ? 'Uploading ...' : 'Upload' }}- </label>- <input- style="visibility: hidden;position: absolute"- type="file"- id="single"- accept="image/*"- (change)="uploadAvatar($event)"- [disabled]="uploading"- />- </div>- `,+ templateUrl: './avatar.component.html',+ styleUrls: ['./avatar.component.css'],})-export class AvatarComponent {+export class AvatarComponent implements OnInit {_avatarUrl: SafeResourceUrl | undefineduploading = false@Input()- set avatarUrl(url: string | undefined) {+ set avatarUrl(url: string | null) {if (url) {this.downloadImage(url)}@@ -485,14 +448,25 @@ export class AvatarComponent {@Output() upload = new EventEmitter<string>()- constructor(private readonly supabase: SupabaseService, private readonly dom: DomSanitizer) {}+ constructor(+ private readonly supabase: SupabaseService,+ private readonly dom: DomSanitizer+ ) {}++ ngOnInit(): void {}async downloadImage(path: string) {try {const { data } = await this.supabase.downLoadImage(path)- this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data))+ if (data instanceof Blob) {+ this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(+ URL.createObjectURL(data)+ )+ }} catch (error) {- console.error('Error downloading image: ', error.message)+ if (error instanceof Error) {+ console.error('Error downloading image: ', error.message)+ }}}@@ -505,13 +479,14 @@ export class AvatarComponent {const file = event.target.files[0]const fileExt = file.name.split('.').pop()- const fileName = `${Math.random()}.${fileExt}`- const filePath = `${fileName}`+ const filePath = `${Math.random()}.${fileExt}`await this.supabase.uploadAvatar(filePath, file)this.upload.emit(filePath)} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {this.uploading = false}@@ -519,19 +494,74 @@ export class AvatarComponent {}```+```html title="src/app/avatar/avatar.component.html"+<div>+ <img+ *ngIf="_avatarUrl"+ [src]="_avatarUrl"+ alt="Avatar"+ class="avatar image"+ style="height: 150px; width: 150px"+ />+</div>+<div+ *ngIf="!_avatarUrl"+ class="avatar no-image"+ style="height: 150px; width: 150px"+></div>+<div style="width: 150px">+ <label class="button primary block" for="single">+ {{ uploading ? 'Uploading ...' : 'Upload' }}+ </label>+ <input+ style="visibility: hidden;position: absolute"+ type="file"+ id="single"+ accept="image/*"+ (change)="uploadAvatar($event)"+ [disabled]="uploading"+ />+</div>+```+### Add the new widgetAnd then we can add the widget on top of the **AccountComponent** html template:+```html title="src/app/account.component.html"+<form+ [formGroup]="updateProfileForm"+ (ngSubmit)="updateProfile()"+ class="form-widget"+>+ <app-avatar [avatarUrl]="this.avatarUrl" (upload)="updateAvatar($event)">+ </app-avatar>+ <!-- input fields -->+</form>+```++And add an `updateAvatar` function along with an `avatarUrl` getter to the **AccountComponent** typescript file:+```ts title="src/app/account.component.ts"-template: `-<app-avatar- [avatarUrl]="this.profile?.avatar_url"- (upload)="updateProfile(username.value, website.value, $event)">-</app-avatar>--<!-- input fields -->-`+@Component({+ selector: 'app-account',+ templateUrl: './account.component.html',+ styleUrls: ['./account.component.css'],+})+export class AccountComponent implements OnInit {+ // ...+ get avatarUrl() {+ return this.updateProfileForm.value.avatar_url as string+ }++ async updateAvatar(event: string): Promise<void> {+ this.updateProfileForm.patchValue({+ avatar_url: event,+ })+ await this.updateProfile()+ }+ // ...+}```## Next stepsdiff --git a/apps/temp-docs/docs/guides/with-expo.mdx b/apps/temp-docs/docs/guides/with-expo.mdxnew file mode 100644index 00000000000..598fbf8f03d--- /dev/null+++ b/apps/temp-docs/docs/guides/with-expo.mdx@@ -0,0 +1,542 @@+---+id: with-expo+title: 'Quickstart: Expo'+description: Learn how to use Supabase in your React Native App.+sidebar_label: Expo+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/expo-user-management).++<ProjectSetup />++## Building the App++Let's start building the React Native app from scratch.++### Initialize a React Native app++We can use [`expo`](https://docs.expo.dev/get-started/create-a-new-app/) to initialize+an app called `expo-user-management`:++```bash+npx create-expo-app -t expo-template-blank-typescript expo-user-management++cd expo-user-management+```++Then let's install the additional dependencies: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+npm install react-native-elements @react-native-async-storage/async-storage react-native-url-polyfill+```++Now let's create a helper file to initialize the Supabase client.+We need the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).+These variables will be exposed on the browser, and that's completely fine since we have+[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```ts title="lib/supabase.ts"+import AsyncStorage from '@react-native-async-storage/async-storage'+import { createClient } from '@supabase/supabase-js'++const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL+const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEY++export const supabase = createClient(supabaseUrl, supabaseAnonKey, {+ auth: {+ storage: AsyncStorage as any,+ autoRefreshToken: true,+ persistSession: true,+ detectSessionInUrl: false,+ },+})+```++### Set up a Login component++Let's set up a React Native component to manage logins and sign ups.+Users would be able to sign in with their email and password.++```tsx title="components/Auth.tsx"+import React, { useState } from 'react'+import { Alert, StyleSheet, View } from 'react-native'+import { supabase } from '../lib/supabase'+import { Button, Input } from 'react-native-elements'++export default function Auth() {+ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [loading, setLoading] = useState(false)++ async function signInWithEmail() {+ setLoading(true)+ const { error } = await supabase.auth.signInWithPassword({+ email: email,+ password: password,+ })++ if (error) Alert.alert(error.message)+ setLoading(false)+ }++ async function signUpWithEmail() {+ setLoading(true)+ const { error } = await supabase.auth.signUp({+ email: email,+ password: password,+ })++ if (error) Alert.alert(error.message)+ setLoading(false)+ }++ return (+ <View>+ <View style={[styles.verticallySpaced, styles.mt20]}>+ <Input+ label="Email"+ leftIcon={{ type: 'font-awesome', name: 'envelope' }}+ onChangeText={(text) => setEmail(text)}+ value={email}+ placeholder="[email protected]"+ autoCapitalize={'none'}+ />+ </View>+ <View style={styles.verticallySpaced}>+ <Input+ label="Password"+ leftIcon={{ type: 'font-awesome', name: 'lock' }}+ onChangeText={(text) => setPassword(text)}+ value={password}+ secureTextEntry={true}+ placeholder="Password"+ autoCapitalize={'none'}+ />+ </View>+ <View style={[styles.verticallySpaced, styles.mt20]}>+ <Button+ title="Sign in"+ disabled={loading}+ onPress={() => signInWithEmail()}+ />+ </View>+ <View style={styles.verticallySpaced}>+ <Button+ title="Sign up"+ disabled={loading}+ onPress={() => signUpWithEmail()}+ />+ </View>+ </View>+ )+}++const styles = StyleSheet.create({+ container: {+ marginTop: 40,+ padding: 12,+ },+ verticallySpaced: {+ paddingTop: 4,+ paddingBottom: 4,+ alignSelf: 'stretch',+ },+ mt20: {+ marginTop: 20,+ },+})+```++### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.++Let's create a new component for that called `Account.tsx`.++```tsx title="components/Account.tsx"+import { useState, useEffect } from 'react'+import { supabase } from '../lib/supabase'+import { StyleSheet, View, Alert } from 'react-native'+import { Button, Input } from 'react-native-elements'+import { Session } from '@supabase/supabase-js'++export default function Account({ session }: { session: Session }) {+ const [loading, setLoading] = useState(true)+ const [username, setUsername] = useState('')+ const [website, setWebsite] = useState('')+ const [avatarUrl, setAvatarUrl] = useState('')++ useEffect(() => {+ if (session) getProfile()+ }, [session])++ async function getProfile() {+ try {+ setLoading(true)+ if (!session?.user) throw new Error('No user on the session!')++ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', session?.user.id)+ .single()+ if (error && status !== 406) {+ throw error+ }++ if (data) {+ setUsername(data.username)+ setWebsite(data.website)+ setAvatarUrl(data.avatar_url)+ }+ } catch (error) {+ if (error instanceof Error) {+ Alert.alert(error.message)+ }+ } finally {+ setLoading(false)+ }+ }++ async function updateProfile({+ username,+ website,+ avatar_url,+ }: {+ username: string+ website: string+ avatar_url: string+ }) {+ try {+ setLoading(true)+ if (!session?.user) throw new Error('No user on the session!')++ const updates = {+ id: session?.user.id,+ username,+ website,+ avatar_url,+ updated_at: new Date(),+ }++ let { error } = await supabase.from('profiles').upsert(updates)++ if (error) {+ throw error+ }+ } catch (error) {+ if (error instanceof Error) {+ Alert.alert(error.message)+ }+ } finally {+ setLoading(false)+ }+ }++ return (+ <View>+ <View style={[styles.verticallySpaced, styles.mt20]}>+ <Input label="Email" value={session?.user?.email} disabled />+ </View>+ <View style={styles.verticallySpaced}>+ <Input+ label="Username"+ value={username || ''}+ onChangeText={(text) => setUsername(text)}+ />+ </View>+ <View style={styles.verticallySpaced}>+ <Input+ label="Website"+ value={website || ''}+ onChangeText={(text) => setWebsite(text)}+ />+ </View>++ <View style={[styles.verticallySpaced, styles.mt20]}>+ <Button+ title={loading ? 'Loading ...' : 'Update'}+ onPress={() =>+ updateProfile({ username, website, avatar_url: avatarUrl })+ }+ disabled={loading}+ />+ </View>++ <View style={styles.verticallySpaced}>+ <Button title="Sign Out" onPress={() => supabase.auth.signOut()} />+ </View>+ </View>+ )+}++const styles = StyleSheet.create({+ container: {+ marginTop: 40,+ padding: 12,+ },+ verticallySpaced: {+ paddingTop: 4,+ paddingBottom: 4,+ alignSelf: 'stretch',+ },+ mt20: {+ marginTop: 20,+ },+})+```++### Launch!++Now that we have all the components in place, let's update `App.tsx`:++```tsx title="App.tsx"+import 'react-native-url-polyfill/auto'+import { useState, useEffect } from 'react'+import { supabase } from './lib/supabase'+import Auth from './components/Auth'+import Account from './components/Account'+import { View } from 'react-native'+import { Session } from '@supabase/supabase-js'++export default function App() {+ const [session, setSession] = useState<Session | null>(null)++ useEffect(() => {+ supabase.auth.getSession().then(({ data: { session } }) => {+ setSession(session)+ })++ supabase.auth.onAuthStateChange((_event, session) => {+ setSession(session)+ })+ }, [])++ return (+ <View>+ {session && session.user ? (+ <Account key={session.user.id} session={session} />+ ) : (+ <Auth />+ )}+ </View>+ )+}+```++Once that's done, run this in a terminal window:++```bash+npm start+```++And then press the appropriate key for the environment you want to test the app in and you should see the completed app.++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like+photos and videos.++### Additional dependency installation++You will need a file picker that works on the environment you will build the project for, we will use react-native-document-picker in this example.++```bash+expo install react-native-document-picker+```++### Create an upload widget++Let's create an avatar for the user so that they can upload a profile photo.+We can start by creating a new component:++```tsx title="components/Avatar.tsx"+import { useState, useEffect } from 'react'+import { supabase } from '../lib/supabase'+import { StyleSheet, View, Alert, Image, Button } from 'react-native'+import DocumentPicker, {+ isCancel,+ isInProgress,+ types,+} from 'react-native-document-picker'++interface Props {+ size: number+ url: string | null+ onUpload: (filePath: string) => void+}++export default function Avatar({ url, size = 150, onUpload }: Props) {+ const [uploading, setUploading] = useState(false)+ const [avatarUrl, setAvatarUrl] = useState<string | null>(null)+ const avatarSize = { height: size, width: size }++ useEffect(() => {+ if (url) downloadImage(url)+ }, [url])++ async function downloadImage(path: string) {+ try {+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)++ if (error) {+ throw error+ }++ const fr = new FileReader()+ fr.readAsDataURL(data)+ fr.onload = () => {+ setAvatarUrl(fr.result as string)+ }+ } catch (error) {+ if (error instanceof Error) {+ console.log('Error downloading image: ', error.message)+ }+ }+ }++ async function uploadAvatar() {+ try {+ setUploading(true)++ const file = await DocumentPicker.pickSingle({+ presentationStyle: 'fullScreen',+ copyTo: 'cachesDirectory',+ type: types.images,+ mode: 'open',+ })++ const photo = {+ uri: file.fileCopyUri,+ type: file.type,+ name: file.name,+ }++ const formData = new FormData()+ formData.append('file', photo)++ const fileExt = file.name.split('.').pop()+ const filePath = `${Math.random()}.${fileExt}`++ let { error } = await supabase.storage+ .from('avatars')+ .upload(filePath, formData)++ if (error) {+ throw error+ }++ onUpload(filePath)+ } catch (error) {+ if (isCancel(error)) {+ console.warn('cancelled')+ // User cancelled the picker, exit any dialogs or menus and move on+ } else if (isInProgress(error)) {+ console.warn(+ 'multiple pickers were opened, only the last will be considered'+ )+ } else if (error instanceof Error) {+ Alert.alert(error.message)+ } else {+ throw error+ }+ } finally {+ setUploading(false)+ }+ }++ return (+ <View>+ {avatarUrl ? (+ <Image+ source={{ uri: avatarUrl }}+ accessibilityLabel="Avatar"+ style={[avatarSize, styles.avatar, styles.image]}+ />+ ) : (+ <View style={[avatarSize, styles.avatar, styles.noImage]} />+ )}+ <View>+ <Button+ title={uploading ? 'Uploading ...' : 'Upload'}+ onPress={uploadAvatar}+ disabled={uploading}+ />+ </View>+ </View>+ )+}++const styles = StyleSheet.create({+ avatar: {+ borderRadius: 5,+ overflow: 'hidden',+ maxWidth: '100%',+ },+ image: {+ objectFit: 'cover',+ paddingTop: 0,+ },+ noImage: {+ backgroundColor: '#333',+ border: '1px solid rgb(200, 200, 200)',+ borderRadius: 5,+ },+})+```++### Add the new widget++And then we can add the widget to the Account page:++```tsx title="components/Account.tsx"+// Import the new component+import Avatar from './Avatar'++// ...+ return (+ <View>+ {/* Add to the body */}+ <View>+ <Avatar+ size={200}+ url={avatarUrl}+ onUpload={(url: string) => {+ setAvatarUrl(url)+ updateProfile({ username, website, avatar_url: url })+ }}+ />+ </View>+ {/* ... */}+ </View>+ )+}+// ...+```++Now you will need to run the prebuild command to get the application working on your chosen platform.++```bash+expo prebuild+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-flutter.mdx b/apps/temp-docs/docs/guides/with-flutter.mdxindex f150b2d309f..a09a5b9f56d 100644--- a/apps/temp-docs/docs/guides/with-flutter.mdx+++ b/apps/temp-docs/docs/guides/with-flutter.mdx@@ -2,134 +2,23 @@id: with-fluttertitle: 'Quickstart: Flutter'description: Learn how to use Supabase in your Flutter App.+sidebar_label: Flutter----# Quickstart: Flutter+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-## Intro+<QuickstartIntro />-This example provides the steps to build a simple user management app (from scratch!) using Supabase and Flutter. It includes:+-- Supabase [Database](/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/guides/auth): users can sign in with magic links (no passwords, only email).-<!-- - Supabase [Storage](/guides/storage): users can upload a photo. -->-- [Row Level Security](/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/guides/api): APIs will be automatically generated when you create your database tables.+### GitHub-By the end of this guide you'll have an app which allows users to login and update some basic profile details:+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/flutter-user-management).---### Github--Whenever you get stuck at any point, take a look at [this repo](https://github.com/supasquad/supabase-flutter-quickstart).--## Project set up--Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.--### Create a project--1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.--### Set up the database schema--Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.--<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".-```--<video width="99%" muted playsInline controls="true">- <source src="/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="SQL" label="SQL">--```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,-- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);--alter table profiles enable row level security;--create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );--create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );--create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );---- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;---- Set up Storage!-insert into storage.buckets (id, name, public)-values ('avatars', 'avatars', true);--create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );--```--</TabsPanel>-</Tabs>--### Get the API Keys--Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.--<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" key on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-</Tabs>+<ProjectSetup />## Building the App@@ -137,19 +26,19 @@ Let's start building the Flutter app from scratch.### Initialize a Flutter app-We can use [`flutter create`](https://flutter.dev/get-started/test-drive) to initialize+We can use [`flutter create`](https://flutter.dev/docs/get-started/test-drive) to initializean app called `supabase_quickstart`:```bashflutter create supabase_quickstart```-Then let's install the only additional dependency: [`supabase_flutter`](https://github.com/supabase/supabase-flutter)+Then let's install the only additional dependency: [`supabase_flutter`](https://pub.dev/packages/supabase_flutter)-Run the following command to get the newest version of `supabase_flutter` to your project.+Copy and paste the following line in your pubspec.yaml to install the package:-```bash-flutter pub add supabase_flutter+```yaml+supabase_flutter: ^1.0.0```Run `flutter pub get` to install the dependencies.@@ -158,14 +47,10 @@ Run `flutter pub get` to install the dependencies.Now that we have the dependencies installed let's setup deep links so users who have logged in via magic link or OAuth can come back to the app.-```sh-1. Go to the "Authentication" section.-2. Click "Settings" in the sidebar.-3. Type `io.supabase.flutterquickstart://login-callback/` in the Additional Redirect URLs input field.-4. Hit save.-```+1. Go to [Authentication Settings](https://app.supabase.com/project/_/auth/settings) in the Dashboard.+1. In **Redirect URLs**, add `io.supabase.flutterquickstart://login-callback/` as a new domain.-+That is it on Supabase's end and the rest are platform specific settings:@@ -227,84 +112,26 @@ There are no additional configurations.Now that we have deep links ready let's initialize the Supabase client inside our `main` function with the API credentials that you copied [earlier](#get-the-api-keys).These variables will be exposed on the app, and that's completely fine since we have-[Row Level Security](/guides/auth#row-level-security) enabled on our Database.+[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.```dart title="lib/main.dart"Future<void> main() async {WidgetsFlutterBinding.ensureInitialized();await Supabase.initialize(- url: '[YOUR_SUPABASE_URL]',- anonKey: '[YOUR_SUPABASE_ANON_KEY]',+ url: 'YOUR_SUPABASE_URL',+ anonKey: 'YOUR_SUPABASE_ANON_KEY',);runApp(MyApp());}```-### Set up AuthState--In order to handle deep links for Android and iOS, let's create a class that will do just that.-`supabase_flutter` plugin comes with `SupabaseAuthState` class where we can inherit from to react to various deep link events.--```dart title="lib/components/auth_state.dart"-import 'package:flutter/material.dart';-import 'package:supabase/supabase.dart';-import 'package:supabase_flutter/supabase_flutter.dart';-import 'package:supabase_quickstart/utils/constants.dart';--class AuthState<T extends StatefulWidget> extends SupabaseAuthState<T> {- @override- void onUnauthenticated() {- if (mounted) {- Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);- }- }-- @override- void onAuthenticated(Session session) {- if (mounted) {- Navigator.of(context)- .pushNamedAndRemoveUntil('/account', (route) => false);- }- }-- @override- void onPasswordRecovery(Session session) {}-- @override- void onErrorAuthenticating(String message) {- context.showErrorSnackBar(message: message);- }-}-```--### Set up AuthRequiredState--We might want to show certain pages to the users only if they are signed in.-For that we can create a handy `AuthRequiredState` class that we can inherit from for pages where the users need to be authenticated.-`AuthRequiredState` will inherit `SupabaseAuthRequiredState` which is provided by `supabase_flutter` package.--```dart title="lib/components/auth_required_state.dart"-import 'package:flutter/material.dart';-import 'package:supabase_flutter/supabase_flutter.dart';--class AuthRequiredState<T extends StatefulWidget>- extends SupabaseAuthRequiredState<T> {- @override- void onUnauthenticated() {- /// Users will be sent back to the LoginPage if they sign out.- if (mounted) {- /// Users will be sent back to the LoginPage if they sign out.- Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);- }- }-}-```+### Setting up some constants and handy functionsLet's also create a constant file to make it easier to use Supabase client.We will also include an extension method declaration to call `showSnackBar` with one line of code.-```dart title="lib/utils/constants.dart"+```dart title="lib/constants.dart"import 'package:flutter/material.dart';import 'package:supabase_flutter/supabase_flutter.dart';@@ -330,24 +157,40 @@ extension ShowSnackBar on BuildContext {### Set up Splash ScreenLet's create a splash screen that will be shown to users right after they open the app.-This splash screen inherits `AuthState` to redirect users to the appropriate pages depending on their authentication state.+This screen retrieves the current session and redirects the user accordingly.```dart title="lib/pages/splash_page.dart"import 'package:flutter/material.dart';-import 'package:supabase_quickstart/components/auth_state.dart';+import 'package:supabase_quickstart/constants.dart';class SplashPage extends StatefulWidget {- const SplashPage({Key? key}) : super(key: key);+ const SplashPage({super.key});@override_SplashPageState createState() => _SplashPageState();}-class _SplashPageState extends AuthState<SplashPage> {+class _SplashPageState extends State<SplashPage> {+ bool _redicrectCalled = false;@override- void initState() {- recoverSupabaseSession();- super.initState();+ void didChangeDependencies() {+ super.didChangeDependencies();+ _redirect();+ }++ Future<void> _redirect() async {+ await Future.delayed(Duration.zero);+ if (_redicrectCalled || !mounted) {+ return;+ }++ _redicrectCalled = true;+ final session = supabase.auth.currentSession;+ if (session != null) {+ Navigator.of(context).pushReplacementNamed('/account');+ } else {+ Navigator.of(context).pushReplacementNamed('/login');+ }}@override@@ -357,48 +200,56 @@ class _SplashPageState extends AuthState<SplashPage> {);}}+```### Set up a Login pageLet's create a Flutter widget to manage logins and sign ups.We'll use Magic Links, so users can sign in with their email without using passwords.-This page will also inherit `AuthState` as it will handle user login.+Notice that this page sets up a listener on the user's auth state using `onAuthStateChange`.+A new event will fire when the user comes back to the app by clicking their magic link, which this page can catch and redirect the user accordingly.```dart title="lib/pages/login_page.dart"+import 'dart:async';+import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';-import 'package:supabase/supabase.dart';-import 'package:supabase_quickstart/components/auth_state.dart';-import 'package:supabase_quickstart/utils/constants.dart';+import 'package:supabase_flutter/supabase_flutter.dart';++import 'package:supabase_quickstart/constants.dart';class LoginPage extends StatefulWidget {- const LoginPage({Key? key}) : super(key: key);+ const LoginPage({super.key});@override_LoginPageState createState() => _LoginPageState();}-class _LoginPageState extends AuthState<LoginPage> {+class _LoginPageState extends State<LoginPage> {bool _isLoading = false;+ bool _redirecting = false;late final TextEditingController _emailController;+ late final StreamSubscription<AuthState> _authStateSubscription;Future<void> _signIn() async {setState(() {_isLoading = true;});- final response = await supabase.auth.signIn(+ try {+ await supabase.auth.signInWithOtp(email: _emailController.text,- options: AuthOptions(- redirectTo: kIsWeb- ? null- : 'io.supabase.flutterquickstart://login-callback/'));- final error = response.error;- if (error != null) {+ emailRedirectTo:+ kIsWeb ? null : 'io.supabase.flutterquickstart://login-callback/',+ );+ if (mounted) {+ context.showSnackBar(message: 'Check your email for login link!');+ _emailController.clear();+ }+ } on AuthException catch (error) {context.showErrorSnackBar(message: error.message);- } else {- context.showSnackBar(message: 'Check your email for login link!');- _emailController.clear();+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected error occured');}setState(() {@@ -408,13 +259,22 @@ class _LoginPageState extends AuthState<LoginPage> {@overridevoid initState() {- super.initState();_emailController = TextEditingController();+ _authStateSubscription = supabase.auth.onAuthStateChange.listen((data) {+ if (_redirecting) return;+ final session = data.session;+ if (session != null) {+ _redirecting = true;+ Navigator.of(context).pushReplacementNamed('/account');+ }+ });+ super.initState();}@overridevoid dispose() {_emailController.dispose();+ _authStateSubscription.cancel();super.dispose();}@@ -447,46 +307,48 @@ class _LoginPageState extends AuthState<LoginPage> {After a user is signed in we can allow them to edit their profile details and manage their account.Let's create a new widget called `account_page.dart` for that.-Note that this page will inherit `AuthRequiredState` as user needs to be authenticated to view this page.```dart title="lib/pages/account_page.dart"import 'package:flutter/material.dart';-import 'package:supabase/supabase.dart';-import 'package:supabase_quickstart/components/auth_required_state.dart';-import 'package:supabase_quickstart/utils/constants.dart';+import 'package:supabase_flutter/supabase_flutter.dart';+import 'package:supabase_quickstart/components/avatar.dart';+import 'package:supabase_quickstart/constants.dart';class AccountPage extends StatefulWidget {- const AccountPage({Key? key}) : super(key: key);+ const AccountPage({super.key});@override_AccountPageState createState() => _AccountPageState();}-class _AccountPageState extends AuthRequiredState<AccountPage> {+class _AccountPageState extends State<AccountPage> {final _usernameController = TextEditingController();final _websiteController = TextEditingController();+ String? _avatarUrl;var _loading = false;/// Called once a user id is received within `onAuthenticated()`- Future<void> _getProfile(String userId) async {+ Future<void> _getProfile() async {setState(() {_loading = true;});- final response = await supabase- .from('profiles')- .select()- .eq('id', userId)- .single()- .execute();- final error = response.error;- if (error != null && response.status != 406) {- context.showErrorSnackBar(message: error.message);- }- final data = response.data;- if (data != null) {++ try {+ final userId = supabase.auth.currentUser!.id;+ final data = await supabase+ .from('profiles')+ .select()+ .eq('id', userId)+ .single() as Map;_usernameController.text = (data['username'] ?? '') as String;_websiteController.text = (data['website'] ?? '') as String;+ _avatarUrl = (data['avatar_url'] ?? '') as String;+ } on PostgrestException catch (error) {+ context.showErrorSnackBar(message: error.message);+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected exception occured');}+setState(() {_loading = false;});@@ -506,12 +368,15 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {'website': website,'updated_at': DateTime.now().toIso8601String(),};- final response = await supabase.from('profiles').upsert(updates).execute();- final error = response.error;- if (error != null) {+ try {+ await supabase.from('profiles').upsert(updates);+ if (mounted) {+ context.showSnackBar(message: 'Successfully updated profile!');+ }+ } on PostgrestException catch (error) {context.showErrorSnackBar(message: error.message);- } else {- context.showSnackBar(message: 'Successfully updated profile!');+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpeted error occured');}setState(() {_loading = false;@@ -519,19 +384,22 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {}Future<void> _signOut() async {- final response = await supabase.auth.signOut();- final error = response.error;- if (error != null) {+ try {+ await supabase.auth.signOut();+ } on AuthException catch (error) {context.showErrorSnackBar(message: error.message);+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected error occured');+ }+ if (mounted) {+ Navigator.of(context).pushReplacementNamed('/');}}@override- void onAuthenticated(Session session) {- final user = session.user;- if (user != null) {- _getProfile(user.id);- }+ void initState() {+ super.initState();+ _getProfile();}@override@@ -559,10 +427,11 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {),const SizedBox(height: 18),ElevatedButton(- onPressed: _updateProfile,- child: Text(_loading ? 'Saving...' : 'Update')),+ onPressed: _updateProfile,+ child: Text(_loading ? 'Saving...' : 'Update'),+ ),const SizedBox(height: 18),- ElevatedButton(onPressed: _signOut, child: const Text('Sign Out')),+ TextButton(onPressed: _signOut, child: const Text('Sign Out')),],),);@@ -582,12 +451,10 @@ import 'package:supabase_quickstart/pages/login_page.dart';import 'package:supabase_quickstart/pages/splash_page.dart';Future<void> main() async {- WidgetsFlutterBinding.ensureInitialized();-await Supabase.initialize(// TODO: Replace credentials with your own- url: '[YOUR_SUPABASE_URL]',- anonKey: '[YOUR_SUPABASE_ANNON_KEY]',+ url: 'YOUR_SUPABASE_URL',+ anonKey: 'YOUR_SUPABASE_ANON_KEY',);runApp(MyApp());}@@ -599,10 +466,15 @@ class MyApp extends StatelessWidget {title: 'Supabase Flutter',theme: ThemeData.dark().copyWith(primaryColor: Colors.green,+ textButtonTheme: TextButtonThemeData(+ style: TextButton.styleFrom(+ foregroundColor: Colors.green,+ ),+ ),elevatedButtonTheme: ElevatedButtonThemeData(style: ElevatedButton.styleFrom(- onPrimary: Colors.white,- primary: Colors.green,+ foregroundColor: Colors.white,+ backgroundColor: Colors.green,),),),@@ -631,21 +503,27 @@ flutter run -d web-server --web-hostname localhost --web-port 3000And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.-+## Bonus: Profile photos-Every Supabase project is configured with [Storage](/guides/storage) for managing large files like+Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files likephotos and videos.+### Making sure we have a public bucket++We will be storing the image as a publicly sharable image.+Make sure your `avatars` bucket is set to public, and if it is not, change the publicity by clicking the dot menu that appears when you hover over the bucket name.+You should see an orange `Public` badge next to your bucket name if your bucket is set to public.+### Adding image uploading feature to Account pageWe will use [`image_picker`](https://pub.dev/packages/image_picker) plugin to select an image from the device.-Run the following command to install it.+Add the following line in your pubspec.yaml file to install `image_picker`:-```bash-flutter pub add image_picker+```yaml+image_picker: ^0.8.4```Using [`image_picker`](https://pub.dev/packages/image_picker) requires some additional preparation depending on the platform.@@ -661,14 +539,15 @@ We can start by creating a new component:```dart title="lib/components/avatar.dart"import 'package:flutter/material.dart';import 'package:image_picker/image_picker.dart';-import 'package:supabase_quickstart/utils/constants.dart';+import 'package:supabase_flutter/supabase_flutter.dart';+import 'package:supabase_quickstart/constants.dart';class Avatar extends StatefulWidget {const Avatar({- Key? key,+ super.key,required this.imageUrl,required this.onUpload,- }) : super(key: key);+ });final String? imageUrl;final void Function(String) onUpload;@@ -684,7 +563,7 @@ class _AvatarState extends State<Avatar> {Widget build(BuildContext context) {return Column(children: [- if (widget.imageUrl == null)+ if (widget.imageUrl == null || widget.imageUrl!.isEmpty)Container(width: 150,height: 150,@@ -709,8 +588,8 @@ class _AvatarState extends State<Avatar> {}Future<void> _upload() async {- final _picker = ImagePicker();- final imageFile = await _picker.pickImage(+ final picker = ImagePicker();+ final imageFile = await picker.pickImage(source: ImageSource.gallery,maxWidth: 300,maxHeight: 300,@@ -720,23 +599,31 @@ class _AvatarState extends State<Avatar> {}setState(() => _isLoading = true);- final bytes = await imageFile.readAsBytes();- final fileExt = imageFile.path.split('.').last;- final fileName = '${DateTime.now().toIso8601String()}.$fileExt';- final filePath = fileName;- final response =- await supabase.storage.from('avatars').uploadBinary(filePath, bytes);+ try {+ final bytes = await imageFile.readAsBytes();+ final fileExt = imageFile.path.split('.').last;+ final fileName = '${DateTime.now().toIso8601String()}.$fileExt';+ final filePath = fileName;+ await supabase.storage.from('avatars').uploadBinary(+ filePath,+ bytes,+ fileOptions: FileOptions(contentType: imageFile.mimeType),+ );+ final imageUrlResponse = await supabase.storage+ .from('avatars')+ .createSignedUrl(filePath, 60 * 60 * 24 * 365 * 10);+ widget.onUpload(imageUrlResponse);+ } on StorageException catch (error) {+ if (mounted) {+ context.showErrorSnackBar(message: error.message);+ }+ } catch (error) {+ if (mounted) {+ context.showErrorSnackBar(message: 'Unexpected error occured');+ }+ }setState(() => _isLoading = false);-- final error = response.error;- if (error != null) {- context.showErrorSnackBar(message: error.message);- return;- }- final imageUrlResponse =- supabase.storage.from('avatars').getPublicUrl(filePath);- widget.onUpload(imageUrlResponse.data!);}}```@@ -747,46 +634,45 @@ And then we can add the widget to the Account page as well as some logic to upda```dart title="lib/pages/account_page.dart"import 'package:flutter/material.dart';-import 'package:supabase/supabase.dart';-import 'package:supabase_quickstart/components/auth_required_state.dart';+import 'package:supabase_flutter/supabase_flutter.dart';import 'package:supabase_quickstart/components/avatar.dart';-import 'package:supabase_quickstart/utils/constants.dart';+import 'package:supabase_quickstart/constants.dart';class AccountPage extends StatefulWidget {- const AccountPage({Key? key}) : super(key: key);+ const AccountPage({super.key});@override_AccountPageState createState() => _AccountPageState();}-class _AccountPageState extends AuthRequiredState<AccountPage> {+class _AccountPageState extends State<AccountPage> {final _usernameController = TextEditingController();final _websiteController = TextEditingController();- String? _userId;String? _avatarUrl;var _loading = false;/// Called once a user id is received within `onAuthenticated()`- Future<void> _getProfile(String userId) async {+ Future<void> _getProfile() async {setState(() {_loading = true;});- final response = await supabase- .from('profiles')- .select()- .eq('id', userId)- .single()- .execute();- final error = response.error;- if (error != null && response.status != 406) {- context.showErrorSnackBar(message: error.message);- }- final data = response.data;- if (data != null) {++ try {+ final userId = supabase.auth.currentUser!.id;+ final data = await supabase+ .from('profiles')+ .select()+ .eq('id', userId)+ .single() as Map;_usernameController.text = (data['username'] ?? '') as String;_websiteController.text = (data['website'] ?? '') as String;_avatarUrl = (data['avatar_url'] ?? '') as String;+ } on PostgrestException catch (error) {+ context.showErrorSnackBar(message: error.message);+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected exception occured');}+setState(() {_loading = false;});@@ -806,12 +692,15 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {'website': website,'updated_at': DateTime.now().toIso8601String(),};- final response = await supabase.from('profiles').upsert(updates).execute();- final error = response.error;- if (error != null) {+ try {+ await supabase.from('profiles').upsert(updates);+ if (mounted) {+ context.showSnackBar(message: 'Successfully updated profile!');+ }+ } on PostgrestException catch (error) {context.showErrorSnackBar(message: error.message);- } else {- context.showSnackBar(message: 'Successfully updated profile!');+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpeted error occured');}setState(() {_loading = false;@@ -819,42 +708,47 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {}Future<void> _signOut() async {- final response = await supabase.auth.signOut();- final error = response.error;- if (error != null) {+ try {+ await supabase.auth.signOut();+ } on AuthException catch (error) {context.showErrorSnackBar(message: error.message);+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected error occured');+ }+ if (mounted) {+ Navigator.of(context).pushReplacementNamed('/');}- Navigator.of(context).pushReplacementNamed('/login');}/// Called when image has been uploaded to Supabase storage from within Avatar widgetFuture<void> _onUpload(String imageUrl) async {- final response = await supabase.from('profiles').upsert({- 'id': _userId,- 'avatar_url': imageUrl,- }).execute();- final error = response.error;- if (error != null) {+ try {+ final userId = supabase.auth.currentUser!.id;+ await supabase.from('profiles').upsert({+ 'id': userId,+ 'avatar_url': imageUrl,+ });+ if (mounted) {+ context.showSnackBar(message: 'Updated your profile image!');+ }+ } on PostgrestException catch (error) {context.showErrorSnackBar(message: error.message);+ } catch (error) {+ context.showErrorSnackBar(message: 'Unexpected error has occured');+ }+ if (!mounted) {+ return;}+setState(() {_avatarUrl = imageUrl;});- context.showSnackBar(message: 'Updated your profile image!');}@override- void onAuthenticated(Session session) {- final user = session.user;- if (user != null) {- _userId = user.id;- _getProfile(user.id);- }- }-- @override- void onUnauthenticated() {- Navigator.of(context).pushReplacementNamed('/login');+ void initState() {+ super.initState();+ _getProfile();}@override@@ -887,10 +781,11 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {),const SizedBox(height: 18),ElevatedButton(- onPressed: _updateProfile,- child: Text(_loading ? 'Saving...' : 'Update')),+ onPressed: _updateProfile,+ child: Text(_loading ? 'Saving...' : 'Update'),+ ),const SizedBox(height: 18),- ElevatedButton(onPressed: _signOut, child: const Text('Sign Out')),+ TextButton(onPressed: _signOut, child: const Text('Sign Out')),],),);@@ -900,9 +795,6 @@ class _AccountPageState extends AuthRequiredState<AccountPage> {Congratulations, that is it! You have now built a fully functional user management app using Flutter and Supabase!-## Next steps--At this stage you have a fully functional application!+## See also-- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).-- Sign in: [app.supabase.com](https://app.supabase.com)+- [Flutter Tutorial: building a Flutter chat app](https://supabase.com/blog/flutter-tutorial-building-a-chat-app)diff --git a/apps/temp-docs/docs/guides/with-ionic-angular.mdx b/apps/temp-docs/docs/guides/with-ionic-angular.mdxnew file mode 100644index 00000000000..a0dea8bc0b7--- /dev/null+++ b/apps/temp-docs/docs/guides/with-ionic-angular.mdx@@ -0,0 +1,576 @@+---+id: with-ionic-angular+title: 'Quickstart: Ionic Angular'+description: Learn how to use Supabase in your Ionic Angular App.+sidebar_label: Ionic Angular+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/mhartington/supabase-ionic-angular).++<ProjectSetup />++## Building the App++Let's start building the Angular app from scratch.++### Initialize an Ionic Angular app++We can use the [Ionic CLI](https://ionicframework.com/docs/cli) to initialize+an app called `supabase-ionic-angular`:++```bash+npm install -g @ionic/cli+ionic start supabase-ionic-angular blank --type angular+cd supabase-ionic-angular+```++Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+```++And finally we want to save the environment variables in the `environment.ts` file.+All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).+These variables will be exposed on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```ts title="environment.ts"+export const environment = {+ production: false,+ supabaseUrl: 'YOUR_SUPABASE_URL',+ supabaseKey: 'YOUR_SUPABASE_KEY',+}+```++Now that we have the API credentials in place, let's create a **SupabaseService** with `ionic g s supabase` to initialize the Supabase client and implement functions to communicate with the Supabase API.++```ts title="src/app/supabase.service.ts"+import { Injectable } from '@angular/core'+import { LoadingController, ToastController } from '@ionic/angular'+import {+ AuthChangeEvent,+ createClient,+ Session,+ SupabaseClient,+} from '@supabase/supabase-js'+import { environment } from '../environments/environment'++export interface Profile {+ username: string+ website: string+ avatar_url: string+}++@Injectable({+ providedIn: 'root',+})+export class SupabaseService {+ private supabase: SupabaseClient++ constructor(+ private loadingCtrl: LoadingController,+ private toastCtrl: ToastController+ ) {+ this.supabase = createClient(+ environment.supabaseUrl,+ environment.supabaseKey+ )+ }++ get user() {+ return this.supabase.auth.user()+ }++ get session() {+ return this.supabase.auth.session()+ }++ get profile() {+ return this.supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', this.user?.id)+ .single()+ }++ authChanges(+ callback: (event: AuthChangeEvent, session: Session | null) => void+ ) {+ return this.supabase.auth.onAuthStateChange(callback)+ }++ signIn(email: string) {+ return this.supabase.auth.signIn({ email })+ }++ signOut() {+ return this.supabase.auth.signOut()+ }++ updateProfile(profile: Profile) {+ const update = {+ ...profile,+ id: this.user?.id,+ updated_at: new Date(),+ }++ return this.supabase.from('profiles').upsert(update, {+ returning: 'minimal', // Don't return the value after inserting+ })+ }++ downLoadImage(path: string) {+ return this.supabase.storage.from('avatars').download(path)+ }++ uploadAvatar(filePath: string, file: File) {+ return this.supabase.storage.from('avatars').upload(filePath, file)+ }++ async createNotice(message: string) {+ const toast = await this.toastCtrl.create({ message, duration: 5000 })+ await toast.present()+ }++ createLoader() {+ return this.loadingCtrl.create()+ }+}+```++### Set up a Login route++Let's set up an route to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.+Create an **LoginPage** with `ionic g page login` Ionic CLI command.++> This guide will show the template inline, but the example app will have templateUrls++```ts title="src/app/login/login.page.ts"+import { Component, OnInit } from '@angular/core'+import { SupabaseService } from '../supabase.service'++@Component({+ selector: 'app-login',+ template: `+ <ion-header>+ <ion-toolbar>+ <ion-title>Login</ion-title>+ </ion-toolbar>+ </ion-header>++ <ion-content>+ <div class="ion-padding">+ <h1>Supabase + Ionic Angular</h1>+ <p>Sign in via magic link with your email below</p>+ </div>+ <ion-list inset="true">+ <form (ngSubmit)="handleLogin($event)">+ <ion-item>+ <ion-label position="stacked">Email</ion-label>+ <ion-input+ [(ngModel)]="email"+ name="email"+ autocomplete+ type="email"+ ></ion-input>+ </ion-item>+ <div class="ion-text-center">+ <ion-button type="submit" fill="clear">Login</ion-button>+ </div>+ </form>+ </ion-list>+ </ion-content>+ `,+ styleUrls: ['./login.page.scss'],+})+export class LoginPage implements OnInit {+ email = ''+ constructor(private readonly supabase: SupabaseService) {}++ ngOnInit() {}+ async handleLogin(event: any) {+ event.preventDefault()+ const loader = await this.supabase.createLoader()+ await loader.present()+ try {+ await this.supabase.signIn(this.email)+ await loader.dismiss()+ await this.supabase.createNotice('Check your email for the login link!')+ } catch (error) {+ await loader.dismiss()+ await this.supabase.createNotice(error.error_description || error.message)+ }+ }+}+```++### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.+Create an **AccountComponent** with `ionic g page account` Ionic CLI command.++```ts title="src/app/account.component.ts"+import { Component, OnInit } from '@angular/core'+import { Router } from '@angular/router'+import { Profile, SupabaseService } from '../supabase.service'++@Component({+ selector: 'app-account',+ template: `+ <ion-header>+ <ion-toolbar>+ <ion-title>Account</ion-title>+ </ion-toolbar>+ </ion-header>++ <ion-content>+ <form>+ <ion-item>+ <ion-label position="stacked">Email</ion-label>+ <ion-input type="email" [value]="session?.user?.email"></ion-input>+ </ion-item>++ <ion-item>+ <ion-label position="stacked">Name</ion-label>+ <ion-input+ type="text"+ name="username"+ [(ngModel)]="profile.username"+ ></ion-input>+ </ion-item>++ <ion-item>+ <ion-label position="stacked">Website</ion-label>+ <ion-input+ type="url"+ name="website"+ [(ngModel)]="profile.website"+ ></ion-input>+ </ion-item>+ <div class="ion-text-center">+ <ion-button fill="clear" (click)="updateProfile()"+ >Update Profile</ion-button+ >+ </div>+ </form>++ <div class="ion-text-center">+ <ion-button fill="clear" (click)="signOut()">Log Out</ion-button>+ </div>+ </ion-content>+ `,+ styleUrls: ['./account.page.scss'],+})+export class AccountPage implements OnInit {+ profile: Profile = {+ username: '',+ avatar_url: '',+ website: '',+ }++ session = this.supabase.session++ constructor(+ private readonly supabase: SupabaseService,+ private router: Router+ ) {}+ ngOnInit() {+ this.getProfile()+ }++ async getProfile() {+ try {+ let { data: profile, error, status } = await this.supabase.profile+ if (error && status !== 406) {+ throw error+ }+ if (profile) {+ this.profile = profile+ }+ } catch (error) {+ alert(error.message)+ }+ }++ async updateProfile(avatar_url: string = '') {+ const loader = await this.supabase.createLoader()+ await loader.present()+ try {+ await this.supabase.updateProfile({ ...this.profile, avatar_url })+ await loader.dismiss()+ await this.supabase.createNotice('Profile updated!')+ } catch (error) {+ await this.supabase.createNotice(error.message)+ }+ }++ async signOut() {+ console.log('testing?')+ await this.supabase.signOut()+ this.router.navigate(['/'], { replaceUrl: true })+ }+}+```++### Launch!++Now that we have all the components in place, let's update **AppComponent**:++```ts title="src/app/app.component.ts"+import { Component } from '@angular/core'+import { Router } from '@angular/router'+import { SupabaseService } from './supabase.service'++@Component({+ selector: 'app-root',+ template: `+ <ion-app>+ <ion-router-outlet></ion-router-outlet>+ </ion-app>+ `,+ styleUrls: ['app.component.scss'],+})+export class AppComponent {+ constructor(private supabase: SupabaseService, private router: Router) {+ this.supabase.authChanges((_, session) => {+ console.log(session)+ if (session?.user) {+ this.router.navigate(['/account'])+ }+ })+ }+}+```++Then update the **AppRoutingModule**++```ts title="src/app/app.ts"+import { NgModule } from '@angular/core'+import { PreloadAllModules, RouterModule, Routes } from '@angular/router'++const routes: Routes = [+ {+ path: '/',+ loadChildren: () =>+ import('./login/login.module').then((m) => m.LoginPageModule),+ },+ {+ path: 'account',+ loadChildren: () =>+ import('./account/account.module').then((m) => m.AccountPageModule),+ },+]++@NgModule({+ imports: [+ RouterModule.forRoot(routes, {+ preloadingStrategy: PreloadAllModules,+ }),+ ],+ exports: [RouterModule],+})+export class AppRoutingModule {}+```++Once that's done, run this in a terminal window:++```bash+ionic serve+```++And the browser will auomatically open to show the app.++++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.++### Create an upload widget++Let's create an avatar for the user so that they can upload a profile photo.++First install two packages in order to interact with the user's camera.++```bash+npm install @ionic/pwa-elements @capacitor/camera+```++[CapacitorJS](https://capacitorjs.com) is a cross platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native deavice API.++Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.++With those packages installed we can update our `main.ts` to include an additional bootstapping call for the Ionic PWA Elements.++```ts title="src/main.ts"+import { enableProdMode } from '@angular/core'+import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'++import { AppModule } from './app/app.module'+import { environment } from './environments/environment'++import { defineCustomElements } from '@ionic/pwa-elements/loader'+defineCustomElements(window)++if (environment.production) {+ enableProdMode()+}+platformBrowserDynamic()+ .bootstrapModule(AppModule)+ .catch((err) => console.log(err))+```++Then create an **AvatarComponent** with this Ionic CLI command:++```bash+ ionic g component avatar --module=/src/app/account/account.module.ts --create-module+```++```ts title="src/app/avatar.component.ts"+import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'+import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'+import { SupabaseService } from '../supabase.service'+import { Camera, CameraResultType } from '@capacitor/camera'+@Component({+ selector: 'app-avatar',+ template: `+ <div class="avatar_wrapper" (click)="uploadAvatar()">+ <img *ngIf="_avatarUrl; else noAvatar" [src]="_avatarUrl" />+ <ng-template #noAvatar>+ <ion-icon name="person" class="no-avatar"></ion-icon>+ </ng-template>+ </div>+ `,+ style: [+ `+ :host {+ display: block;+ margin: auto;+ min-height: 150px;+ }+ :host .avatar_wrapper {+ margin: 16px auto 16px;+ border-radius: 50%;+ overflow: hidden;+ height: 150px;+ aspect-ratio: 1;+ background: var(--ion-color-step-50);+ border: thick solid var(--ion-color-step-200);+ }+ :host .avatar_wrapper:hover {+ cursor: pointer;+ }+ :host .avatar_wrapper ion-icon.no-avatar {+ width: 100%;+ height: 115%;+ }+ :host img {+ display: block;+ object-fit: cover;+ width: 100%;+ height: 100%;+ }+ `,+ ],+})+export class AvatarComponent implements OnInit {+ _avatarUrl: SafeResourceUrl | undefined+ uploading = false++ @Input()+ set avatarUrl(url: string | undefined) {+ if (url) {+ this.downloadImage(url)+ }+ }++ @Output() upload = new EventEmitter<string>()++ constructor(+ private readonly supabase: SupabaseService,+ private readonly dom: DomSanitizer+ ) {}++ ngOnInit() {}++ async downloadImage(path: string) {+ try {+ const { data } = await this.supabase.downLoadImage(path)+ this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(+ URL.createObjectURL(data)+ )+ } catch (error) {+ console.error('Error downloading image: ', error.message)+ }+ }++ async uploadAvatar() {+ const loader = await this.supabase.createLoader()+ try {+ const photo = await Camera.getPhoto({+ resultType: CameraResultType.DataUrl,+ })++ const file = await fetch(photo.dataUrl)+ .then((res) => res.blob())+ .then(+ (blob) =>+ new File([blob], 'my-file', { type: `image/${photo.format}` })+ )++ const fileName = `${Math.random()}-${new Date().getTime()}.${+ photo.format+ }`++ await loader.present()+ await this.supabase.uploadAvatar(fileName, file)++ this.upload.emit(fileName)+ } catch (error) {+ this.supabase.createNotice(error.message)+ } finally {+ loader.dismiss()+ }+ }+}+```++### Add the new widget++And then we can add the widget on top of the **AccountComponent** html template:++```ts title="src/app/account.component.ts"+template: `+<ion-header>+ <ion-toolbar>+ <ion-title>Account</ion-title>+ </ion-toolbar>+</ion-header>++<ion-content>+ <app-avatar+ [avatarUrl]="this.profile?.avatar_url"+ (upload)="updateProfile($event)"+ ></app-avatar>++<!-- input fields -->+`+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-ionic-react.mdx b/apps/temp-docs/docs/guides/with-ionic-react.mdxnew file mode 100644index 00000000000..7ca3cb9ced7--- /dev/null+++ b/apps/temp-docs/docs/guides/with-ionic-react.mdx@@ -0,0 +1,506 @@+---+id: with-ionic-react+title: 'Quickstart: Ionic React'+description: Learn how to use Supabase in your Ionic React App.+sidebar_label: Ionic React+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/mhartington/supabase-ionic-react).++<ProjectSetup />++## Building the App++Let's start building the React app from scratch.++### Initialize an Ionic React app++We can use the [Ionic CLI](https://ionicframework.com/docs/cli) to initialize+an app called `supabase-ionic-react`:++```bash+npm install -g @ionic/cli+ionic start supabase-ionic-react blank --type react+cd supabase-ionic-react+```++Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+```++And finally we want to save the environment variables in a `.env`.+All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).++```bash title=".env"+REACT_APP_SUPABASE_URL=YOUR_SUPABASE_URL+REACT_APP_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY+```++Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed+on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```js title="src/supabaseClient.js"+import { createClient } from '@supabase/supabase-js'++const supabaseUrl = process.env.REACT_APP_SUPABASE_URL+const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY++export const supabase = createClient(supabaseUrl, supabaseAnonKey)+```++### Set up a Login route++Let's set up a React component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.++```jsx title="/src/pages/Login.tsx"+import { useState } from 'react';+import {+ IonButton,+ IonContent,+ IonHeader,+ IonInput,+ IonItem,+ IonLabel,+ IonList,+ IonPage,+ IonTitle,+ IonToolbar,+ useIonToast,+ useIonLoading,+} from '@ionic/react';+import { supabase } from '../supabaseClient';++export function LoginPage() {+ const [email, setEmail] = useState('');++ const [showLoading, hideLoading] = useIonLoading();+ const [showToast ] = useIonToast();+ const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {+ console.log()+ e.preventDefault();+ await showLoading();+ try {+ await supabase.auth.signIn({ email });+ await showToast({ message: 'Check your email for the login link!' });+ } catch (e: any) {+ await showToast({ message: e.error_description || e.message , duration: 5000});+ } finally {+ await hideLoading();+ }+ };+ return (+ <IonPage>+ <IonHeader>+ <IonToolbar>+ <IonTitle>Login</IonTitle>+ </IonToolbar>+ </IonHeader>++ <IonContent>+ <div className="ion-padding">+ <h1>Supabase + Ionic React</h1>+ <p>Sign in via magic link with your email below</p>+ </div>+ <IonList inset={true}>+ <form onSubmit={handleLogin}>+ <IonItem>+ <IonLabel position="stacked">Email</IonLabel>+ <IonInput+ value={email}+ name="email"+ onIonChange={(e) => setEmail(e.detail.value ?? '')}+ type="email"+ ></IonInput>+ </IonItem>+ <div className="ion-text-center">+ <IonButton type="submit" fill="clear">+ Login+ </IonButton>+ </div>+ </form>+ </IonList>+ </IonContent>+ </IonPage>+ );+}+```++### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.++Let's create a new component for that called `Account.tsx`.++```jsx title="src/pages/Account.tsx"+import {+ IonButton,+ IonContent,+ IonHeader,+ IonInput,+ IonItem,+ IonLabel,+ IonPage,+ IonTitle,+ IonToolbar,+ useIonLoading,+ useIonToast,+ useIonRouter+} from '@ionic/react';+import { useEffect, useState } from 'react';+import { supabase } from '../supabaseClient';++export function AccountPage() {+ const [showLoading, hideLoading] = useIonLoading();+ const [showToast] = useIonToast();+ const [session] = useState(() => supabase.auth.session());+ const router = useIonRouter();+ const [profile, setProfile] = useState({+ username: '',+ website: '',+ avatar_url: '',+ });+ useEffect(() => {+ getProfile();+ }, [session]);+ const getProfile = async () => {+ console.log('get');+ await showLoading();+ try {+ const user = supabase.auth.user();+ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user!.id)+ .single();++ if (error && status !== 406) {+ throw error;+ }++ if (data) {+ setProfile({+ username: data.username,+ website: data.website,+ avatar_url: data.avatar_url,+ });+ }+ } catch (error: any) {+ showToast({ message: error.message, duration: 5000 });+ } finally {+ await hideLoading();+ }+ };+ const signOut = async () => {+ await supabase.auth.signOut();+ router.push('/', 'forward', 'replace');+ }+ const updateProfile = async (e?: any, avatar_url: string = '') => {+ e?.preventDefault();++ console.log('update ');+ await showLoading();++ try {+ const user = supabase.auth.user();++ const updates = {+ id: user!.id,+ ...profile,+ avatar_url: avatar_url,+ updated_at: new Date(),+ };++ let { error } = await supabase.from('profiles').upsert(updates, {+ returning: 'minimal', // Don't return the value after inserting+ });++ if (error) {+ throw error;+ }+ } catch (error: any) {+ showToast({ message: error.message, duration: 5000 });+ } finally {+ await hideLoading();+ }+ };+ return (+ <IonPage>+ <IonHeader>+ <IonToolbar>+ <IonTitle>Account</IonTitle>+ </IonToolbar>+ </IonHeader>++ <IonContent>+ <form onSubmit={updateProfile}>+ <IonItem>+ <IonLabel>+ <p>Email</p>+ <p>{session?.user?.email}</p>+ </IonLabel>+ </IonItem>++ <IonItem>+ <IonLabel position="stacked">Name</IonLabel>+ <IonInput+ type="text"+ name="username"+ value={profile.username}+ onIonChange={(e) =>+ setProfile({ ...profile, username: e.detail.value ?? '' })+ }+ ></IonInput>+ </IonItem>++ <IonItem>+ <IonLabel position="stacked">Website</IonLabel>+ <IonInput+ type="url"+ name="website"+ value={profile.website}+ onIonChange={(e) =>+ setProfile({ ...profile, website: e.detail.value ?? '' })+ }+ ></IonInput>+ </IonItem>+ <div className="ion-text-center">+ <IonButton fill="clear" type="submit">+ Update Profile+ </IonButton>+ </div>+ </form>++ <div className="ion-text-center">+ <IonButton fill="clear" onClick={signOut}>+ Log Out+ </IonButton>+ </div>+ </IonContent>+ </IonPage>+ );+}+```++### Launch!++Now that we have all the components in place, let's update `App.tsx`:++```jsx title="src/App.tsx"+import { Redirect, Route } from 'react-router-dom'+import { IonApp, IonRouterOutlet, setupIonicReact } from '@ionic/react'+import { IonReactRouter } from '@ionic/react-router'+import { supabase } from './supabaseClient'++import '@ionic/react/css/ionic.bundle.css'++/* Theme variables */+import './theme/variables.css'+import { LoginPage } from './pages/Login'+import { AccountPage } from './pages/Account'+import { useEffect, useState } from 'react'+import { Session } from '@supabase/supabase-js'++setupIonicReact()++const App: React.FC = () => {+ const [session, setSession] = (useState < Session) | (null > null)+ useEffect(() => {+ setSession(supabase.auth.session())+ supabase.auth.onAuthStateChange((_event, session) => {+ setSession(session)+ })+ }, [session])+ return (+ <IonApp>+ <IonReactRouter>+ <IonRouterOutlet>+ <Route+ exact+ path="/"+ render={() => {+ return session ? <Redirect to="/account" /> : <LoginPage />+ }}+ />+ <Route exact path="/account">+ <AccountPage />+ </Route>+ </IonRouterOutlet>+ </IonReactRouter>+ </IonApp>+ )+}++export default App+```++Once that's done, run this in a terminal window:++```bash+ionic serve+```++And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.++++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.++### Create an upload widget++First install two packages in order to interact with the user's camera.++```bash+npm install @ionic/pwa-elements @capacitor/camera+```++[CapacitorJS](https://capacitorjs.com) is a cross platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native deavice API.++Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.++With those packages installed we can update our `index.tsx` to include an additional bootstapping call for the Ionic PWA Elements.++```ts title="src/index.tsx"+import React from 'react'+import ReactDOM from 'react-dom'+import App from './App'+import * as serviceWorkerRegistration from './serviceWorkerRegistration'+import reportWebVitals from './reportWebVitals'++import { defineCustomElements } from '@ionic/pwa-elements/loader'+defineCustomElements(window)++ReactDOM.render(+ <React.StrictMode>+ <App />+ </React.StrictMode>,+ document.getElementById('root')+)++serviceWorkerRegistration.unregister()+reportWebVitals()+```++Then create an **AvatarComponent**.++```jsx title="src/components/Avatar.tsx"+import { IonIcon } from '@ionic/react';+import { person } from 'ionicons/icons';+import { Camera, CameraResultType } from '@capacitor/camera';+import { useEffect, useState } from 'react';+import { supabase } from '../supabaseClient';+import './Avatar.css'+export function Avatar({+ url,+ onUpload,+}: {+ url: string;+ onUpload: (e: any, file: string) => Promise<void>;+}) {+ const [avatarUrl, setAvatarUrl] = useState<string | undefined>();++ useEffect(() => {+ if (url) {+ downloadImage(url);+ }+ }, [url]);+ const uploadAvatar = async () => {+ try {+ const photo = await Camera.getPhoto({+ resultType: CameraResultType.DataUrl,+ });++ const file = await fetch(photo.dataUrl!)+ .then((res) => res.blob())+ .then(+ (blob) =>+ new File([blob], 'my-file', { type: `image/${photo.format}` })+ );++ const fileName = `${Math.random()}-${new Date().getTime()}.${+ photo.format+ }`;+ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(fileName, file);+ if (uploadError) {+ throw uploadError;+ }+ onUpload(null, fileName);+ } catch (error) {+ console.log(error);+ }+ };++ const downloadImage = async (path: string) => {+ try {+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path);+ if (error) {+ throw error;+ }+ const url = URL.createObjectURL(data!);+ setAvatarUrl(url);+ } catch (error: any) {+ console.log('Error downloading image: ', error.message);+ }+ };++ return (+ <div className="avatar">+ <div className="avatar_wrapper" onClick={uploadAvatar}>+ {avatarUrl ? (+ <img src={avatarUrl} />+ ) : (+ <IonIcon icon={person} className="no-avatar" />+ )}+ </div>++ </div>+ );+}+```++### Add the new widget++And then we can add the widget to the Account page:++```jsx title="src/pages/Account.tsx"+// Import the new component++import { Avatar } from '../components/Avatar';++// ...+return (+ <IonPage>+ <IonHeader>+ <IonToolbar>+ <IonTitle>Account</IonTitle>+ </IonToolbar>+ </IonHeader>++ <IonContent>+ <Avatar url={profile.avatar_url} onUpload={updateProfile}></Avatar>+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-ionic-vue.mdx b/apps/temp-docs/docs/guides/with-ionic-vue.mdxnew file mode 100644index 00000000000..4292b8b9545--- /dev/null+++ b/apps/temp-docs/docs/guides/with-ionic-vue.mdx@@ -0,0 +1,586 @@+---+id: with-ionic-vue+title: 'Quickstart: Ionic Vue'+description: Learn how to use Supabase in your Ionic Vue App.+sidebar_label: Ionic Vue+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/mhartington/supabase-ionic-vue).++<ProjectSetup />++## Building the App++Let's start building the Vue app from scratch.++### Initialize an Ionic Vue app++We can use the [Ionic CLI](https://ionicframework.com/docs/cli) to initialize+an app called `supabase-ionic-vue`:++```bash+npm install -g @ionic/cli+ionic start supabase-ionic-vue blank --type vue+cd supabase-ionic-vue+```++Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+```++And finally we want to save the environment variables in a `.env`.+All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).++```bash title=".env"+VUE_APP_SUPABASE_URL=YOUR_SUPABASE_URL+VUE_APP_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY+```++Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed+on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```js title="src/supabase.ts"+import { createClient } from '@supabase/supabase-js';++const supabaseUrl = process.env.VUE_APP_SUPABASE_URL as string;+const supabaseAnonKey = process.env.VUE_APP_SUPABASE_ANON_KEY as string;++export const supabase = createClient(supabaseUrl, supabaseAnonKey);+```++### Set up a Login route++Let's set up a Vue component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.++```html title="/src/views/Login.vue"+<template>+ <ion-page>+ <ion-header>+ <ion-toolbar>+ <ion-title>Login</ion-title>+ </ion-toolbar>+ </ion-header>++ <ion-content>+ <div class="ion-padding">+ <h1>Supabase + Ionic Vue</h1>+ <p>Sign in via magic link with your email below</p>+ </div>+ <ion-list inset="true">+ <form @submit.prevent="handleLogin">+ <ion-item>+ <ion-label position="stacked">Email</ion-label>+ <ion-input+ v-model="email"+ name="email"+ autocomplete+ type="email"+ ></ion-input>+ </ion-item>+ <div class="ion-text-center">+ <ion-button type="submit" fill="clear">Login</ion-button>+ </div>+ </form>+ </ion-list>+ <p>{{email}}</p>+ </ion-content>+ </ion-page>+</template>++<script lang="ts">+ import { supabase } from '../supabase'+ import {+ IonContent,+ IonHeader,+ IonPage,+ IonTitle,+ IonToolbar,+ IonList,+ IonItem,+ IonLabel,+ IonInput,+ IonButton,+ toastController,+ loadingController,+ } from '@ionic/vue'+ import { defineComponent, ref } from 'vue'++ export default defineComponent({+ name: 'LoginPage',+ components: {+ IonContent,+ IonHeader,+ IonPage,+ IonTitle,+ IonToolbar,+ IonList,+ IonItem,+ IonLabel,+ IonInput,+ IonButton,+ },+ setup() {+ const email = ref('')+ const handleLogin = async () => {+ const loader = await loadingController.create({})+ const toast = await toastController.create({ duration: 5000 })++ try {+ await loader.present()+ const { error } = await supabase.auth.signIn({ email: email.value })++ if (error) throw error++ toast.message = 'Check your email for the login link!'+ await toast.present()+ } catch (error: any) {+ toast.message = error.error_description || error.message+ await toast.present()+ } finally {+ await loader.dismiss()+ }+ }+ return { handleLogin, email }+ },+ })+</script>+```++### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.++Let's create a new component for that called `Account.vue`.++```html title="src/views/Account.vue"+<template>+ <ion-page>+ <ion-header>+ <ion-toolbar>+ <ion-title>Account</ion-title>+ </ion-toolbar>+ </ion-header>++ <ion-content>+ <form @submit.prevent="updateProfile">+ <ion-item>+ <ion-label>+ <p>Email</p>+ <p>{{ session?.user?.email }}</p>+ </ion-label>+ </ion-item>++ <ion-item>+ <ion-label position="stacked">Name</ion-label>+ <ion-input+ type="text"+ name="username"+ v-model="profile.username"+ ></ion-input>+ </ion-item>++ <ion-item>+ <ion-label position="stacked">Website</ion-label>+ <ion-input+ type="url"+ name="website"+ v-model="profile.website"+ ></ion-input>+ </ion-item>+ <div class="ion-text-center">+ <ion-button fill="clear" type="submit">Update Profile</ion-button>+ </div>+ </form>++ <div class="ion-text-center">+ <ion-button fill="clear" @click="signOut">Log Out</ion-button>+ </div>+ </ion-content>+ </ion-page>+</template>++<script lang="ts">+ import { store } from '@/store'+ import { supabase } from '@/supabase'+ import {+ IonContent,+ IonHeader,+ IonPage,+ IonTitle,+ IonToolbar,+ toastController,+ loadingController,+ IonInput,+ IonItem,+ IonButton,+ IonLabel,+ } from '@ionic/vue'+ import { User } from '@supabase/supabase-js'+ import { defineComponent, onMounted, ref } from 'vue'+ export default defineComponent({+ name: 'AccountPage',+ components: {+ IonContent,+ IonHeader,+ IonPage,+ IonTitle,+ IonToolbar,+ IonInput,+ IonItem,+ IonButton,+ IonLabel,+ },+ setup() {+ const session = ref(supabase.auth.session())+ const profile = ref({+ username: '',+ website: '',+ avatar_url: '',+ })+ const user = store.user as User+ async function getProfile() {+ const loader = await loadingController.create({})+ const toast = await toastController.create({ duration: 5000 })+ await loader.present()+ try {+ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user.id)+ .single()++ if (error && status !== 406) throw error++ if (data) {+ console.log(data)+ profile.value = {+ username: data.username,+ website: data.website,+ avatar_url: data.avatar_url,+ }+ }+ } catch (error: any) {+ toast.message = error.message+ await toast.present()+ } finally {+ await loader.dismiss()+ }+ }++ const updateProfile = async () => {+ const loader = await loadingController.create({})+ const toast = await toastController.create({ duration: 5000 })+ try {+ await loader.present()+ const updates = {+ id: user.id,+ ...profile.value,+ updated_at: new Date(),+ }+ //+ let { error } = await supabase.from('profiles').upsert(updates, {+ returning: 'minimal', // Don't return the value after inserting+ })+ //+ if (error) throw error+ } catch (error: any) {+ toast.message = error.message+ await toast.present()+ } finally {+ await loader.dismiss()+ }+ }++ async function signOut() {+ const loader = await loadingController.create({})+ const toast = await toastController.create({ duration: 5000 })+ await loader.present()+ try {+ let { error } = await supabase.auth.signOut()+ if (error) throw error+ } catch (error: any) {+ toast.message = error.message+ await toast.present()+ } finally {+ await loader.dismiss()+ }+ }++ onMounted(() => {+ getProfile()+ })+ return { signOut, profile, session, updateProfile }+ },+ })+</script>+```++### Launch!++Now that we have all the components in place, let's update `App.vue` and our routes:++```ts title="src/router.index.ts"+import { createRouter, createWebHistory } from '@ionic/vue-router'+import { RouteRecordRaw } from 'vue-router'+import LoginPage from '../views/Login.vue'+import AccountPage from '../views/Account.vue'+const routes: Array<RouteRecordRaw> = [+ {+ path: '/',+ name: 'Login',+ component: LoginPage,+ },+ {+ path: '/account',+ name: 'Account',+ component: AccountPage,+ },+]++const router = createRouter({+ history: createWebHistory(process.env.BASE_URL),+ routes,+})++export default router+```++```html title="src/App.vue"+<template>+ <ion-app>+ <ion-router-outlet />+ </ion-app>+</template>++<script lang="ts">+ import { IonApp, IonRouterOutlet, useIonRouter } from '@ionic/vue'+ import { defineComponent } from 'vue'++ import { store } from './store'+ import { supabase } from './supabase'++ export default defineComponent({+ name: 'App',+ components: {+ IonApp,+ IonRouterOutlet,+ },+ setup() {+ const router = useIonRouter()+ store.user = supabase.auth.user() ?? {}+ supabase.auth.onAuthStateChange((_, session) => {+ store.user = session?.user ?? {}+ if (session?.user) {+ router.replace('/account')+ }+ })+ },+ })+</script>+```++Once that's done, run this in a terminal window:++```bash+ionic serve+```++And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.++++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.++### Create an upload widget++First install two packages in order to interact with the user's camera.++```bash+npm install @ionic/pwa-elements @capacitor/camera+```++[CapacitorJS](https://capacitorjs.com) is a cross platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native deavice API.++Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.++With those packages installed we can update our `main.ts` to include an additional bootstapping call for the Ionic PWA Elements.++```ts title="src/main.tsx"+import { createApp } from 'vue'+import App from './App.vue'+import router from './router'++import { IonicVue } from '@ionic/vue'+/* Core CSS required for Ionic components to work properly */+import '@ionic/vue/css/ionic.bundle.css'++/* Theme variables */+import './theme/variables.css'++import { defineCustomElements } from '@ionic/pwa-elements/loader'+defineCustomElements(window)+const app = createApp(App).use(IonicVue).use(router)++router.isReady().then(() => {+ app.mount('#app')+})+```++Then create an **AvatarComponent**.++```html title="src/components/Avatar.vue"+<template>+ <div class="avatar">+ <div class="avatar_wrapper" @click="uploadAvatar">+ <img v-if="avatarUrl" :src="avatarUrl" />+ <ion-icon v-else name="person" class="no-avatar"></ion-icon>+ </div>+ </div>+</template>++<script lang="ts">+ import { ref, toRefs, watch, defineComponent } from 'vue'+ import { supabase } from '../supabase'+ import { Camera, CameraResultType } from '@capacitor/camera'+ import { IonIcon } from '@ionic/vue'+ import { person } from 'ionicons/icons'+ export default defineComponent({+ name: 'AppAvatar',+ props: { path: String },+ emits: ['upload', 'update:path'],+ components: { IonIcon },+ setup(prop, { emit }) {+ const { path } = toRefs(prop)+ const avatarUrl = ref('')++ const downloadImage = async () => {+ try {+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path.value)+ if (error) throw error+ avatarUrl.value = URL.createObjectURL(data!)+ } catch (error: any) {+ console.error('Error downloading image: ', error.message)+ }+ }++ const uploadAvatar = async () => {+ try {+ const photo = await Camera.getPhoto({+ resultType: CameraResultType.DataUrl,+ })+ if (photo.dataUrl) {+ const file = await fetch(photo.dataUrl)+ .then((res) => res.blob())+ .then(+ (blob) =>+ new File([blob], 'my-file', { type: `image/${photo.format}` })+ )++ const fileName = `${Math.random()}-${new Date().getTime()}.${+ photo.format+ }`+ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(fileName, file)+ if (uploadError) {+ throw uploadError+ }+ emit('update:path', fileName)+ emit('upload')+ }+ } catch (error) {+ console.log(error)+ }+ }++ watch(path, () => {+ if (path.value) downloadImage()+ })++ return { avatarUrl, uploadAvatar, person }+ },+ })+</script>+<style>+ .avatar {+ display: block;+ margin: auto;+ min-height: 150px;+ }+ .avatar .avatar_wrapper {+ margin: 16px auto 16px;+ border-radius: 50%;+ overflow: hidden;+ height: 150px;+ aspect-ratio: 1;+ background: var(--ion-color-step-50);+ border: thick solid var(--ion-color-step-200);+ }+ .avatar .avatar_wrapper:hover {+ cursor: pointer;+ }+ .avatar .avatar_wrapper ion-icon.no-avatar {+ width: 100%;+ height: 115%;+ }+ .avatar img {+ display: block;+ object-fit: cover;+ width: 100%;+ height: 100%;+ }+</style>+```++### Add the new widget++And then we can add the widget to the Account page:++```html title="src/views/Account.vue"+<template>+ <ion-page>+ <ion-header>+ <ion-toolbar>+ <ion-title>Account</ion-title>+ </ion-toolbar>+ </ion-header>++ <ion-content>+ <avatar v-model:path="profile.avatar_url" @upload="updateProfile"></avatar>+...+</template>+<script lang="ts">+import Avatar from '../components/Avatar.vue';+export default defineComponent({+ name: 'AccountPage',+ components: {+ Avatar,+ ....+ }++</script>+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-nextjs.mdx b/apps/temp-docs/docs/guides/with-nextjs.mdxindex d1a2abe4676..82492aca8a0 100644--- a/apps/temp-docs/docs/guides/with-nextjs.mdx+++ b/apps/temp-docs/docs/guides/with-nextjs.mdx@@ -2,272 +2,356 @@id: with-nextjstitle: 'Quickstart: Next.js'description: Learn how to use Supabase in your Next App.+sidebar_label: 'Next.js'----# Quickstart: Next.js-import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'--## Intro+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-This example provides the steps to build a simple user management app (from scratch!) using Supabase and Next.js. It includes:+<QuickstartIntro />-- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email).-- Supabase [Storage](/docs/guides/storage): users can upload a photo.-- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables.+-By the end of this guide you'll have an app which allows users to login and update some basic profile details:+### Video Guide-+<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/0Fs96oZ4se0"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>-<!-- ## Video demo+### GitHub-Coming soon.+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management).-Use the annotated timeline to step through this tutorial.+<ProjectSetup />-## Instant deploy--Want to deploy a completed version of this example without following the guide?+## Building the App-[](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Freact-user-management&project-name=supabase-user-management&repository-name=supabase-user-management&demo-title=Supabase%20User%20Management&demo-description=An%20example%20web%20app%20using%20Supabase%20and%20Next.js&demo-url=https%3A%2F%2Fsupabase-react-user-management.vercel.app&demo-image=https%3A%2F%2Fi.imgur.com%2FZ3HkQqe.png&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&external-id=nextjs-user-management)+Let's start building the Next.js app from scratch.-Clicking this button the application will:+### Initialize a Next.js app-- Launch and prepare the Postgres database in Supabase.-- Launch the app in Vercel.-- Fork the example into your own GitHub account.-- Prepare the deployed application with all the necessary environment variables.+We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize+an app called `supabase-nextjs`:-If you want to do it yourself, let's get started: -->+<Tabs+ groupId="language"+ defaultValue="js"+ values={[+ {label: 'JavaScript', value: 'js'},+ {label: 'TypeScript', value: 'ts'},+ ]}>+<TabItem value="js">-## Project set up+```bash+npx create-next-app@latest --use-npm supabase-nextjs+cd supabase-nextjs+```-Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.+</TabItem>+<TabItem value="ts">-### Create a project+```bash+npx create-next-app@latest --ts --use-npm supabase-nextjs+cd supabase-nextjs+```-1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.+</TabItem>+</Tabs>-### Set up the database schema+Then install the Supabase client library: [supabase-js](https://github.com/supabase/supabase-js)-Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.+```bash+npm install @supabase/supabase-js+```-<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="Dashboard UI">+And finally we want to save the environment variables in a `.env.local`.+All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).-```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".+```bash title=".env.local"+NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL+NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY```-<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="SQL" label="Using SQL">+And one optional step is to update the CSS file `styles/globals.css` to make the app look nice.+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/nextjs-ts-user-management/styles/globals.css).-```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,+### Set up a Login component- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);+#### Supabase Auth Helpers-alter table profiles enable row level security;+Next.js is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and middleware edge-functions.-create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );+It can be challenging to authenticate your users in all these different environments, that's why we've created the [Supabase Auth Helpers](https://supabase.com/docs/guides/auth/auth-helpers/nextjs) to make user management and data fetching within Next.js as easy as possible.-create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );+Install the auth helpers for React and Next.js-create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );+```bash+npm install @supabase/auth-helpers-react @supabase/auth-helpers-nextjs+```--- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;+<Tabs+ groupId="language"+ defaultValue="js"+ values={[+ {label: 'JavaScript', value: 'js'},+ {label: 'TypeScript', value: 'ts'},+ ]}>+<TabItem value="js">--- Set up Storage!-insert into storage.buckets (id, name)-values ('avatars', 'avatars');+Wrap your `pages/_app.js` component with the `SessionContextProvider` component:-create policy "Avatar images are publicly accessible."- on storage.objects for select- using ( bucket_id = 'avatars' );+```jsx title="pages/_app.js"+import '../styles/globals.css'+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+import { SessionContextProvider } from '@supabase/auth-helpers-react'-create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );+function MyApp({ Component, pageProps }) {+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())+ return (+ <SessionContextProvider+ supabaseClient={supabaseClient}+ initialSession={pageProps.initialSession}+ >+ <Component {...pageProps} />+ </SessionContextProvider>+ )+}+export default MyApp```-</TabsPanel>-</Tabs>+</TabItem>+<TabItem value="ts">-### Get the API Keys+Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:-Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.+```jsx title="pages/_app.tsx"+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+// highlight-next-line+import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'-<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="Dashboard UI">+function MyApp({+ Component,+ pageProps,+}: AppProps<{+ // highlight-next-line+ initialSession: Session,+}>) {+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())-```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.+ return (+ <SessionContextProvider+ supabaseClient={supabaseClient}+ initialSession={pageProps.initialSession}+ >+ <Component {...pageProps} />+ </SessionContextProvider>+ )+}+export default MyApp```-<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>+See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.-</TabsPanel>+</TabItem></Tabs>-## Building the App--Let's start building the Next.js app from scratch.+#### Supabase Auth UI-### Initialize a Next.js app+We can use the [Supabase Auth UI](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui) a pre-built React component for authenticating users via OAuth, email, and magic links.-We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize-an app called `supabase-nextjs`:+Install the Supabase Auth UI for React```bash-npx create-next-app supabase-nextjs-cd supabase-nextjs+npm install @supabase/auth-ui-react```-Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)+Add the `Auth` component to your home page-```bash-npm install @supabase/supabase-js-```+```jsx title="pages/index.js"+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'+import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'-And finally we want to save the environment variables in a `.env.local`.-All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).+const Home = () => {+ const session = useSession()+ const supabase = useSupabaseClient()-```bash title=".env.local"-NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL-NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY+ return (+ <div className="container" style={{ padding: '50px 0 100px 0' }}>+ {!session ? (+ <Auth+ supabaseClient={supabase}+ appearance={{ theme: ThemeSupa }}+ theme="dark"+ />+ ) : (+ <p>Account page will go here.</p>+ )}+ </div>+ )+}++export default Home```-Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client.-These variables will be exposed on the browser, and that's completely fine since we have-[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.+### Account page-```js title="utils/supabaseClient.js"-import { createClient } from '@supabase/supabase-js'+After a user is signed in we can allow them to edit their profile details and manage their account.-const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL-const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY+<Tabs+ groupId="language"+ defaultValue="js"+ values={[+ {label: 'JavaScript', value: 'js'},+ {label: 'TypeScript', value: 'ts'},+ ]}>+<TabItem value="js">-export const supabase = createClient(supabaseUrl, supabaseAnonKey)-```+Let's create a new component for that called `Account.js` within a `components` folder.-And one optional step is to update the CSS file `styles/globals.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css).+```tsx title="components/Account.js"+import { useState, useEffect } from 'react'+import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'-### Set up a Login component+export default function Account({ session }) {+ const supabase = useSupabaseClient()+ const user = useUser()+ const [loading, setLoading] = useState(true)+ const [username, setUsername] = useState(null)+ const [website, setWebsite] = useState(null)+ const [avatar_url, setAvatarUrl] = useState(null)-Let's set up a React component to manage logins and sign ups.-We'll use Magic Links, so users can sign in with their email without using passwords.+ useEffect(() => {+ getProfile()+ }, [session])-```jsx title="components/Auth.js"-import { useState } from 'react'-import { supabase } from '../utils/supabaseClient'+ async function getProfile() {+ try {+ setLoading(true)-export default function Auth() {- const [loading, setLoading] = useState(false)- const [email, setEmail] = useState('')+ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user.id)+ .single()++ if (error && status !== 406) {+ throw error+ }++ if (data) {+ setUsername(data.username)+ setWebsite(data.website)+ setAvatarUrl(data.avatar_url)+ }+ } catch (error) {+ alert('Error loading user data!')+ console.log(error)+ } finally {+ setLoading(false)+ }+ }- const handleLogin = async (email) => {+ async function updateProfile({ username, website, avatar_url }) {try {setLoading(true)- const { error } = await supabase.auth.signIn({ email })++ const updates = {+ id: user.id,+ username,+ website,+ avatar_url,+ updated_at: new Date().toISOString(),+ }++ let { error } = await supabase.from('profiles').upsert(updates)if (error) throw error- alert('Check your email for the login link!')+ alert('Profile updated!')} catch (error) {- alert(error.error_description || error.message)+ alert('Error updating the data!')+ console.log(error)} finally {setLoading(false)}}return (- <div className="row flex-center flex">- <div className="col-6 form-widget">- <h1 className="header">Supabase + Next.js</h1>- <p className="description">Sign in via magic link with your email below</p>- <div>- <input- className="inputField"- type="email"- placeholder="Your email"- value={email}- onChange={(e) => setEmail(e.target.value)}- />- </div>- <div>- <button- onClick={(e) => {- e.preventDefault()- handleLogin(email)- }}- className="button block"- disabled={loading}- >- <span>{loading ? 'Loading' : 'Send magic link'}</span>- </button>- </div>+ <div className="form-widget">+ <div>+ <label htmlFor="email">Email</label>+ <input id="email" type="text" value={session.user.email} disabled />+ </div>+ <div>+ <label htmlFor="username">Username</label>+ <input+ id="username"+ type="text"+ value={username || ''}+ onChange={(e) => setUsername(e.target.value)}+ />+ </div>+ <div>+ <label htmlFor="website">Website</label>+ <input+ id="website"+ type="website"+ value={website || ''}+ onChange={(e) => setWebsite(e.target.value)}+ />+ </div>++ <div>+ <button+ className="button primary block"+ onClick={() => updateProfile({ username, website, avatar_url })}+ disabled={loading}+ >+ {loading ? 'Loading ...' : 'Update'}+ </button>+ </div>++ <div>+ <button+ className="button block"+ onClick={() => supabase.auth.signOut()}+ >+ Sign Out+ </button></div></div>)}```-### Account page--After a user is signed in we can allow them to edit their profile details and manage their account.+</TabItem>+<TabItem value="ts">-Let's create a new component for that called `Account.js`.+Let's create a new component for that called `Account.tsx` within a `components` folder.-```jsx title="components/Account.js"+```tsx title="components/Account.tsx"import { useState, useEffect } from 'react'-import { supabase } from '../utils/supabaseClient'--export default function Account({ session }) {+import {+ useUser,+ useSupabaseClient,+ Session,+} from '@supabase/auth-helpers-react'+import { Database } from '../utils/database.types'+type Profiles = Database['public']['Tables']['profiles']['Row']++export default function Account({ session }: { session: Session }) {+ const supabase = useSupabaseClient<Database>()+ const user = useUser()const [loading, setLoading] = useState(true)- const [username, setUsername] = useState(null)- const [website, setWebsite] = useState(null)- const [avatar_url, setAvatarUrl] = useState(null)+ const [username, setUsername] = useState<Profiles['username']>(null)+ const [website, setWebsite] = useState<Profiles['website']>(null)+ const [avatar_url, setAvatarUrl] = useState<Profiles['avatar_url']>(null)useEffect(() => {getProfile()@@ -276,7 +360,7 @@ export default function Account({ session }) {async function getProfile() {try {setLoading(true)- const user = supabase.auth.user()+ if (!user) throw new Error('No user')let { data, error, status } = await supabase.from('profiles')@@ -294,34 +378,40 @@ export default function Account({ session }) {setAvatarUrl(data.avatar_url)}} catch (error) {- alert(error.message)+ alert('Error loading user data!')+ console.log(error)} finally {setLoading(false)}}- async function updateProfile({ username, website, avatar_url }) {+ async function updateProfile({+ username,+ website,+ avatar_url,+ }: {+ username: Profiles['username']+ website: Profiles['website']+ avatar_url: Profiles['avatar_url']+ }) {try {setLoading(true)- const user = supabase.auth.user()+ if (!user) throw new Error('No user')const updates = {id: user.id,username,website,avatar_url,- updated_at: new Date(),+ updated_at: new Date().toISOString(),}- let { error } = await supabase.from('profiles').upsert(updates, {- returning: 'minimal', // Don't return the value after inserting- })-- if (error) {- throw error- }+ let { error } = await supabase.from('profiles').upsert(updates)+ if (error) throw error+ alert('Profile updated!')} catch (error) {- alert(error.message)+ alert('Error updating the data!')+ console.log(error)} finally {setLoading(false)}@@ -334,7 +424,7 @@ export default function Account({ session }) {<input id="email" type="text" value={session.user.email} disabled /></div><div>- <label htmlFor="username">Name</label>+ <label htmlFor="username">Username</label><inputid="username"type="text"@@ -363,7 +453,10 @@ export default function Account({ session }) {</div><div>- <button className="button block" onClick={() => supabase.auth.signOut()}>+ <button+ className="button block"+ onClick={() => supabase.auth.signOut()}+ >Sign Out</button></div>@@ -372,33 +465,41 @@ export default function Account({ session }) {}```+</TabItem>+</Tabs>+### Launch!Now that we have all the components in place, let's update `pages/index.js`:```jsx title="pages/index.js"-import { useState, useEffect } from 'react'-import { supabase } from '../utils/supabaseClient'-import Auth from '../components/Auth'+import type { NextPage } from 'next'+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'+import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'+// highlight-next-lineimport Account from '../components/Account'-export default function Home() {- const [session, setSession] = useState(null)-- useEffect(() => {- setSession(supabase.auth.session())-- supabase.auth.onAuthStateChange((_event, session) => {- setSession(session)- })- }, [])+const Home: NextPage = () => {+ const session = useSession()+ const supabase = useSupabaseClient()return (<div className="container" style={{ padding: '50px 0 100px 0' }}>- {!session ? <Auth /> : <Account key={session.user.id} session={session} />}+ {!session ? (+ <Auth+ supabaseClient={supabase}+ appearance={{ theme: ThemeSupa }}+ theme="dark"+ />+ ) : (+ // highlight-next-line+ <Account session={session} />+ )}</div>)}++export default Home```Once that's done, run this in a terminal window:@@ -409,8 +510,6 @@ npm run devAnd then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.--## Bonus: Profile photosEvery Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like@@ -418,14 +517,23 @@ photos and videos.### Create an upload widget-Let's create an avatar for the user so that they can upload a profile photo.-We can start by creating a new component:+Let's create an avatar widget for the user so that they can upload a profile photo. We can start by creating a new component:++<Tabs+ groupId="language"+ defaultValue="js"+ values={[+ {label: 'JavaScript', value: 'js'},+ {label: 'TypeScript', value: 'ts'},+ ]}>+<TabItem value="js">```jsx title="components/Avatar.js"-import { useEffect, useState } from 'react'-import { supabase } from '../utils/supabaseClient'+import React, { useEffect, useState } from 'react'+import { useSupabaseClient } from '@supabase/auth-helpers-react'-export default function Avatar({ url, size, onUpload }) {+export default function Avatar({ uid, url, size, onUpload }) {+ const supabase = useSupabaseClient()const [avatarUrl, setAvatarUrl] = useState(null)const [uploading, setUploading] = useState(false)@@ -435,18 +543,20 @@ export default function Avatar({ url, size, onUpload }) {async function downloadImage(path) {try {- const { data, error } = await supabase.storage.from('avatars').download(path)+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)if (error) {throw error}const url = URL.createObjectURL(data)setAvatarUrl(url)} catch (error) {- console.log('Error downloading image: ', error.message)+ console.log('Error downloading image: ', error)}}- async function uploadAvatar(event) {+ const uploadAvatar = async (event) => {try {setUploading(true)@@ -456,10 +566,12 @@ export default function Avatar({ url, size, onUpload }) {const file = event.target.files[0]const fileExt = file.name.split('.').pop()- const fileName = `${Math.random()}.${fileExt}`+ const fileName = `${uid}.${fileExt}`const filePath = `${fileName}`- let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)+ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(filePath, file, { upsert: true })if (uploadError) {throw uploadError@@ -467,7 +579,8 @@ export default function Avatar({ url, size, onUpload }) {onUpload(filePath)} catch (error) {- alert(error.message)+ alert('Error uploading avatar!')+ console.log(error)} finally {setUploading(false)}@@ -483,7 +596,10 @@ export default function Avatar({ url, size, onUpload }) {style={{ height: size, width: size }}/>) : (- <div className="avatar no-image" style={{ height: size, width: size }} />+ <div+ className="avatar no-image"+ style={{ height: size, width: size }}+ />)}<div style={{ width: size }}><label className="button primary block" htmlFor="single">@@ -506,6 +622,120 @@ export default function Avatar({ url, size, onUpload }) {}```+</TabItem>+<TabItem value="ts">++```tsx title="components/Avatar.tsx"+import React, { useEffect, useState } from 'react'+import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { Database } from '../utils/database.types'+type Profiles = Database['public']['Tables']['profiles']['Row']++export default function Avatar({+ uid,+ url,+ size,+ onUpload,+}: {+ uid: string+ url: Profiles['avatar_url']+ size: number+ onUpload: (url: string) => void+}) {+ const supabase = useSupabaseClient<Database>()+ const [avatarUrl, setAvatarUrl] = useState<Profiles['avatar_url']>(null)+ const [uploading, setUploading] = useState(false)++ useEffect(() => {+ if (url) downloadImage(url)+ }, [url])++ async function downloadImage(path: string) {+ try {+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)+ if (error) {+ throw error+ }+ const url = URL.createObjectURL(data)+ setAvatarUrl(url)+ } catch (error) {+ console.log('Error downloading image: ', error)+ }+ }++ const uploadAvatar: React.ChangeEventHandler<HTMLInputElement> = async (+ event+ ) => {+ try {+ setUploading(true)++ if (!event.target.files || event.target.files.length === 0) {+ throw new Error('You must select an image to upload.')+ }++ const file = event.target.files[0]+ const fileExt = file.name.split('.').pop()+ const fileName = `${uid}.${fileExt}`+ const filePath = `${fileName}`++ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(filePath, file, { upsert: true })++ if (uploadError) {+ throw uploadError+ }++ onUpload(filePath)+ } catch (error) {+ alert('Error uploading avatar!')+ console.log(error)+ } finally {+ setUploading(false)+ }+ }++ return (+ <div>+ {avatarUrl ? (+ <img+ src={avatarUrl}+ alt="Avatar"+ className="avatar image"+ style={{ height: size, width: size }}+ />+ ) : (+ <div+ className="avatar no-image"+ style={{ height: size, width: size }}+ />+ )}+ <div style={{ width: size }}>+ <label className="button primary block" htmlFor="single">+ {uploading ? 'Uploading ...' : 'Upload'}+ </label>+ <input+ style={{+ visibility: 'hidden',+ position: 'absolute',+ }}+ type="file"+ id="single"+ accept="image/*"+ onChange={uploadAvatar}+ disabled={uploading}+ />+ </div>+ </div>+ )+}+```++</TabItem>+</Tabs>+### Add the new widgetAnd then we can add the widget to the Account page:@@ -520,6 +750,7 @@ return (<div className="form-widget">{/* Add to the body */}<Avatar+ uid={user.id}url={avatar_url}size={150}onUpload={(url) => {@@ -536,5 +767,10 @@ return (At this stage you have a fully functional application!+- See the complete [example on GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management) and deploy it to Vercel.+- Explore the [pre-built Auth UI for React](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui).+- Explore the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs).+- Explore the [Supabase Cache Helpers](https://github.com/psteinroe/supabase-cache-helpers).+- See the [Next.js Supscription Payments Starter](https://github.com/vercel/nextjs-subscription-payments) template on GitHub.- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-react.mdx b/apps/temp-docs/docs/guides/with-react.mdxindex 9f26002872f..43deef7a598 100644--- a/apps/temp-docs/docs/guides/with-react.mdx+++ b/apps/temp-docs/docs/guides/with-react.mdx@@ -2,164 +2,23 @@id: with-reacttitle: 'Quickstart: React'description: Learn how to use Supabase in your React App.+sidebar_label: React----# Quickstart: React+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-## Intro+<QuickstartIntro />-This example provides the steps to build a simple user management app (from scratch!) using Supabase and React. It includes:+-- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email).-- Supabase [Storage](/docs/guides/storage): users can upload a photo.-- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables.+### GitHub-By the end of this guide you'll have an app which allows users to login and update some basic profile details:+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/react-user-management).---<!-- ## Video demo--Coming soon.--Use the annotated timeline to step through this tutorial.--## Instant deploy--Want to deploy a completed version of this example without following the guide?--[](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Freact-user-management&project-name=supabase-user-management&repository-name=supabase-user-management&demo-title=Supabase%20User%20Management&demo-description=An%20example%20web%20app%20using%20Supabase%20and%20Next.js&demo-url=https%3A%2F%2Fsupabase-react-user-management.vercel.app&demo-image=https%3A%2F%2Fi.imgur.com%2FZ3HkQqe.png&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&external-id=nextjs-user-management)--Clicking this button the application will:--- Launch and prepare the Postgres database in Supabase.-- Launch the app in Vercel.-- Fork the example into your own GitHub account.-- Prepare the deployed application with all the necessary environment variables.--If you want to do it yourself, let's get started: -->--## Project set up--Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.--### Create a project--1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.--### Set up the database schema--Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.--<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="Dashboard UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>-</TabsPanel>-<TabsPanel id="SQL" label="SQL Code">--```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,-- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);--alter table profiles enable row level security;--create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );--create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );--create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );---- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;---- Set up Storage!-insert into storage.buckets (id, name)-values ('avatars', 'avatars');--create policy "Avatar images are publicly accessible."- on storage.objects for select- using ( bucket_id = 'avatars' );--create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );--```--</TabsPanel>-</Tabs>--### Get the API Keys--Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.--<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="second" label="second">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-</Tabs>+<ProjectSetup />## Building the App@@ -171,11 +30,11 @@ We can use [Create React App](https://create-react-app.dev/docs/getting-started/an app called `supabase-react`:```bash-npx create-react-app supabase-react --use-npm+npx create-react-app supabase-reactcd supabase-react```-Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)+Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js).```bashnpm install @supabase/supabase-js@@ -202,7 +61,7 @@ export const supabase = createClient(supabaseUrl, supabaseAnonKey)```And one optional step is to update the CSS file `src/index.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css).+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css).### Set up a Login component@@ -216,10 +75,12 @@ export default function Auth() {const [loading, setLoading] = useState(false)const [email, setEmail] = useState('')- const handleLogin = async (email) => {+ const handleLogin = async (e) => {+ e.preventDefault()+try {setLoading(true)- const { error } = await supabase.auth.signIn({ email })+ const { error } = await supabase.auth.signInWithOtp({ email })if (error) throw erroralert('Check your email for the login link!')} catch (error) {@@ -231,30 +92,29 @@ export default function Auth() {return (<div className="row flex-center flex">- <div className="col-6 form-widget">+ <div className="col-6 form-widget" aria-live="polite"><h1 className="header">Supabase + React</h1>- <p className="description">Sign in via magic link with your email below</p>- <div>- <input- className="inputField"- type="email"- placeholder="Your email"- value={email}- onChange={(e) => setEmail(e.target.value)}- />- </div>- <div>- <button- onClick={(e) => {- e.preventDefault()- handleLogin(email)- }}- className={'button block'}- disabled={loading}- >- {loading ? <span>Loading</span> : <span>Send magic link</span>}- </button>- </div>+ <p className="description">+ Sign in via magic link with your email below+ </p>+ {loading ? (+ 'Sending magic link...'+ ) : (+ <form onSubmit={handleLogin}>+ <label htmlFor="email">Email</label>+ <input+ id="email"+ className="inputField"+ type="email"+ placeholder="Your email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ />+ <button className="button block" aria-live="polite">+ Send magic link+ </button>+ </form>+ )}</div></div>)@@ -271,7 +131,7 @@ Let's create a new component for that called `Account.js`.import { useState, useEffect } from 'react'import { supabase } from './supabaseClient'-export default function Account({ session }) {+const Account = ({ session }) => {const [loading, setLoading] = useState(true)const [username, setUsername] = useState(null)const [website, setWebsite] = useState(null)@@ -281,10 +141,10 @@ export default function Account({ session }) {getProfile()}, [session])- async function getProfile() {+ const getProfile = async () => {try {setLoading(true)- const user = supabase.auth.user()+ const { user } = sessionlet { data, error, status } = await supabase.from('profiles')@@ -308,10 +168,12 @@ export default function Account({ session }) {}}- async function updateProfile({ username, website, avatar_url }) {+ const updateProfile = async (e) => {+ e.preventDefault()+try {setLoading(true)- const user = supabase.auth.user()+ const { user } = sessionconst updates = {id: user.id,@@ -321,9 +183,7 @@ export default function Account({ session }) {updated_at: new Date(),}- let { error } = await supabase.from('profiles').upsert(updates, {- returning: 'minimal', // Don't return the value after inserting- })+ let { error } = await supabase.from('profiles').upsert(updates)if (error) {throw error@@ -336,48 +196,49 @@ export default function Account({ session }) {}return (- <div className="form-widget">- <div>- <label htmlFor="email">Email</label>- <input id="email" type="text" value={session.user.email} disabled />- </div>- <div>- <label htmlFor="username">Name</label>- <input- id="username"- type="text"- value={username || ''}- onChange={(e) => setUsername(e.target.value)}- />- </div>- <div>- <label htmlFor="website">Website</label>- <input- id="website"- type="website"- value={website || ''}- onChange={(e) => setWebsite(e.target.value)}- />- </div>-- <div>- <button- className="button primary block"- onClick={() => updateProfile({ username, website, avatar_url })}- disabled={loading}- >- {loading ? 'Loading ...' : 'Update'}- </button>- </div>-- <div>- <button className="button block" onClick={() => supabase.auth.signOut()}>- Sign Out- </button>- </div>+ <div aria-live="polite">+ {loading ? (+ 'Saving ...'+ ) : (+ <form onSubmit={updateProfile} className="form-widget">+ <div>Email: {session.user.email}</div>+ <div>+ <label htmlFor="username">Name</label>+ <input+ id="username"+ type="text"+ value={username || ''}+ onChange={(e) => setUsername(e.target.value)}+ />+ </div>+ <div>+ <label htmlFor="website">Website</label>+ <input+ id="website"+ type="url"+ value={website || ''}+ onChange={(e) => setWebsite(e.target.value)}+ />+ </div>+ <div>+ <button className="button primary block" disabled={loading}>+ Update profile+ </button>+ </div>+ </form>+ )}+ <button+ type="button"+ className="button block"+ onClick={() => supabase.auth.signOut()}+ >+ Sign Out+ </button></div>)}++export default Account```### Launch!@@ -391,11 +252,13 @@ import { supabase } from './supabaseClient'import Auth from './Auth'import Account from './Account'-export default function Home() {+export default function App() {const [session, setSession] = useState(null)useEffect(() => {- setSession(supabase.auth.session())+ supabase.auth.getSession().then(({ data: { session } }) => {+ setSession(session)+ })supabase.auth.onAuthStateChange((_event, session) => {setSession(session)@@ -404,7 +267,11 @@ export default function Home() {return (<div className="container" style={{ padding: '50px 0 100px 0' }}>- {!session ? <Auth /> : <Account key={session.user.id} session={session} />}+ {!session ? (+ <Auth />+ ) : (+ <Account key={session.user.id} session={session} />+ )}</div>)}@@ -418,7 +285,7 @@ npm startAnd then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.-+## Bonus: Profile photos@@ -440,9 +307,11 @@ export default function Avatar({ url, size, onUpload }) {if (url) downloadImage(url)}, [url])- async function downloadImage(path) {+ const downloadImage = async (path) => {try {- const { data, error } = await supabase.storage.from('avatars').download(path)+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)if (error) {throw error}@@ -453,7 +322,7 @@ export default function Avatar({ url, size, onUpload }) {}}- async function uploadAvatar(event) {+ const uploadAvatar = async (event) => {try {setUploading(true)@@ -466,7 +335,9 @@ export default function Avatar({ url, size, onUpload }) {const fileName = `${Math.random()}.${fileExt}`const filePath = `${fileName}`- let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)+ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(filePath, file)if (uploadError) {throw uploadError@@ -481,33 +352,31 @@ export default function Avatar({ url, size, onUpload }) {}return (- <div>- {avatarUrl ? (- <img- src={avatarUrl}- alt="Avatar"- className="avatar image"- style={{ height: size, width: size }}- />+ <div style={{ width: size }} aria-live="polite">+ <img+ src={avatarUrl ? avatarUrl : `https://place-hold.it/${size}x${size}`}+ alt={avatarUrl ? 'Avatar' : 'No image'}+ className="avatar image"+ style={{ height: size, width: size }}+ />+ {uploading ? (+ 'Uploading...') : (- <div className="avatar no-image" style={{ height: size, width: size }} />+ <>+ <label className="button primary block" htmlFor="single">+ Upload an avatar+ </label>+ <div className="visually-hidden">+ <input+ type="file"+ id="single"+ accept="image/*"+ onChange={uploadAvatar}+ disabled={uploading}+ />+ </div>+ </>)}- <div style={{ width: size }}>- <label className="button primary block" htmlFor="single">- {uploading ? 'Uploading ...' : 'Upload'}- </label>- <input- style={{- visibility: 'hidden',- position: 'absolute',- }}- type="file"- id="single"- accept="image/*"- onChange={uploadAvatar}- disabled={uploading}- />- </div></div>)}diff --git a/apps/temp-docs/docs/guides/with-redwoodjs.mdx b/apps/temp-docs/docs/guides/with-redwoodjs.mdxindex 377e0b2ff94..792af09bd5b 100644--- a/apps/temp-docs/docs/guides/with-redwoodjs.mdx+++ b/apps/temp-docs/docs/guides/with-redwoodjs.mdx@@ -2,12 +2,11 @@id: with-redwoodjstitle: 'Quickstart: RedwoodJS'description: Learn how to use Supabase in your RedwoodJS App.+sidebar_label: RedwoodJS----# Quickstart: RedwoodJS-import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'+import TabItem from '@theme/TabItem'## Intro@@ -32,15 +31,15 @@ This example provides the steps to build a simple user management app (from scraBy the end of this guide you'll have an app which allows users to login and update some basic profile details:-+:::noteNote: For RedwoodJS apps, port will be 8910:::-### Github+### GitHub-If you get stuck at any point, take a look at [this repo](https://github.com/dthyresson/redwoodjs-supabase-quickstart).+If you get stuck at any point, take a look at [this repo](https://github.com/redwoodjs/redwoodjs-supabase-quickstart).<!-- ## Video demo@@ -109,22 +108,28 @@ Now we are going to set up the database schema. We can use the "User Managementor you can just copy/paste the SQL from below and run it yourself.<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-4. Click "Run".-```+ defaultValue="dashboard"+ values={[+ {label: 'Dashboard', value: 'dashboard'},+ {label: 'SQL', value: 'sql'},+ ]}>+<TabItem value="dashboard">++1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard.+2. Click **User Management Starter**.+3. Click **Run**.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/sql-user-management-starter.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-</TabsPanel>-<TabsPanel id="SQL" label="SQL">+</TabItem>+<TabItem value="sql">```sql-- Create a table for public "profiles"@@ -175,7 +180,7 @@ create policy "Anyone can upload an avatar."```-</TabsPanel>+</TabItem></Tabs>#### Important Note about Prisma and Migrations@@ -189,23 +194,19 @@ Because this Quick Start does not use Prisma to manage the database schema, seedNow that you've created some database tables, you are ready to insert data using the auto-generated API.We just need to get the URL as well as the `anon`, `service_role` and `JWT_SECRET` keys from the API settings.-<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "JWT Secret" keys on this page.-```+1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard.+2. Click **API** in the sidebar.+3. Find your API `URL`, `anon`, and `service_role` keys on this page.<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />+ <source+ src="/docs/videos/api/api-url-and-key.mp4"+ type="video/mp4"+ muted+ playsInline+ /></video>-</TabsPanel>-</Tabs>-## Building the AppLet's start building the RedwoodJS app from scratch.@@ -302,7 +303,10 @@ import { createClient } from '@supabase/supabase-js'// ...-const supabaseClient = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)+const supabaseClient = createClient(+ process.env.SUPABASE_URL,+ process.env.SUPABASE_KEY+)const App = () => (<FatalErrorBoundary page={FatalErrorPage}>@@ -320,7 +324,7 @@ export default App```And one optional step is to update the CSS file `web/src/index.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css).+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css).### Start RedwoodJS and your first Page@@ -414,7 +418,9 @@ const Auth = () => {<div className="row flex-center flex"><div className="col-6 form-widget"><h1 className="header">Supabase + RedwoodJS</h1>- <p className="description">Sign in via magic link with your email below</p>+ <p className="description">+ Sign in via magic link with your email below+ </p><div><inputclassName="inputField"@@ -628,7 +634,7 @@ yarn rw devAnd then open the browser to [localhost:8910](http://localhost:8910) and you should see the completed app.-+## Bonus: Profile photos@@ -664,7 +670,9 @@ const Avatar = ({ url, size, onUpload }) => {async function downloadImage(path) {try {- const { data, error } = await supabase.storage.from('avatars').download(path)+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)if (error) {throw error}@@ -688,7 +696,9 @@ const Avatar = ({ url, size, onUpload }) => {const fileName = `${Math.random()}.${fileExt}`const filePath = `${fileName}`- let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)+ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(filePath, file)if (uploadError) {throw uploadError@@ -712,7 +722,10 @@ const Avatar = ({ url, size, onUpload }) => {style={{ height: size, width: size }}/>) : (- <div className="avatar no-image" style={{ height: size, width: size }} />+ <div+ className="avatar no-image"+ style={{ height: size, width: size }}+ />)}<div style={{ width: size }}><label className="button primary block" htmlFor="single">diff --git a/apps/temp-docs/docs/guides/with-solidjs.mdx b/apps/temp-docs/docs/guides/with-solidjs.mdxnew file mode 100644index 00000000000..8cdacfcc4cf--- /dev/null+++ b/apps/temp-docs/docs/guides/with-solidjs.mdx@@ -0,0 +1,434 @@+---+id: with-solidjs+title: 'Quickstart: SolidJS'+description: Learn how to use Supabase in your SolidJS App.+sidebar_label: SolidJS+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/solid-user-management).++<ProjectSetup />++## Building the App++Let's start building the SolidJS app from scratch.++### Initialize a SolidJS app++We can use [Degit](https://github.com/Rich-Harris/degit) to initialize an app called `supabase-solid`:++```bash+npx degit solidjs/templates/ts supabase-solid+cd supabase-solid+```++Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+```++And finally we want to save the environment variables in a `.env`.+All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).++```bash title=".env"+VITE_SUPABASE_URL=YOUR_SUPABASE_URL+VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY+```++Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed+on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```js title="src/supabaseClient.jsx"+import { createClient } from '@supabase/supabase-js'++const supabaseUrl = import.meta.env.VITE_SUPABASE_URL+const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY++export const supabase = createClient(supabaseUrl, supabaseAnonKey)+```++And one optional step is to update the CSS file `src/index.css` to make the app look nice.+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/solid-user-management/src/index.css).++### Set up a Login component++Let's set up a SolidJS component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.++```jsx title="/src/Auth.tsx"+import { createSignal } from 'solid-js'+import { supabase } from './supabaseClient'++export default function Auth() {+ const [loading, setLoading] = createSignal(false)+ const [email, setEmail] = createSignal('')++ const handleLogin = async (e: SubmitEvent) => {+ e.preventDefault()++ try {+ setLoading(true)+ const { error } = await supabase.auth.signInWithOtp({ email: email() })+ if (error) throw error+ alert('Check your email for the login link!')+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ setLoading(false)+ }+ }++ return (+ <div class="row flex-center flex">+ <div class="col-6 form-widget" aria-live="polite">+ <h1 class="header">Supabase + SolidJS</h1>+ <p class="description">Sign in via magic link with your email below</p>+ <form class="form-widget" onSubmit={handleLogin}>+ <div>+ <label for="email">Email</label>+ <input+ id="email"+ class="inputField"+ type="email"+ placeholder="Your email"+ value={email()}+ onChange={(e) => setEmail(e.currentTarget.value)}+ />+ </div>+ <div>+ <button type="submit" class="button block" aria-live="polite">+ {loading() ? <span>Loading</span> : <span>Send magic link</span>}+ </button>+ </div>+ </form>+ </div>+ </div>+ )+}+```++### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.++Let's create a new component for that called `Account.tsx`.++```jsx title="src/Account.tsx"+import { AuthSession } from '@supabase/supabase-js'+import { Component, createEffect, createSignal } from 'solid-js'+import { supabase } from './supabaseClient'++interface Props {+ session: AuthSession;+}++const Account: Component<Props> = ({ session }) => {+ const [loading, setLoading] = createSignal(true)+ const [username, setUsername] = (createSignal < string) | (null > null)+ const [website, setWebsite] = (createSignal < string) | (null > null)+ const [avatarUrl, setAvatarUrl] = (createSignal < string) | (null > null)++ createEffect(() => {+ getProfile()+ })++ const getProfile = async () => {+ try {+ setLoading(true)+ const { user } = session++ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user.id)+ .single()++ if (error && status !== 406) {+ throw error+ }++ if (data) {+ setUsername(data.username)+ setWebsite(data.website)+ setAvatarUrl(data.avatar_url)+ }+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ setLoading(false)+ }+ }++ const updateProfile = async (e: Event) => {+ e.preventDefault()++ try {+ setLoading(true)+ const { user } = session++ const updates = {+ id: user.id,+ username: username(),+ website: website(),+ avatar_url: avatarUrl(),+ updated_at: new Date().toISOString(),+ }++ let { error } = await supabase.from('profiles').upsert(updates)++ if (error) {+ throw error+ }+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ setLoading(false)+ }+ }++ return (+ <div aria-live="polite">+ <form onSubmit={updateProfile} class="form-widget">+ <div>Email: {session.user.email}</div>+ <div>+ <label for="username">Name</label>+ <input+ id="username"+ type="text"+ value={username() || ''}+ onChange={(e) => setUsername(e.currentTarget.value)}+ />+ </div>+ <div>+ <label for="website">Website</label>+ <input+ id="website"+ type="text"+ value={website() || ''}+ onChange={(e) => setWebsite(e.currentTarget.value)}+ />+ </div>+ <div>+ <button+ type="submit"+ class="button primary block"+ disabled={loading()}+ >+ {loading() ? 'Saving ...' : 'Update profile'}+ </button>+ </div>+ <button+ type="button"+ class="button block"+ onClick={() => supabase.auth.signOut()}+ >+ Sign Out+ </button>+ </form>+ </div>+ )+}++export default Account+```++### Launch!++Now that we have all the components in place, let's update `App.tsx`:++```jsx title="src/App.tsx"+import { Component, createEffect, createSignal } from 'solid-js'+import { supabase } from './supabaseClient'+import { AuthSession } from '@supabase/supabase-js'+import Account from './Account'+import Auth from './Auth'++const App: Component = () => {+ const [session, setSession] = createSignal<AuthSession | null>(null)++ createEffect(() => {+ supabase.auth.getSession().then(({ data: { session } }) => {+ setSession(session)+ })++ supabase.auth.onAuthStateChange((_event, session) => {+ setSession(session)+ })+ })++ return (+ <div class="container" style={{ padding: '50px 0 100px 0' }}>+ {!session() ? <Auth /> : <Account session={session()!} />}+ </div>+ )+}++export default App+```++Once that's done, run this in a terminal window:++```bash+npm start+```++And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.++++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.++### Create an upload widget++Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:++```jsx title="src/Avatar.tsx"+import { Component, createEffect, createSignal, JSX } from 'solid-js'+import { supabase } from './supabaseClient'++interface Props {+ size: number+ url: string | null+ onUpload: (event: Event, filePath: string) => void+}++const Avatar: Component<Props> = (props) => {+ const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null)+ const [uploading, setUploading] = createSignal(false)++ createEffect(() => {+ if (props.url) downloadImage(props.url)+ })++ const downloadImage = async (path: string) => {+ try {+ const { data, error } = await supabase.storage.from('avatars').download(path)+ if (error) {+ throw error+ }+ const url = URL.createObjectURL(data)+ setAvatarUrl(url)+ } catch (error) {+ if (error instanceof Error) {+ console.log('Error downloading image: ', error.message)+ }+ }+ }++ const uploadAvatar: JSX.EventHandler<HTMLInputElement, Event> = async (event) => {+ try {+ setUploading(true)++ const target = event.currentTarget+ if (!target?.files || target.files.length === 0) {+ throw new Error('You must select an image to upload.')+ }++ const file = target.files[0]+ const fileExt = file.name.split('.').pop()+ const fileName = `${Math.random()}.${fileExt}`+ const filePath = `${fileName}`++ let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)++ if (uploadError) {+ throw uploadError+ }++ props.onUpload(event, filePath)+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ setUploading(false)+ }+ }++ return (+ <div style={{ width: props.size }} aria-live="polite">+ {avatarUrl() ? (+ <img+ src={avatarUrl()!}+ alt={avatarUrl() ? 'Avatar' : 'No image'}+ class="avatar image"+ style={{ height: `${props.size}px`, width: `${props.size}px` }}+ />+ ) : (+ <div+ class="avatar no-image"+ style={{ height: `${props.size}px`, width: `${props.size}px` }}+ />+ )}+ <div style={{ width: `${props.size}px` }}>+ <label class="button primary block" for="single">+ {uploading() ? 'Uploading ...' : 'Upload avatar'}+ </label>+ <span style="display:none">+ <input+ type="file"+ id="single"+ accept="image/*"+ onChange={uploadAvatar}+ disabled={uploading()}+ />+ </span>+ </div>+ </div>+ )+}++export default Avatar+```++### Add the new widget++And then we can add the widget to the Account page:++```jsx title="src/Account.tsx"+// Import the new component+import Avatar from './Avatar'++// ...++return (+ <form onSubmit={updateProfile} class="form-widget">+ {/* Add to the body */}+ <Avatar+ url={avatarUrl()}+ size={150}+ onUpload={(e: Event, url: string) => {+ setAvatarUrl(url)+ updateProfile(e)+ }}+ />+ {/* ... */}+ </div>+)+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-svelte.mdx b/apps/temp-docs/docs/guides/with-svelte.mdxindex 7608069d74e..2a423276170 100644--- a/apps/temp-docs/docs/guides/with-svelte.mdx+++ b/apps/temp-docs/docs/guides/with-svelte.mdx@@ -2,139 +2,23 @@id: with-sveltetitle: 'Quickstart: Svelte'description: Learn how to use Supabase in your Svelte App.+sidebar_label: Svelte----# Quickstart: Svelte-import Tabs from '@theme/Tabs'-import TabsPanel from '@theme/TabsPanel'--## Intro--This example provides the steps to build a simple user management app (from scratch!) using Supabase and Svelte. It includes:--- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email).-- Supabase [Storage](/docs/guides/storage): users can upload a photo.-- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables.--By the end of this guide you'll have an app which allows users to login and update some basic profile details:----### Github--Whenever you get stuck at any point, take a look at [this repo](https://github.com/yustarandomname/svelte-supabase-quickstart).--## Project set up--Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.--### Create a project--1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.--### Set up the database schema--Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.--<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="SQL" label="SQL">--```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,-- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);--alter table profiles enable row level security;--create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );+<QuickstartIntro />-create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );+--- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;+### GitHub--- Set up Storage!-insert into storage.buckets (id, name)-values ('avatars', 'avatars');+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/svelte-user-management).-create policy "Avatar images are publicly accessible."- on storage.objects for select- using ( bucket_id = 'avatars' );--create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );--```--</TabsPanel>-</Tabs>--### Get the API Keys--Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.--<Tabs defaultActiveId="UI">-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-</Tabs>+<ProjectSetup />## Building the App@@ -142,12 +26,12 @@ Let's start building the Svelte app from scratch.### Initialize a Svelte app-We can use the [Quickstart Svelte Template](https://svelte.dev/blog/the-easiest-way-to-get-started) to initialize-an app called `supabase-svelte`:+We can use the Vite Svelte TypeScript Template to initialize an app called `supabase-svelte`:```bash-npx degit sveltejs/template supabase-svelte+npm create vite@latest supabase-svelte -- --template svelte-tscd supabase-svelte+npm install```Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)@@ -160,136 +44,112 @@ And finally we want to save the environment variables in a `.env`.All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).```bash title=".env"-SVELTE_APP_SUPABASE_URL=YOUR_SUPABASE_URL-SVELTE_APP_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY-```--Our app is almost functional, to make svelte work with supabase and .env files we first need to change the `rollup.config.js` file a bit.-Supabase imports `json` files, to convert .json files to ES6 modules we need the `@rollup/plugin-json` install it by running:--```bash- npm install --save-dev @rollup/plugin-json-```--Furthermore, to use the .env with svelte we need another rollup plugin. Install:--```bash- npm install --save-dev dotenv @rollup/plugin-replace-```--and add these plugins to the `rollup.config.js` file.--```js title="rollup.config.js"-import { config } from 'dotenv'-import replace from '@rollup/plugin-replace'-import json from '@rollup/plugin-json'--export default {- plugins: [- replace({- __api: JSON.stringify({- env: {- isProd: production,- ...config().parsed, // attached the .env config- },- }),- delimiters: ['', ''],- }),- json(),- // ...- ],- // ...-}+VITE_SUPABASE_URL=YOUR_SUPABASE_URL+VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY```Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposedon the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.-```js title="src/supabaseClient.js"+```js title="src/supabaseClient.ts"import { createClient } from '@supabase/supabase-js'-const supabaseUrl = __api.env.SVELTE_APP_SUPABASE_URL-const supabaseAnonKey = __api.env.SVELTE_APP_SUPABASE_ANON_KEY+const supabaseUrl = import.meta.env.VITE_SUPABASE_URL+const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEYexport const supabase = createClient(supabaseUrl, supabaseAnonKey)```-And one optional step is to update the CSS file `public/global.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css).+And one optional step is to update the CSS file `src/app.css` to make the app look nice.+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/svelte-user-management/src/app.css).### Set up a Login componentLet's set up a Svelte component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.-```html title="/src/Auth.svelte"-<script>- import { supabase } from './supabaseClient'+```html title="src/lib/Auth.svelte"+<script lang="ts">+ import { supabase } from 'src/supabaseClient'let loading = false- let email+ let email = ''const handleLogin = async () => {try {loading = true- const { error } = await supabase.auth.signIn({ email })+ const { error } = await supabase.auth.signInWithOtp({ email })if (error) throw error- alert('Check your email for the login link!')+ alert('Check your email for login link!')} catch (error) {- alert(error.error_description || error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {loading = false}}</script>-<form class="row flex-center flex" on:submit|preventDefault="{handleLogin}">- <div class="col-6 form-widget">+<div class="row flex-center flex">+ <div class="col-6 form-widget" aria-live="polite"><h1 class="header">Supabase + Svelte</h1><p class="description">Sign in via magic link with your email below</p>- <div>- <input class="inputField" type="email" placeholder="Your email" bind:value="{email}" />- </div>- <div>- <input type="submit" class='button block' value={loading ? "Loading" : "Send magic link"}- disabled={loading} />- </div>+ <form class="form-widget" on:submit|preventDefault="{handleLogin}">+ <div>+ <label for="email">Email</label>+ <input+ id="email"+ class="inputField"+ type="email"+ placeholder="Your email"+ bind:value="{email}"+ />+ </div>+ <div>+ <button+ type="submit"+ class="button block"+ aria-live="polite"+ disabled="{loading}"+ >+ <span>{loading ? 'Loading' : 'Send magic link'}</span>+ </button>+ </div>+ </form></div>-</form>-```--### User store--To access the user information in other places, we use a writable store. Create a new file called `sessionStore.js`--```javascript title="src/sessionStore.js"-import { writable } from 'svelte/store'--export const user = writable(false)+</div>```### Account pageAfter a user is signed in we can allow them to edit their profile details and manage their account.-Let's create a new component for that called `Profile.svelte`.+Let's create a new component for that called `Account.svelte`.-```html title="src/Profile.svelte"-<script>- import { supabase } from './supabaseClient'- import { user } from './sessionStore'+```html title="src/lib/Account.svelte"+<script lang="ts">+ import { onMount } from "svelte";+ import type { AuthSession } from "@supabase/supabase-js";+ import { supabase } from "../supabaseClient";- let loading = true- let username = null- let website = null- let avatar_url = null+ export let session: AuthSession;- async function getProfile() {+ let loading = false+ let username: string | null = null+ let website: string | null = null+ let avatarUrl: string | null = null++ onMount(() => {+ getProfile()+ })++ const getProfile = async () => {try {loading = true- const user = supabase.auth.user()+ const { user } = session- let { data, error, status } = await supabase+ const { data, error, status } = await supabase.from('profiles')- .select(`username, website, avatar_url`)+ .select('username, website, avatar_url').eq('id', user.id).single()@@ -298,75 +158,63 @@ Let's create a new component for that called `Profile.svelte`.if (data) {username = data.usernamewebsite = data.website- avatar_url = data.avatar_url+ avatarUrl = data.avatar_url}} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {loading = false}}- async function updateProfile() {+ const updateProfile = async () => {try {loading = true- const user = supabase.auth.user()+ const { user } = sessionconst updates = {id: user.id,username,website,- avatar_url,- updated_at: new Date(),+ avatar_url: avatarUrl,+ updated_at: new Date().toISOString(),}- let { error } = await supabase.from('profiles').upsert(updates, {- returning: 'minimal', // Don't return the value after inserting- })+ let { error } = await supabase.from('profiles').upsert(updates)- if (error) throw error- } catch (error) {- alert(error.message)- } finally {- loading = false- }- }-- async function signOut() {- try {- loading = true- let { error } = await supabase.auth.signOut()- if (error) throw error+ if (error) {+ throw error+ }} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {loading = false}}</script>-<form use:getProfile class="form-widget" on:submit|preventDefault="{updateProfile}">- <div>- <label for="email">Email</label>- <input id="email" type="text" value="{$user.email}" disabled />- </div>+<form on:submit|preventDefault={updateProfile} class="form-widget">+ <div>Email: {session.user.email}</div><div><label for="username">Name</label>- <input id="username" type="text" bind:value="{username}" />+ <input id="username" type="text" bind:value={username} /></div><div><label for="website">Website</label>- <input id="website" type="website" bind:value="{website}" />+ <input id="website" type="text" bind:value={website} /></div>-<div>- <input type="submit" class="button block primary" value={loading ? 'Loading ...' : 'Update'}- disabled={loading}/>- </div>-- <div>- <button class="button block" on:click="{signOut}" disabled="{loading}">Sign Out</button>+ <button type="submit" class="button primary block" disabled={loading}>+ {loading ? 'Saving ...' : 'Update profile'}+ </button></div>+ <button type="button" class="button block" on:click={() => supabase.auth.signOut()}>+ Sign Out+ </button></form>```@@ -375,24 +223,31 @@ Let's create a new component for that called `Profile.svelte`.Now that we have all the components in place, let's update `App.svelte`:```html title="src/App.svelte"-<script>- import { user } from './sessionStore'+<script lang="ts">+ import { onMount } from 'svelte'import { supabase } from './supabaseClient'- import Auth from './Auth.svelte'- import Profile from './Profile.svelte'+ import type { AuthSession } from '@supabase/supabase-js'+ import Account from './lib/Account.svelte'+ import Auth from './lib/Auth.svelte'- user.set(supabase.auth.user())+ let session: AuthSession- supabase.auth.onAuthStateChange((_, session) => {- user.set(session.user)+ onMount(() => {+ supabase.auth.getSession().then(({ data }) => {+ session = data.session+ })++ supabase.auth.onAuthStateChange((_event, _session) => {+ session = _session+ })})</script>-<div class="container" style="padding: 50px 0 100px 0;">- {#if $user}- <Profile />- {:else}+<div class="container" style="padding: 50px 0 100px 0">+ {#if !session}<Auth />+ {:else}+ <Account {session} />{/if}</div>```@@ -403,11 +258,11 @@ Once that's done, run this in a terminal window:npm run dev```-And then open the browser to [localhost:5000](http://localhost:5000) and you should see the completed app.+And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.-> ⚠️ WARNING: Svelte uses by default `port 5000`, Supabase uses `port 3000`. To change the redirection port for supabase go to: `Authentication > Settings` and change the `Site Url` to `localhost:5000`+> ⚠️ WARNING: Svelte uses Vite and the default port is `5173`, Supabase uses `port 3000`. To change the redirection port for supabase go to: `Authentication > Settings` and change the `Site Url` to `localhost:5173`-+## Bonus: Profile photos@@ -417,32 +272,40 @@ Every Supabase project is configured with [Storage](/docs/guides/storage) for maLet's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:-```html title="src/Avatar.svelte"-<script>+```html title="src/lib/Avatar.svelte"+<script lang="ts">import { createEventDispatcher } from 'svelte'- import { supabase } from './supabaseClient'+ import { supabase } from '../supabaseClient'- export let path- export let size = '10em'+ export let size: number+ export let url: string+ let avatarUrl: string = nulllet uploading = false- let src- let files+ let files: FileListconst dispatch = createEventDispatcher()- async function downloadImage() {+ const downloadImage = async (path: string) => {try {- const { data, error } = await supabase.storage.from('avatars').download(path)- if (error) throw error+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path)- src = URL.createObjectURL(data)+ if (error) {+ throw error+ }++ const url = URL.createObjectURL(data)+ avatarUrl = url} catch (error) {- console.error('Error downloading image: ', error.message)+ if (error instanceof Error) {+ console.log('Error downloading image: ', error.message)+ }}}- async function uploadAvatar() {+ const uploadAvatar = async () => {try {uploading = true@@ -452,49 +315,49 @@ Let's create an avatar for the user so that they can upload a profile photo. Weconst file = files[0]const fileExt = file.name.split('.').pop()- const fileName = `${Math.random()}.${fileExt}`- const filePath = `${fileName}`+ const filePath = `${Math.random()}.${fileExt}`- let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)+ let { error } = await supabase.storage+ .from('avatars')+ .upload(filePath, file)- if (uploadError) throw uploadError+ if (error) {+ throw error+ }- path = filePath+ url = filePathdispatch('upload')} catch (error) {- alert(error.message)+ if (error instanceof Error) {+ alert(error.message)+ }} finally {uploading = false}}++ $: if (url) downloadImage(url)</script>-<div>- {#if path}- <img- use:downloadImage- {src}- alt="Avatar"- class="avatar image"- style="height: {size}; width: {size};"- />- {:else}- <div class="avatar no-image" style="height: {size}; width: {size};" />+<div style="width: {size}px" aria-live="polite">+ {#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'}+ class="avatar image" style="height: {size}px, width: {size}px" /> {:else}+ <div class="avatar no-image" style="height: {size}px, width: {size}px" />{/if}-- <div style="width: {size};">+ <div style="width: {size}px"><label class="button primary block" for="single">- {uploading ? 'Uploading ...' : 'Upload'}+ {uploading ? 'Uploading ...' : 'Upload avatar'}</label>- <input- style="visibility: hidden; position:absolute;"- type="file"- id="single"- accept="image/*"- bind:files- on:change="{uploadAvatar}"- disabled="{uploading}"- />+ <span style="display:none">+ <input+ type="file"+ id="single"+ accept="image/*"+ bind:files+ on:change="{uploadAvatar}"+ disabled="{uploading}"+ />+ </span></div></div>```@@ -503,15 +366,15 @@ Let's create an avatar for the user so that they can upload a profile photo. WeAnd then we can add the widget to the Account page:-```html title="src/Profile.svelte"-<script>+```html title="src/lib/Account.svelte"+<script lang="ts">// Import the new componentimport Avatar from './Avatar.svelte'</script>-<form use:getProfile class="form-widget" on:submit|preventDefault="{updateProfile}">+<form on:submit|preventDefault="{updateProfile}" class="form-widget"><!-- Add to body -->- <Avatar bind:path="{avatar_url}" on:upload="{updateProfile}" />+ <Avatar bind:url="{avatarUrl}" size="{150}" on:upload="{updateProfile}" /><!-- Other form elements --></form>diff --git a/apps/temp-docs/docs/guides/with-sveltekit.mdx b/apps/temp-docs/docs/guides/with-sveltekit.mdxnew file mode 100644index 00000000000..86f2c66592d--- /dev/null+++ b/apps/temp-docs/docs/guides/with-sveltekit.mdx@@ -0,0 +1,463 @@+---+id: with-sveltekit+title: 'Quickstart: SvelteKit'+description: Learn how to use Supabase in your SvelteKit App.+sidebar_label: SvelteKit+---++import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'++<QuickstartIntro />++++### GitHub++Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/sveltekit-user-management).++<ProjectSetup />++## Building the App++Let's start building the Svelte app from scratch.++### Initialize a Svelte app++We can use the [SvelteKit Skeleton Project](https://kit.svelte.dev/docs) to initialize+an app called `supabase-sveltekit` (for this tutorial you do not need TypeScript, ESLint, Prettier, or Playwright):++```bash+npm init svelte@next supabase-sveltekit+cd supabase-sveltekit+npm install+```++Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)++```bash+npm install @supabase/supabase-js+```++And finally we want to save the environment variables in a `.env`.+All we need are the `SUPABASE_URL` and the `SUPABASE_KEY` key that you copied [earlier](#get-the-api-keys).++```bash title=".env"+PUBLIC_SUPABASE_URL="YOUR_SUPABASE_URL"+PUBLIC_SUPABASE_ANON_KEY="YOUR_SUPABASE_KEY"+```++Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed+on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.++```js title="src/lib/supabaseClient.ts"+import { createClient } from '@supabase/auth-helpers-sveltekit'+import { env } from '$env/dynamic/public'++export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY)+```++And one optional step is to update the CSS file `public/global.css` to make the app look nice.+You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/svelte-user-management/src/app.css).++### Supabase Auth Helpers++SvelteKit is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and more.++It can be challenging to authenticate your users in all these different environments, that's why we've created the Supabase Auth Helpers to make user management and data fetching within SvelteKit as easy as possible.++Install the auth helpers for SvelteKit:++```bash+npm install @supabase/auth-helpers-sveltekit+```++Update your `src/routes/+layout.svelte`:++```html title="src/routes/+layout.svelte"+<script lang="ts">+ import { supabaseClient } from '$lib/supabaseClient'+ import { invalidate } from '$app/navigation'+ import { onMount } from 'svelte'+ import './styles.css'++ onMount(() => {+ const {+ data: { subscription }+ } = supabaseClient.auth.onAuthStateChange(() => {+ invalidate('supabase:auth')+ })++ return () => {+ subscription.unsubscribe()+ }+ })+</script>++<div class="container" style="padding: 50px 0 100px 0">+ <slot />+</div>+```++Create a new `src/routes/+layout.ts` file to handle the session on the client-side.++```ts title="src/routes/+layout.ts"+import type { LayoutLoad } from './$types';+import { getSupabase } from '@supabase/auth-helpers-sveltekit';++export const load: LayoutLoad = async (event) => {+ const { session } = await getSupabase(event);+ return { session };+};+```++Create a new `src/routes/+layout.server.ts` file to handle the session on the server-side.++```ts title="src/routes/+layout.server.ts"+import type { LayoutServerLoad } from './$types';+import { getServerSession } from '@supabase/auth-helpers-sveltekit';++export const load: LayoutServerLoad = async (event) => {+ return {+ session: await getServerSession(event)+ };+};+```++Be sure to create `src/hooks.client.ts` and `src/hooks.server.ts` in order to get the auth helper started on the client and server-side.++```ts title="src/hooks.client.ts"+import '$lib/supabaseClient'+```++```ts title="src/hooks.server.ts"+import '$lib/supabaseClient'+```++### Set up a Login component++Let's set up a Svelte component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.++```html title="src/routes/Auth.svelte"+<script lang="ts">+ import { supabaseClient } from '$lib/supabaseClient'++ let loading = false+ let email: string++ const handleLogin = async () => {+ try {+ loading = true+ const { error } = await supabaseClient.auth.signInWithOtp({ email })+ if (error) throw error+ alert('Check your email for the login link!')+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ loading = false+ }+ }+</script>++<form class="row flex-center flex" on:submit|preventDefault={handleLogin}>+ <div class="col-6 form-widget">+ <h1 class="header">Supabase + SvelteKit</h1>+ <p class="description">Sign in via magic link with your email below</p>+ <div>+ <input class="inputField" type="email" placeholder="Your email" bind:value={email} />+ </div>+ <div>+ <input+ type="submit"+ class="button block"+ value={loading ? 'Loading' : 'Send magic link'}+ disabled={loading}+ />+ </div>+ </div>+</form>+```++### Account component++After a user is signed in, they need to be able to edit their profile details and manage their account.+Create a new `Account.svelte` component to handle this functionality.++```html title="src/routes/Account.svelte"+<script lang="ts">+ import { onMount } from 'svelte'+ import type { AuthSession } from '@supabase/supabase-js'+ import { supabaseClient } from '$lib/supabaseClient'++ export let session: AuthSession++ let loading = false+ let username: string | null = null+ let website: string | null = null+ let avatarUrl: string | null = null++ onMount(() => {+ getProfile()+ })++ const getProfile = async () => {+ try {+ loading = true+ const { user } = session++ const { data, error, status } = await supabaseClient+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user.id)+ .single()++ if (data) {+ username = data.username+ website = data.website+ avatarUrl = data.avatar_url+ }++ if (error && status !== 406) throw error+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ loading = false+ }+ }++ async function updateProfile() {+ try {+ loading = true+ const { user } = session++ const updates = {+ id: user.id,+ username,+ website,+ avatar_url: avatarUrl,+ updated_at: new Date()+ }++ let { error } = await supabaseClient.from('profiles').upsert(updates)++ if (error) throw error+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ loading = false+ }+ }++ async function signOut() {+ try {+ loading = true+ let { error } = await supabaseClient.auth.signOut()+ if (error) throw error+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ loading = false+ }+ }+</script>++<form class="form-widget" on:submit|preventDefault={updateProfile}>+ <div>+ <label for="email">Email</label>+ <input id="email" type="text" value={session.user.email} disabled />+ </div>+ <div>+ <label for="username">Name</label>+ <input id="username" type="text" bind:value={username} />+ </div>+ <div>+ <label for="website">Website</label>+ <input id="website" type="website" bind:value={website} />+ </div>++ <div>+ <input+ type="submit"+ class="button block primary"+ value={loading ? 'Loading...' : 'Update'}+ disabled={loading}+ />+ </div>++ <div>+ <button class="button block" on:click={signOut} disabled={loading}> Sign Out </button>+ </div>+</form>+```++### Launch!++Now that we have all the components in place, let's update `src/routes/+page.svelte`:++```html title="src/routes/+page.svelte"+<script>+ import { page } from '$app/stores'+ import Account from './Account.svelte'+ import Auth from './Auth.svelte'+</script>++<svelte:head>+ <title>Supabase + SvelteKit</title>+ <meta name="description" content="SvelteKit using supabase-js v2" />+</svelte:head>++{#if !$page.data.session}+ <Auth />+{:else}+ <Account session={$page.data.session} />+{/if}+```++Once that's done, run this in a terminal window:++```bash+npm run dev+```++And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.++++## Bonus: Profile photos++Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.++### Create an upload widget++Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:++```html title="src/routes/Avatar.svelte"+<script lang="ts">+ import { createEventDispatcher } from 'svelte'+ import { supabaseClient } from '$lib/supabaseClient'++ export let size = 10+ export let url: string++ let avatarUrl: string | null = null+ let uploading = false+ let files: FileList++ const dispatch = createEventDispatcher()++ const downloadImage = async (path: string) => {+ try {+ const { data, error } = await supabaseClient.storage.from('avatars').download(path)++ if (error) {+ throw error+ }++ const url = URL.createObjectURL(data)+ avatarUrl = url+ } catch (error) {+ if (error instanceof Error) {+ console.log('Error downloading image: ', error.message)+ }+ }+ }++ const uploadAvatar = async () => {+ try {+ uploading = true++ if (!files || files.length === 0) {+ throw new Error('You must select an image to upload.')+ }++ const file = files[0]+ const fileExt = file.name.split('.').pop()+ const filePath = `${Math.random()}.${fileExt}`++ let { error } = await supabaseClient.storage.from('avatars').upload(filePath, file)++ if (error) {+ throw error+ }++ url = filePath+ dispatch('upload')+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ uploading = false+ }+ }++ $: if (url) downloadImage(url)+</script>++<div>+ {#if avatarUrl}+ <img+ src={avatarUrl}+ alt={avatarUrl ? 'Avatar' : 'No image'}+ class="avatar image"+ style="height: {size}em; width: {size}em;"+ />+ {:else}+ <div class="avatar no-image" style="height: {size}em; width: {size}em;" />+ {/if}++ <div style="width: {size}em;">+ <label class="button primary block" for="single">+ {uploading ? 'Uploading ...' : 'Upload'}+ </label>+ <input+ style="visibility: hidden; position:absolute;"+ type="file"+ id="single"+ accept="image/*"+ bind:files+ on:change={uploadAvatar}+ disabled={uploading}+ />+ </div>+</div>+```++### Add the new widget++And then we can add the widget to the Account page:++```html title="src/routes/Account.svelte"+<script>+ // Import the new component+ import Avatar from './Avatar.svelte'+</script>++<form+ use:getProfile+ class="form-widget"+ on:submit|preventDefault="{updateProfile}"+>+ <!-- Add to body -->+ <Avatar bind:url={avatarUrl} size={10} on:upload={updateProfile} />++ <!-- Other form elements -->+</form>+```++## Next steps++At this stage you have a fully functional application!++- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).+- Sign in: [app.supabase.com](https://app.supabase.com)diff --git a/apps/temp-docs/docs/guides/with-vue-3.mdx b/apps/temp-docs/docs/guides/with-vue-3.mdxindex 0bf2e7d3ff1..30a7be5449e 100644--- a/apps/temp-docs/docs/guides/with-vue-3.mdx+++ b/apps/temp-docs/docs/guides/with-vue-3.mdx@@ -2,138 +2,23 @@id: with-vue-3title: 'Quickstart: Vue 3'description: Learn how to use Supabase in your Vue 3 App.+sidebar_label: 'Vue 3'----# Quickstart: Vue+import Tabs from '@theme/Tabs'+import TabItem from '@theme/TabItem'+import QuickstartIntro from './_partials/quickstart_intro.md'+import ProjectSetup from './_partials/project_setup.mdx'-## Intro+<QuickstartIntro />-This example provides the steps to build a simple user management app (from scratch!) using Supabase and Vue 3. It includes:+-- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data.-- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email).-- Supabase [Storage](/docs/guides/storage): users can upload a photo.-- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data.-- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables.+### GitHub-By the end of this guide you'll have an app which allows users to login and update some basic profile details:+Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/vue3-user-management).---### Github--Whenever you get stuck at any point, take a look at [this repo](https://github.com/zernonia/supabase-vue-3).--## Project set up--Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase-and then creating a "schema" inside the database.--### Create a project--1. Go to [app.supabase.com](https://app.supabase.com).-1. Click on "New Project".-1. Enter your project details.-1. Wait for the new database to launch.--### Set up the database schema--Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor,-or you can just copy/paste the SQL from below and run it yourself.--<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "SQL Editor" section.-2. Click "User Management Starter".-3. Click "Run".-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/sql-user-management-starter.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-<TabsPanel id="SQL" label="SQL">--```sql--- Create a table for public "profiles"-create table profiles (- id uuid references auth.users not null,- updated_at timestamp with time zone,- username text unique,- avatar_url text,- website text,-- primary key (id),- unique(username),- constraint username_length check (char_length(username) >= 3)-);--alter table profiles enable row level security;--create policy "Public profiles are viewable by everyone."- on profiles for select- using ( true );--create policy "Users can insert their own profile."- on profiles for insert- with check ( auth.uid() = id );--create policy "Users can update own profile."- on profiles for update- using ( auth.uid() = id );---- Set up Realtime!-begin;- drop publication if exists supabase_realtime;- create publication supabase_realtime;-commit;-alter publication supabase_realtime add table profiles;---- Set up Storage!-insert into storage.buckets (id, name)-values ('avatars', 'avatars');--create policy "Avatar images are publicly accessible."- on storage.objects for select- using ( bucket_id = 'avatars' );--create policy "Anyone can upload an avatar."- on storage.objects for insert- with check ( bucket_id = 'avatars' );--```--</TabsPanel>-</Tabs>--### Get the API Keys--Now that you've created some database tables, you are ready to insert data using the auto-generated API.-We just need to get the URL and `anon` key from the API settings.--<Tabs-defaultActiveId="UI"->-<TabsPanel id="UI" label="UI">--```sh-1. Go to the "Settings" section.-2. Click "API" in the sidebar.-3. Find your API URL in this page.-4. Find your "anon" and "service_role" keys on this page.-```--<video width="99%" muted playsInline controls="true">- <source src="/docs/videos/api/api-url-and-key.mp4" type="video/mp4" muted playsInline />-</video>--</TabsPanel>-</Tabs>+<ProjectSetup />## Building the App@@ -146,10 +31,10 @@ an app called `supabase-vue-3`:```bash# npm 6.x-npm init @vitejs/app supabase-vue-3 --template vue+npm create vite@latest supabase-vue-3 --template vue# npm 7+, extra double-dash is needed:-npm init @vitejs/app supabase-vue-3 -- --template vue+npm create vite@latest supabase-vue-3 -- --template vuecd supabase-vue-3```@@ -180,29 +65,50 @@ const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEYexport const supabase = createClient(supabaseUrl, supabaseAnonKey)```-And one optional step is to update the CSS file `src/assets/main.css` to make the app look nice.-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css).--```javascript title="src/main.js"-import { createApp } from 'vue'-import App from './App.vue'-import './assets/main.css'--createApp(App).mount('#app')-```+Optionally, update [src/style.css](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/vue3-user-management/src/style.css) to style the app.### Set up a Login componentLet's set up a Vue component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.```html title="/src/components/Auth.vue"+<script setup>+ import { ref } from 'vue'+ import { supabase } from '../supabase'++ const loading = ref(false)+ const email = ref('')++ const handleLogin = async () => {+ try {+ loading.value = true+ const { error } = await supabase.auth.signInWithOtp({+ email: email.value,+ })+ if (error) throw error+ alert('Check your email for the login link!')+ } catch (error) {+ if (error instanceof Error) {+ alert(error.message)+ }+ } finally {+ loading.value = false+ }+ }+</script>+<template><form class="row flex-center flex" @submit.prevent="handleLogin"><div class="col-6 form-widget"><h1 class="header">Supabase + Vue 3</h1><p class="description">Sign in via magic link with your email below</p><div>- <input class="inputField" type="email" placeholder="Your email" v-model="email" />+ <input+ class="inputField"+ type="email"+ placeholder="Your email"+ v-model="email"+ /></div><div><input@@ -215,62 +121,96 @@ Let's set up a Vue component to manage logins and sign ups. We'll use Magic Link</div></form></template>+```-<script>- import { ref } from 'vue'+### Account page++After a user is signed in we can allow them to edit their profile details and manage their account.+Let's create a new component for that called `Account.vue`.++```html title="src/components/Account.vue"+<script setup>import { supabase } from '../supabase'+ import { onMounted, ref, toRefs } from 'vue'- export default {- setup() {- const loading = ref(false)- const email = ref('')-- const handleLogin = async () => {- try {- loading.value = true- const { error } = await supabase.auth.signIn({ email: email.value })- if (error) throw error- alert('Check your email for the login link!')- } catch (error) {- alert(error.error_description || error.message)- } finally {- loading.value = false- }- }+ const props = defineProps(['session'])+ const { session } = toRefs(props)- return {- loading,- email,- handleLogin,- }- },- }-</script>-```+ const loading = ref(true)+ const username = ref('')+ const website = ref('')+ const avatar_url = ref('')-### User store+ onMounted(() => {+ getProfile()+ })-To access the user information in other places, we use a reactive store. Create a new file called `store.js` and utilize Vue 3 `reactive` functionalities.+ async function getProfile() {+ try {+ loading.value = true+ const { user } = session.value-```javascript title="src/store.js"-import { reactive } from 'vue'+ let { data, error, status } = await supabase+ .from('profiles')+ .select(`username, website, avatar_url`)+ .eq('id', user.id)+ .single()-export const store = reactive({- user: {},-})-```+ if (error && status !== 406) throw error-### Account page+ if (data) {+ username.value = data.username+ website.value = data.website+ avatar_url.value = data.avatar_url+ }+ } catch (error) {+ alert(error.message)+ } finally {+ loading.value = false+ }+ }-After a user is signed in we can allow them to edit their profile details and manage their account.-Let's create a new component for that called `Profile.vue`.+ async function updateProfile() {+ try {+ loading.value = true+ const { user } = session.value++ const updates = {+ id: user.id,+ username: username.value,+ website: website.value,+ avatar_url: avatar_url.value,+ updated_at: new Date(),+ }++ let { error } = await supabase.from('profiles').upsert(updates)++ if (error) throw error+ } catch (error) {+ alert(error.message)+ } finally {+ loading.value = false+ }+ }++ async function signOut() {+ try {+ loading.value = true+ let { error } = await supabase.auth.signOut()+ if (error) throw error+ } catch (error) {+ alert(error.message)+ } finally {+ loading.value = false+ }+ }+</script>-```html title="src/components/Profile.vue"<template><form class="form-widget" @submit.prevent="updateProfile"><div><label for="email">Email</label>- <input id="email" type="text" :value="store.user.email" disabled />+ <input id="email" type="text" :value="session.user.email" disabled /></div><div><label for="username">Name</label>@@ -291,140 +231,44 @@ Let's create a new component for that called `Profile.vue`.</div><div>- <button class="button block" @click="signOut" :disabled="loading">Sign Out</button>+ <button class="button block" @click="signOut" :disabled="loading">+ Sign Out+ </button></div></form></template>+```-<script>- import { supabase } from '../supabase'- import { store } from '../store'- import { onMounted, ref } from 'vue'-- export default {- setup() {- const loading = ref(true)- const username = ref('')- const website = ref('')- const avatar_url = ref('')-- async function getProfile() {- try {- loading.value = true- store.user = supabase.auth.user()-- let { data, error, status } = await supabase- .from('profiles')- .select(`username, website, avatar_url`)- .eq('id', store.user.id)- .single()-- if (error && status !== 406) throw error-- if (data) {- username.value = data.username- website.value = data.website- avatar_url.value = data.avatar_url- }- } catch (error) {- alert(error.message)- } finally {- loading.value = false- }- }+### Launch!- async function updateProfile() {- try {- loading.value = true- store.user = supabase.auth.user()-- const updates = {- id: store.user.id,- username: username.value,- website: website.value,- avatar_url: avatar_url.value,- updated_at: new Date(),- }-- let { error } = await supabase.from('profiles').upsert(updates, {- returning: 'minimal', // Don't return the value after inserting- })-- if (error) throw error- } catch (error) {- alert(error.message)- } finally {- loading.value = false- }- }+Now that we have all the components in place, let's update `App.vue`:- async function signOut() {- try {- loading.value = true- let { error } = await supabase.auth.signOut()- if (error) throw error- } catch (error) {- alert(error.message)- } finally {- loading.value = false- }- }+```html title="src/App.vue"+<script setup>+ import { onMounted, ref } from 'vue'+ import Account from './components/Account.vue'+ import Auth from './components/Auth.vue'+ import { supabase } from './supabase'- onMounted(() => {- getProfile()- })+ const session = ref()- return {- store,- loading,- username,- website,- avatar_url,+ onMounted(() => {+ supabase.auth.getSession().then(({ data }) => {+ session.value = data.session+ })- updateProfile,- signOut,- }- },- }+ supabase.auth.onAuthStateChange((_, _session) => {+ session.value = _session+ })+ })</script>-```--### Launch!--Now that we have all the components in place, let's update `App.vue`:-```html title="src/App.vue"<template><div class="container" style="padding: 50px 0 100px 0">- <Profile v-if="store.user" />+ <Account v-if="session" :session="session" /><Auth v-else /></div></template>--<script>- import { store } from './store'- import { supabase } from './supabase'- import Auth from './components/Auth.vue'- import Profile from './components/Profile.vue'-- export default {- components: {- Auth,- Profile,- },-- setup() {- store.user = supabase.auth.user()- supabase.auth.onAuthStateChange((_, session) => {- store.user = session.user- })-- return {- store,- }- },- }-</script>```Once that's done, run this in a terminal window:@@ -433,9 +277,9 @@ Once that's done, run this in a terminal window:npm run dev```-And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.+And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.-+## Bonus: Profile photos@@ -446,6 +290,61 @@ Every Supabase project is configured with [Storage](/docs/guides/storage) for maLet's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:```html title="src/components/Avatar.vue"+<script setup>+ import { ref, toRefs, watch } from 'vue'+ import { supabase } from '../supabase'++ const prop = defineProps(['path', 'size'])+ const { path, size } = toRefs(prop)++ const emit = defineEmits(['upload', 'update:path'])+ const uploading = ref(false)+ const src = ref('')+ const files = ref()++ const downloadImage = async () => {+ try {+ const { data, error } = await supabase.storage+ .from('avatars')+ .download(path.value)+ if (error) throw error+ src.value = URL.createObjectURL(data)+ } catch (error) {+ console.error('Error downloading image: ', error.message)+ }+ }++ const uploadAvatar = async (evt) => {+ files.value = evt.target.files+ try {+ uploading.value = true+ if (!files.value || files.value.length === 0) {+ throw new Error('You must select an image to upload.')+ }++ const file = files.value[0]+ const fileExt = file.name.split('.').pop()+ const filePath = `${Math.random()}.${fileExt}`++ let { error: uploadError } = await supabase.storage+ .from('avatars')+ .upload(filePath, file)++ if (uploadError) throw uploadError+ emit('update:path', filePath)+ emit('upload')+ } catch (error) {+ alert(error.message)+ } finally {+ uploading.value = false+ }+ }++ watch(path, () => {+ if (path.value) downloadImage()+ })+</script>+<template><div><img@@ -453,11 +352,15 @@ Let's create an avatar for the user so that they can upload a profile photo. We:src="src"alt="Avatar"class="avatar image"- :style="{ height: size, width: size }"+ :style="{ height: size + 'em', width: size + 'em' }"+ />+ <div+ v-else+ class="avatar no-image"+ :style="{ height: size + 'em', width: size + 'em' }"/>- <div v-else class="avatar no-image" :style="{ height: size, width: size }" />- <div :style="{ width: size }">+ <div :style="{ width: size + 'em' }"><label class="button primary block" for="single">{{ uploading ? "Uploading ..." : "Upload" }}</label>@@ -466,100 +369,32 @@ Let's create an avatar for the user so that they can upload a profile photo. Wetype="file"id="single"accept="image/*"- @change="uploadAvatar($event)"+ @change="uploadAvatar":disabled="uploading"/></div></div></template>--<script>- import { ref, toRefs, watch } from 'vue'- import { supabase } from '../supabase'-- export default {- props: {- path: String,- },- emits: ['upload', 'update:path'],- setup(prop, { emit }) {- const { path } = toRefs(prop)- const size = ref('10em')- const uploading = ref(false)- const src = ref('')- const files = ref()-- const downloadImage = async () => {- try {- const { data, error } = await supabase.storage.from('avatars').download(path.value)- if (error) throw error- src.value = URL.createObjectURL(data)- } catch (error) {- console.error('Error downloading image: ', error.message)- }- }-- const uploadAvatar = async (evt) => {- files.value = evt.target.files- try {- uploading.value = true- if (!files.value || files.value.length === 0) {- throw new Error('You must select an image to upload.')- }-- const file = files.value[0]- const fileExt = file.name.split('.').pop()- const fileName = `${Math.random()}.${fileExt}`- const filePath = `${fileName}`-- let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)-- if (uploadError) throw uploadError- emit('update:path', filePath)- emit('upload')- } catch (error) {- alert(error.message)- } finally {- uploading.value = false- }- }-- watch(path, () => {- path.value ? downloadImage() : ''- })-- return {- path,- size,- uploading,- src,- files,-- uploadAvatar,- }- },- }-</script>```### Add the new widgetAnd then we can add the widget to the Account page:-```html title="src/Profile.vue"+```html title="src/components/Account.vue"+<script>+ // Import the new component+ import Avatar from './Avatar.vue'+</script>+<template><form class="form-widget" @submit.prevent="updateProfile"><!-- Add to body -->- <Avatar v-model:path="avatar_url" @upload="updateProfile" />+ <Avatar v-model:path="avatar_url" @upload="updateProfile" size="10" /><!-- Other form elements --></form></template>--<script>- // Import the new component- import Avatar from './Avatar.vue'-</script>```## Next steps