diff --git a/.github/workflows/avoid-typos.yml b/.github/workflows/avoid-typos.yml
index 1cbe64238ac..68a17b5ba32 100644
--- a/.github/workflows/avoid-typos.yml
+++ b/.github/workflows/avoid-typos.yml
@@ -17,4 +17,8 @@ jobs:
locale: "US"
reporter: github-pr-review
level: error
- exclude: "*.css"
+ exclude: |
+ "*.css"
+ "**/package.json"
+ "**/package-lock.json"
+ ".git/*"
diff --git a/.gitignore b/.gitignore
index c67a911193a..c78e6a2eb47 100644
--- a/.gitignore
+++ b/.gitignore
@@ -121,3 +121,6 @@ typings/
**/supabase/.temp
apps/new-docs/*
+
+# For self-hosted logs: https://github.com/supabase/supabase/blob/86e3ab20abfdb9c3e666334d3d2f8efeef9ccf2c/docker/docker-compose-logging.yml#L101
+gcloud.json
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
index 5487e76808a..e88f3cb89f0 100644
--- a/DEVELOPERS.md
+++ b/DEVELOPERS.md
@@ -28,7 +28,7 @@ You need to install and configure the following dependencies on your machine to
- [Git](http://git-scm.com/)
- [Node.js v16.x (LTS)](http://nodejs.org)
-- [npm](https://www.npmjs.com/) version 7+ or [Yarn](https://yarnpkg.com/)
+- [npm](https://www.npmjs.com/) version 8.x.x or [Yarn](https://yarnpkg.com/)
## Local development
diff --git a/README.md b/README.md
index fcf1cfe5aba..f3506927e0a 100644
--- a/README.md
+++ b/README.md
@@ -13,8 +13,8 @@
- [x] Authentication and Authorization. [Docs](https://supabase.com/docs/guides/auth)
- [x] Auto-generated APIs.
- [x] REST. [Docs](https://supabase.com/docs/guides/database/api#rest-api)
+ - [x] GraphQL. [Docs](https://supabase.com/docs/guides/database/api#graphql-api)
- [x] Realtime subscriptions. [Docs](https://supabase.com/docs/guides/database/api#realtime-api)
- - [x] GraphQL (Beta). [Docs](https://supabase.com/docs/guides/database/api#graphql-api)
- [x] Functions.
- [x] Database Functions. [Docs](https://supabase.com/docs/guides/database/functions)
- [x] Edge Functions [Docs](https://supabase.com/docs/guides/functions)
@@ -63,6 +63,7 @@ You can also [self-host](https://supabase.com/docs/guides/hosting/overview) and
- [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. Realtime polls Postgres' built-in replication functionality for database changes, converts changes to JSON, then broadcasts the JSON over websockets to authorized clients.
- [PostgREST](http://postgrest.org/) is a web server that turns your PostgreSQL database directly into a RESTful API
+- [pg_graphql](http://github.com/supabase/pg_graphql/) a PostgreSQL extension that exposes a GraphQL API
- [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.
diff --git a/apps/docs/components/Favicons.tsx b/apps/docs/components/Favicons.tsx
index 5c65346f0fa..1e9ddafffe1 100644
--- a/apps/docs/components/Favicons.tsx
+++ b/apps/docs/components/Favicons.tsx
@@ -5,32 +5,46 @@ const Favicons = () => {
const { basePath } = useRouter()
return (
-
-
-
-
- {/* */}
-
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
+ {/* prettier-ignore */}
+
-
+
+
+
+
+
-
+
-
+ {/* misc */}
+
+
+
)
}
diff --git a/apps/docs/components/JwtGenerator.js b/apps/docs/components/JwtGenerator.js
index 4ac1b05e255..d0dc7a7bf08 100644
--- a/apps/docs/components/JwtGenerator.js
+++ b/apps/docs/components/JwtGenerator.js
@@ -1,7 +1,6 @@
import React, { useState } from 'react'
import KJUR from 'jsrsasign'
-import CodeBlock from './CodeBlock/CodeBlock'
-import { Button, Select, Input } from 'ui'
+import { Button, Select, Input, CodeBlock } from 'ui'
const JWT_HEADER = { alg: 'HS256', typ: 'JWT' }
const now = new Date()
diff --git a/apps/docs/components/Navigation/AlgoliaSearch.tsx b/apps/docs/components/Navigation/AlgoliaSearch.tsx
deleted file mode 100644
index eeb954f037a..00000000000
--- a/apps/docs/components/Navigation/AlgoliaSearch.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import { render } from 'react-dom'
-import { IconCommand } from 'ui'
-import { createElement, FC, useEffect, useRef, Fragment } from 'react'
-import algoliasearch from 'algoliasearch/lite'
-import { autocomplete, getAlgoliaResults } from '@algolia/autocomplete-js'
-import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches'
-import { useRouter } from 'next/router'
-
-// [Joshen] We're currently using DocSearch from Algolia as it provides a nice
-// UI out of the box + some good preconfigured search settings (e.g hierarchy).
-// However, we're using our own Algolia account to store the records in the indexes
-// (rather than going through the DocSearch program from Algolia where they'll crawl
-// our site for us). Refer to scripts/build-search on how we're saving the records.
-
-// Using Algolia's autocomplete library gives us full flexbility in terms of customizing
-// our search experience, but that will take time to figure out. Hence why for now we're just
-// using DocSearch with our own records.
-
-// Potentially for search, we could
-// - Go ahead with the DocSearch program and let them crawl our site to generate the records
-// - But we need to ensure that our site is semantically correct first
-// - Use Algolia itself to flesh out our own search logic
-// - The basics are already set up to be honest, but will take time to make it great
-// - Go back to Typesense if we deem that Algolia is not helpful in the long run
-
-const searchClient = algoliasearch(
- process.env.NEXT_PUBLIC_ALGOLIA_APP_ID,
- process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY
-)
-
-// [Joshen] Not working properly, but lets not get stuck on this
-// Priority just to get a search working
-const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
- key: 'docs-search',
- limit: 3,
- //@ts-ignore
- transformSource({ source }) {
- return {
- ...source,
- templates: {
- ...source.templates,
- header({ state }) {
- if (state.query) return null
- return (
-
- Your searches
-
-
- )
- },
- },
- }
- },
-})
-
-interface Props {}
-
-const AlgoliaSearch: FC = ({}) => {
- const searchRef = useRef(null)
- const router = useRouter()
-
- useEffect(() => {
- if (!searchRef.current) {
- return undefined
- }
- const search = autocomplete({
- openOnFocus: true,
- container: searchRef.current,
- defaultActiveItemId: 0,
- detachedMediaQuery: '',
- // @ts-ignore
- renderer: { createElement, Fragment, render },
- placeholder: 'Search docs',
- plugins: [recentSearchesPlugin],
- renderNoResults({ state, render }, root) {
- render(
-
diff --git a/apps/docs/components/reference/RefFunctionSection.tsx b/apps/docs/components/reference/RefFunctionSection.tsx
index 8b228a6bfa6..ddb35ba930b 100644
--- a/apps/docs/components/reference/RefFunctionSection.tsx
+++ b/apps/docs/components/reference/RefFunctionSection.tsx
@@ -1,7 +1,6 @@
import ReactMarkdown from 'react-markdown'
-import { IconDatabase, Tabs } from 'ui'
-import CodeBlock from '~/components/CodeBlock/CodeBlock'
+import { CodeBlock, IconDatabase, Tabs } from 'ui'
import Options from '~/components/Options'
import Param from '~/components/Params'
diff --git a/apps/docs/data/nav/supabase-js/v2.ts b/apps/docs/data/nav/supabase-js/v2.ts
index 13925dc1d85..f71236ae3aa 100644
--- a/apps/docs/data/nav/supabase-js/v2.ts
+++ b/apps/docs/data/nav/supabase-js/v2.ts
@@ -160,6 +160,11 @@ const Nav = [
url: '/reference/javascript/storage-from-createsignedurls',
items: [],
},
+ {
+ name: 'from.createSignedUploadUrl()',
+ url: '/reference/javascript/storage-from-createsigneduploadurl',
+ items: [],
+ },
{
name: 'from.getPublicUrl()',
url: '/reference/javascript/storage-from-getpublicurl',
diff --git a/apps/docs/docs/ref/python/introduction.mdx b/apps/docs/docs/ref/python/introduction.mdx
index cf0a9f0ee4f..cecb5e86669 100644
--- a/apps/docs/docs/ref/python/introduction.mdx
+++ b/apps/docs/docs/ref/python/introduction.mdx
@@ -19,3 +19,14 @@ hideTitle: true
changes, invoke Deno Edge Functions, build login and user management functionality, and manage
large files.
+
+
+
The Python client library is created and maintained by the Supabase community, and is not an official library. Please be tolerant of areas where the library is still being developed, and — as with all the libraries — feel free to contribute wherever you find issues.
+
+
+ Huge thanks to official maintainers, [anand2312](https://github.com/anand2312/), [dreinon](https://github.com/dreinon), [J0](https://github.com/j0), and [Leynier](https://github.com/leynier).
+
+
+ Shoutout to [timkpaine](https://github.com/timkpaine) for maintaining our Conda libraries as well.
+
+
+
+
+
+The Supabase Analytics server is a Logflare self-hostable instance that manages the ingestion and query pipelines for searching and aggregating structured analytics events.
+
+When self-hosting the Analytics server, the full logging experience matching that of the Supabase Platform is available in the Studio instance, allowing for an integrated and enhanced development experience.
+However, it's important to note that certain [differences](#differences) may arise due to the platform's infrastructure.
+
+
+ All logflare technical docs are available at
+ [https://docs.logflare.app](https://docs.logflare.app)
+
+
+## Getting Started
+
+### Pre-requisites
+
+Logflare currently requires BigQuery usage. You will need to create a Google Cloud project with billing enabled.
+
+The requirements are as follows after creating the project:
+
+- Project ID
+- Project number
+- A service account key
+
+#### Setting up BigQuery Service Account
+
+To ensure that you have sufficient permissions to insert into your Google Cloud BigQuery, ensure that you have created a service account with either:
+
+- BigQuery Admin role; or
+- The following permissions:
+ - bigquery.datasets.create
+ - bigquery.datasets.get
+ - bigquery.datasets.getIamPolicy
+ - bigquery.datasets.update
+ - bigquery.jobs.create
+ - bigquery.routines.create
+ - bigquery.routines.update
+ - bigquery.tables.create
+ - bigquery.tables.delete
+ - bigquery.tables.get
+ - bigquery.tables.getData
+ - bigquery.tables.update
+ - bigquery.tables.updateData
+
+You can create the service account via the web console or `gcloud`, as per the [Google Cloud documentation](https://cloud.google.com/iam/docs/keys-create-delete). In the web console, you can create the key by navigating to IAM > Service Accounts > Actions (dropdown) > Manage Keys
+
+We recommend setting the BigQuery Admin role, as it simplifies permissions setup.
+
+#### Downloading the Service Account key
+
+After the service account is created, you will need to create a key for the service account. This key will sign the JWTs for API requests that the Analytics server makes with BigQuery.
+
+### Docker Compose
+
+Using the example [self-hosting stack based on docker-compose](https://github.com/supabase/supabase/tree/master/docker), you include the logging related services using the following command
+
+You will first need to update the `.env.example` file with the necessary environment variables.
+
+- `GOOGLE_PROJECT_ID`
+- `GOOGLE_PROJECT_NUMBER`
+
+You will need to place your Service Account key in your present working directory with the filename `gcloud.json`.
+
+Thereafter, you can run the docker-compose commands and include the logging-specific compose file.
+
+```bash
+# assuming you clone the supabase/supabase repo.
+cd docker
+docker compose -f docker-compose.yml -f docker-compose-logging.yml up
+```
+
+This would include two additional docker services to your compose stack: Logflare and Vector.
+
+
+ Read more about [self-hosting Logflare](https://docs.logflare.app/self-hosting) as your analytics
+ server.
+
+
+#### Vector Usage
+
+In the Docker Compose example, we utilize vector to coordinate the logging pipeline between the services. However, if you peer into the [vector configuration file](https://github.com/supabase/supabase/blob/master/docker/volumes/logs/vector.yml), you will be able to see that Vector sends logs to the Analytics ingestion endpoint.
+
+If you need to customize the logging pipeline for your own needs, you must ensure that the payloads matches the expected event schema structure. Without the correct structure, it would cause the Studio Logs UI features to break.
+
+### Standalone Docker Container
+
+If desired, you can utilize the standalone docker-container. Please refer to the [docker-compose file](https://github.com/supabase/supabase/tree/master/docker/docker-compose-logging.yml) for required docker configuration.
+
+Additional supplementary technical documentation on self-hosting and using the `supabase/logflare` image for a full Logflare experience is available at the [official Logflare documentation](https://docs.logflare.app/self-hosting/).
+
+## Differences
+
+API logs rely on Kong instead of the Supabase Cloud API Gateway. Logs from Kong are not enriched with platform-only data.
+
+Within the self-hosted setup, all logs are routed to Logflare via Vector. As Kong routes API requests to PostgREST, self-hosted or local deployments will result in Kong request logs instead.
+This would result in differences in the log event metadata between self-hosted API requests and Supabase Platform requests.
+
+## BigQuery
+
+All log event data is stored in and queried from BigQuery. To use the Analytics server with Supabase you'll need a Google Cloud Platform account for access to BigQuery.
+
+Make sure to set the `GOOGLE_DATASET_ID_APPEND`, `GOOGLE_PROJECT_ID` and `GOOGLE_PROJECT_NUMBER` environment variables.
+
+Download your Google Cloud API JWT and store it under gcloud.json in your working directory.
+
+
+ You must also enable billing on your Google Cloud project, as the streaming inserts feature is
+ required.
+
+
+## Production Recommendations
+
+To self-host in a production setting, we recommend performing the following for a better experience.
+
+### Ensure that Logflare is behind a firewall and restrict all network access to it besides safe requests.
+
+Self-hosted Logflare has UI authentication disabled and is intended for exposure to the internet. We recommend restricting access to the dashboard, accessible at the `/dashboard` path.
+If dashboard access is required for managing sources, we recommend having an authentication layer, such as a VPN.
+
+### Use a different Postgres Database to store Logflare data.
+
+Logflare requires a Postgres database to function. However, if there is an issue with you self-hosted Postgres service, you would not be able to debug it as it would also bring Logflare down together.
+
+The self-hosted example is only used as a minimal example on running the entire stack, however it is not recommended to use the same database server for both production and observability.
+
+
+
+
+
+ ### Client libraries
+
+ - [JavaScript - Pino Transport](https://github.com/Logflare/pino-logflare)
+ - [Elixir](https://github.com/Logflare/logflare_api_client)
+ - [Elixir - Logger Backend](https://github.com/Logflare/logflare_logger_backend)
+ - [Erlang](https://github.com/Logflare/logflare_erl)
+ - [Erlang - Lager Backend](https://github.com/Logflare/logflare_lager_backend)
+ - [Cloudflare Worker](https://gist.github.com/chasers/c7a220e91820a1084b27fcfdb18ad6bd)
+
+ ### Integrations
+
+ - [Fly - Logs](https://github.com/Logflare/fly-log-shipper)
+ - [Vercel Integration - Logs](https://vercel.com/integrations/logflare)
+ - [Cloudflare App - Logs](https://www.cloudflare.com/apps/logflare/install)
+
+ ### Additional links
+
+ - [Source code](https://github.com/logflare/logflare)
+ - [OpenAPI docs](https://logflare.app/api/openapi)
+ - [Supabase Acquires Logflare](https://supabase.com/blog/supabase-acquires-logflare)
+ - [Logflare self-hosting docs](https://docs.logflare.app/self-hosting)
+
+
+
+
diff --git a/apps/docs/docs/ref/swift/introduction.mdx b/apps/docs/docs/ref/swift/introduction.mdx
new file mode 100644
index 00000000000..80dc3584bd1
--- /dev/null
+++ b/apps/docs/docs/ref/swift/introduction.mdx
@@ -0,0 +1,29 @@
+---
+id: introduction
+title: Introduction
+hideTitle: true
+---
+
+
+
+
+
Swift Client Library
+
@supabase-community/supabase-swift
+
+
+
+
+This reference documents every object and method available in Supabase's Swift library, [supabase-swift](https://github.com/supabase-community/supabase-swift). You can use supabase-swift to interact with your Postgres database, listen to database changes, invoke Deno Edge Functions, build login and user management functionality, and manage large files.
+
+We also provide a [supabase](https://pub.dev/packages/supabase) package for non-Swift projects.
+
+
+
+
The Swift client library is created and maintained by the Supabase community, and is not an official library. Please be tolerant of areas where the library is still being developed, and — as with all the libraries — feel free to contribute wherever you find issues.
+
+
+ Huge thanks to official maintainer, [Maail](https://github.com/maail).
+
+
+
+
diff --git a/apps/docs/generator/helpers.ts b/apps/docs/generator/helpers.ts
index 6bb5653e808..e7796c9101f 100644
--- a/apps/docs/generator/helpers.ts
+++ b/apps/docs/generator/helpers.ts
@@ -2,6 +2,7 @@ import * as _ from 'lodash'
import * as fs from 'fs'
export const slugify = (text: string) => {
+ if (!text) return ''
return text
.toString()
.toLowerCase()
diff --git a/apps/docs/layouts/SiteLayout.tsx b/apps/docs/layouts/SiteLayout.tsx
index d8966e5d668..0af5320a944 100644
--- a/apps/docs/layouts/SiteLayout.tsx
+++ b/apps/docs/layouts/SiteLayout.tsx
@@ -22,6 +22,10 @@ const levelsData = {
icon: '/docs/img/icons/menu/database',
name: 'Database',
},
+ api: {
+ icon: '/docs/img/icons/menu/database',
+ name: 'Serverless APIs',
+ },
auth: {
icon: '/docs/img/icons/menu/auth',
name: 'Auth',
@@ -34,6 +38,10 @@ const levelsData = {
icon: '/docs/img/icons/menu/realtime',
name: 'Realtime',
},
+ analytics: {
+ icon: '/docs/img/icons/menu/analytics',
+ name: 'Analytics',
+ },
storage: {
icon: '/docs/img/icons/menu/storage',
name: 'Storage',
@@ -82,6 +90,10 @@ const levelsData = {
icon: '/docs/img/icons/menu/reference-python',
name: 'Python Reference v2.0',
},
+ reference_swift_v1: {
+ icon: '/docs/img/icons/menu/reference-swift',
+ name: 'Swift Reference v1.0',
+ },
reference_cli: {
icon: '/docs/img/icons/menu/reference-cli',
name: 'CLI Reference',
@@ -102,6 +114,10 @@ const levelsData = {
icon: '/docs/img/icons/menu/reference-realtime',
name: 'Realtime Server Reference',
},
+ reference_self_hosting_analytics: {
+ icon: '/docs/img/icons/menu/reference-analytics',
+ name: 'Analytics Server Reference',
+ },
}
const MobileHeader = memo(function MobileHeader() {
@@ -298,20 +314,6 @@ const NavContainer = memo(function NavContainer() {
})
const SiteLayout = ({ children }) => {
- // const mobileMenuOpen = useMenuMobileOpen()
-
- useEffect(() => {
- const key = localStorage.getItem('supabaseDarkMode')
- if (!key) {
- // Default to dark mode if no preference config
- document.documentElement.className = 'dark'
- document.documentElement.style.colorScheme = 'dark'
- } else {
- document.documentElement.className = key === 'true' ? 'dark' : ''
- document.documentElement.style.colorScheme = key === 'true' ? 'dark' : ''
- }
- }, [])
-
return (
<>
diff --git a/apps/docs/layouts/tutorials/TutorialLayout.tsx b/apps/docs/layouts/tutorials/TutorialLayout.tsx
index 2f58a612cca..ba3ffe68f6e 100644
--- a/apps/docs/layouts/tutorials/TutorialLayout.tsx
+++ b/apps/docs/layouts/tutorials/TutorialLayout.tsx
@@ -14,19 +14,8 @@ interface Props {
}
const Layout: FC = (props: Props) => {
- // const contentString = renderToString(props.children)
const [active, setActive] = useState(false)
- useEffect(() => {
- const key = localStorage.getItem('supabaseDarkMode')
- if (!key) {
- // Default to dark mode if no preference config
- document.documentElement.className = 'dark'
- } else {
- document.documentElement.className = key === 'true' ? 'dark' : ''
- }
- }, [])
-
useEffect(() => {
setTimeout(function () {
setActive(true)
diff --git a/apps/docs/lib/docs.ts b/apps/docs/lib/docs.ts
index daa0f83d6bd..2ae4f8dfe80 100644
--- a/apps/docs/lib/docs.ts
+++ b/apps/docs/lib/docs.ts
@@ -2,7 +2,7 @@ import fs from 'fs'
import { join } from 'path'
import matter from 'gray-matter'
import nonGeneratedReferencePages from 'data/nonGeneratedReferencePages'
-import { REFERENCES } from 'components/Navigation/Navigation.constants'
+import { REFERENCES } from '~/components/Navigation/NavigationMenu/NavigationMenu.constants'
const docsDirectory = process.cwd()
diff --git a/apps/docs/lib/mdx/getConfig.tsx b/apps/docs/lib/mdx/getConfig.tsx
index 8a014486212..d208d4243cc 100644
--- a/apps/docs/lib/mdx/getConfig.tsx
+++ b/apps/docs/lib/mdx/getConfig.tsx
@@ -4,6 +4,8 @@ import specStorageV0 from '~/../../spec/storage_v0_config.yaml' assert { type: '
import specRealtimeV0 from '~/../../spec/realtime_v0_config.yaml' assert { type: 'yml' }
// @ts-expect-error
import specAuthV1 from '~/../../spec/gotrue_v1_config.yaml' assert { type: 'yml' }
+// @ts-expect-error
+import specAnalyticsV0 from '~/../../spec/analytics_v0_config.yaml' assert { type: 'yml' }
function getStorageConfigV0() {
return { ...specStorageV0 }
@@ -17,4 +19,8 @@ function getAuthConfigV1() {
return { ...specAuthV1 }
}
-export { getStorageConfigV0, getRealtimeConfigV0, getAuthConfigV1 }
+function getAnalyticsConfigV0() {
+ return { ...specAnalyticsV0 }
+}
+
+export { getStorageConfigV0, getRealtimeConfigV0, getAuthConfigV1, getAnalyticsConfigV0 }
diff --git a/apps/docs/lib/refGenerator/helpers.ts b/apps/docs/lib/refGenerator/helpers.ts
index 83864fa5540..3325d45786f 100644
--- a/apps/docs/lib/refGenerator/helpers.ts
+++ b/apps/docs/lib/refGenerator/helpers.ts
@@ -267,6 +267,7 @@ export function gen_v3(spec: OpenAPIV3.Document, dest: string, { apiUrl }: { api
}
const slugify = (text: string) => {
+ if (!text) return ''
return text
.toString()
.toLowerCase()
diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjs
index 777b2e2224a..b3c71cae82e 100644
--- a/apps/docs/next.config.mjs
+++ b/apps/docs/next.config.mjs
@@ -80,6 +80,16 @@ const nextConfig = {
},
]
},
+ async redirects() {
+ return [
+ {
+ source: '/',
+ destination: '/docs',
+ basePath: false,
+ permanent: false,
+ },
+ ]
+ },
}
// next.config.js
diff --git a/apps/docs/package.json b/apps/docs/package.json
index f8fd026c549..cfda86a3831 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -35,7 +35,10 @@
"gen:supabase-js:v2": "npm-run-all gen:supabase-js:v2:ref",
"gen:supabase-js:v2:ref": "ts-node ./generator/index.ts gen --type legacy --input ../../spec/supabase_js_v2.yml --output ./docs/reference/javascript/generated",
"gen:realtime": "npm-run-all gen:realtime:config",
- "gen:realtime:config": "ts-node ./generator/index.ts gen --type config --input ../../spec/realtime_v0_config.yaml --output ./docs/reference/realtime/generated/config.mdx"
+ "gen:realtime:config": "ts-node ./generator/index.ts gen --type config --input ../../spec/realtime_v0_config.yaml --output ./docs/reference/realtime/generated/config.mdx",
+ "gen:analytics": "npm-run-all gen:analytics:config gen:analytics:usage",
+ "gen:analytics:config": "ts-node ./generator/index.ts gen --type config --input ../../spec/analytics_v0_config.yaml --output ./docs/reference/analytics/generated/config.mdx",
+ "gen:analytics:usage": "ts-node ./generator/index.ts gen --type api --input ../../spec/transforms/analytics_v0_openapi_deparsed.json --output ./docs/reference/analytics/generated/usage.mdx"
},
"dependencies": {
"@algolia/autocomplete-js": "^1.7.2",
@@ -45,9 +48,9 @@
"@mdx-js/react": "^1.6.22",
"@next/mdx": "^12.0.4",
"@radix-ui/react-accordion": "^1.0.1",
- "@supabase/auth-helpers-nextjs": "^0.5.4",
+ "@supabase/auth-helpers-nextjs": "^0.5.6",
"@supabase/auth-helpers-react": "^0.3.1",
- "@supabase/supabase-js": "^2.8.0",
+ "@supabase/supabase-js": "^2.13.0",
"algoliasearch": "^4.14.2",
"babel": "^6.23.0",
"clsx": "^1.2.1",
@@ -65,6 +68,7 @@
"mdast-util-to-markdown": "^1.5.0",
"mdast-util-to-string": "^3.1.1",
"mdx-mermaid": "2.0.0-rc3",
+ "mermaid": "^10.0.2",
"micromark-extension-mdxjs": "^1.0.0",
"next": "12.3.2",
"next-compose-plugins": "^2.2.1",
diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsx
index f3f6b65f63a..b8ebabf1003 100644
--- a/apps/docs/pages/_app.tsx
+++ b/apps/docs/pages/_app.tsx
@@ -1,19 +1,18 @@
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { SessionContextProvider } from '@supabase/auth-helpers-react'
-import { ThemeProvider } from 'common/Providers'
-import { DefaultSeo } from 'next-seo'
-import Head from 'next/head'
+import { AuthProvider, ThemeProvider } from 'common'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
+import ReactMarkdown from 'react-markdown'
+import remarkGfm from 'remark-gfm'
import { AppPropsWithLayout } from 'types'
+import { CommandMenuProvider } from 'ui'
+import components from '~/components'
import Favicons from '~/components/Favicons'
-import SearchProvider from '~/components/Search/SearchProvider'
import SiteLayout from '~/layouts/SiteLayout'
import { IS_PLATFORM, LOCAL_SUPABASE } from '~/lib/constants'
import { post } from '~/lib/fetchWrappers'
-import '../styles/algolia-search.scss'
import '../styles/ch.scss'
-import '../styles/docsearch.scss'
import '../styles/main.scss?v=1.0.0'
import '../styles/new-docs.scss'
import '../styles/prism-okaidia.scss'
@@ -25,7 +24,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
IS_PLATFORM || LOCAL_SUPABASE ? createBrowserSupabaseClient() : undefined
)
- function telemetry(route: string) {
+ function handlePageTelemetry(route: string) {
return post(`https://api.supabase.io/platform/telemetry/page`, {
referrer: document.referrer,
title: document.title,
@@ -38,7 +37,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
/*
* handle telemetry
*/
- telemetry(url)
+ handlePageTelemetry(url)
/*
* handle "scroll to top" behaviour on route change
*/
@@ -60,30 +59,44 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
}
}, [router.events])
+ useEffect(() => {
+ /**
+ * Send page telemetry on first page load
+ */
+ if (router.isReady) {
+ handlePageTelemetry(router.route)
+ }
+ }, [router.isReady])
+
const SITE_TITLE = 'Supabase Documentation'
+ const AuthContainer = (props) => {
+ return IS_PLATFORM || LOCAL_SUPABASE ? (
+
+ {props.children}
+
+ ) : (
+ {props.children}
+ )
+ }
+
return (
<>
- {IS_PLATFORM || LOCAL_SUPABASE ? (
-
-
-
-
-
-
-
-
-
- ) : (
+
-
+ (
+
+ )}
+ >
-
+
- )}
+
>
)
}
diff --git a/apps/docs/pages/_document.tsx b/apps/docs/pages/_document.tsx
index ed9a8a70c10..67f89450efd 100644
--- a/apps/docs/pages/_document.tsx
+++ b/apps/docs/pages/_document.tsx
@@ -2,11 +2,11 @@ import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
-
+
-
+
diff --git a/apps/docs/pages/guides/api.mdx b/apps/docs/pages/guides/api.mdx
new file mode 100644
index 00000000000..3b518ced47b
--- /dev/null
+++ b/apps/docs/pages/guides/api.mdx
@@ -0,0 +1,75 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'api',
+ title: 'Serverless APIs',
+ description: 'Auto-generating and Realtime APIs.',
+ sidebar_label: 'Overview',
+ video: 'https://www.youtube.com/v/rPAJJFdtPw0',
+}
+
+Supabase auto-generates three types of API directly from your database schema.
+
+- REST - connect to your database through a restful interface, directly from the browser.
+- GraphQL - manipulate your database using a graph-like query language.
+- Realtime - listen to database changes.
+
+All the APIs are auto-generated from your database and are designed to get you building as fast as possible, without writing a single line of code.
+
+You can use them directly from the browser (two-tier architecture), or as a complement to your own API server (three-tier architecture).
+
+## Features
+
+- **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.
+
+## 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 at the URL `https://.supabase.co/rest/v1/`.
+
+The REST interface is automatically reflected from your database's schema and supports:
+- Basic CRUD operations (Create/Read/Update/Delete)
+- Arbitrarily deep relationships among tables/views, functions that return table types can also nest related tables/views.
+- Works with Postgres Views, Materialized Views and Foreign Tables
+- Works with Postgres Functions
+- User defined computed columns and computed relationships
+- Works with the Postgres security model - including Row Level Security, Roles, and Grants.
+
+The REST API resolves all requests to a single SQL statement leading to fast response times and high throughput.
+
+Reference:
+- [Docs](https://postgrest.org/)
+- [Source Code](https://github.com/PostgREST/postgrest)
+
+## GraphQL API [#graphql-api-overview]
+
+Supabase uses [pg_graphql](https://supabase.github.io/pg_graphql/) to expose a GraphQL API endpoint at `https://.supabase.co/graphql/v1/`.
+You can introspect and query the GraphQL API of an existing Supabase project within Studio [here](https://app.supabase.com/project/_/api/graphiql),
+or navigate there manually at `API Docs > GraphQL > GraphiQL`.
+
+The GraphQL interface is automatically reflected from your database's schema and supports:
+- Basic CRUD operations (Create/Read/Update/Delete)
+- Support for Tables, Views, Materialized Views, and Foreign Tables
+- Arbitrarily deep relationships among tables/views
+- User defined computed fields
+- The Postgres security model - including Row Level Security, Roles, and Grants.
+
+The GraphQL API resolves all requests in a single round-trip leading to fast response times and high throughput.
+
+Reference:
+- [Docs](https://supabase.github.io/pg_graphql/)
+- [Source Code](https://github.com/supabase/pg_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.
+Go to your project's [Replication section](https://app.supabase.com/project/_/database/replication) to get started.
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/api-keys.mdx b/apps/docs/pages/guides/api/api-keys.mdx
new file mode 100644
index 00000000000..3f9869586f5
--- /dev/null
+++ b/apps/docs/pages/guides/api/api-keys.mdx
@@ -0,0 +1,70 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'api-keys',
+ title: 'Understanding API Keys',
+ description: 'Securing your Serverless API with Postgres Row Level Security.',
+}
+
+Supabase provides two default keys when you create a project: an `anon` key, and a `service_role` key. You can find both keys in the [API Settings](https://app.supabase.com/project/_/settings/api).
+
+The Serverless APIs are designed to work with Postgres Row Level Security (RLS). These keys both map to Postgres roles. You can find an `anon` user and a `service_role` user in the [Roles](http://app.supabase.com/project/_/database/roles) section of the dashboard.
+
+The keys are both long-lived JWTs. If you decode these keys, you will see that they contain the "role", an "issued date", and an "expiry date" ~10 years in the future.
+
+```json
+{
+ "role": "anon",
+ "iat": 1625137684,
+ "exp": 1940713684
+}
+```
+
+## The `anon` key
+
+The `anon` key has very few privileges. You can use it in your [RLS policies](/docs/guides/auth/row-level-security) for "anonymous" access. For example, this policy will allow access to the `profiles` table:
+
+```sql
+create policy "Allow anonymous access" on profiles to anon for
+select
+ using (true);
+```
+
+And similarity for disallowing access:
+
+```sql
+create policy "Disallow anonymous access" on profiles to anon for
+select
+ using (false);
+```
+
+If you are using [Supabase Auth](/docs/guides/auth/overview), then the `anon` role will automatically update to `authenticated` once a user is logged in:
+
+```sql
+create policy "Allow access to authenticated users" on profiles to authenticated for
+select
+ using (true);
+```
+
+## The `service_role` key
+
+The "service_role" is a predefined Postgres role with elevated privileges, designed to perform various administrative and service-related tasks. It can bypass Row Level Security, so it should only be used on a private server.
+
+
+ Never expose the `service_role` key in a browser or anywhere where a user can see it.
+
+
+A common use case for the `service_role` key is running data analytics jobs on the backend. To support joins on user id, it is often useful to grant the service role read access to `auth.users` table.
+
+```sql
+grant
+select
+ on table auth.users to service_role;
+```
+
+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.
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/creating-routes.mdx b/apps/docs/pages/guides/api/creating-routes.mdx
new file mode 100644
index 00000000000..c48442f12d1
--- /dev/null
+++ b/apps/docs/pages/guides/api/creating-routes.mdx
@@ -0,0 +1,252 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'creating-routes',
+ title: 'Creating API Routes',
+ description:
+ 'API routes are automatically created when you create Postgres Tables, Views, or Functions.',
+}
+
+API routes are automatically created when you create Postgres Tables, Views, or Functions.
+
+## Create a table
+
+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.
+
+
+
+
+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**.
+
+
+
+
+
+
+```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)
+ );
+```
+
+
+
+
+## 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.
+
+
+
+The REST API and the GraphQL API are both accessible through this URL:
+
+- REST: `https://.supabase.co/rest/v1`
+- GraphQL: `https://.supabase.co/graphql/v1`
+
+Both of these routes require the `anon` key to be passed through an `apikey` header.
+
+## 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:
+
+
+
+
+```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('*')
+```
+
+
+
+
+```bash
+# Append /rest/v1/ to your URL, and then use the table name as the route
+curl '/rest/v1/todos' \
+-H "apikey: " \
+-H "Authorization: Bearer "
+```
+
+
+
+
+JS Reference: [select()](/docs/reference/javascript/select),
+[insert()](/docs/reference/javascript/insert),
+[update()](/docs/reference/javascript/update),
+[upsert()](/docs/reference/javascript/upsert),
+[delete()](/docs/reference/javascript/delete),
+[rpc()](/docs/reference/javascript/rpc) (call Postgres functions).
+
+### GraphQL API
+
+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/).
+
+
+
+
+```javascript
+import { createClient, useQuery } from 'urql'
+
+// Prepare API key and Authorization header
+const headers = {
+ apikey: ,
+ authorization: `Bearer ${}`,
+}
+
+// Create GraphQL client
+// See: https://formidable.com/open-source/urql/docs/basics/react-preact/#setting-up-the-client
+const client = createClient({
+ 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
+```
+
+
+
+
+```bash
+# Append /graphql/v1/ to your URL, and then use the table name as the route
+curl --request POST '/graphql/v1' \
+-H 'apikey: ' \
+-H 'Authorization: Bearer ' \
+-H 'Content-Type: application/json' \
+-d '{ "query":"{ todos(first: 3) { edges { node { id } } } }" }'
+```
+
+
+
+
+### Realtime API
+
+By default Realtime is disabled on your database. Let's turn on Realtime for the `todos` table.
+
+
+
+
+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.
+
+
+
+
+
+
+```sql
+alter
+ publication supabase_realtime add table todos;
+```
+
+
+
+
+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.
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/graphql/graphiql.mdx b/apps/docs/pages/guides/api/graphql/graphiql.mdx
new file mode 100644
index 00000000000..a3ce41073fd
--- /dev/null
+++ b/apps/docs/pages/guides/api/graphql/graphiql.mdx
@@ -0,0 +1,22 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'graphiql',
+ title: 'GraphiQL documentation',
+ description: 'Some docs on graphiql.',
+ video: 'https://www.youtube.com/v/7CqlTU9aOR4',
+}
+
+Every Supabase project has a GraphQL Endpoint: `https://.supabase.co/graphql/v1`.
+
+This endpoint 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.
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/joins-and-nesting.mdx b/apps/docs/pages/guides/api/joins-and-nesting.mdx
new file mode 100644
index 00000000000..470eba7a5aa
--- /dev/null
+++ b/apps/docs/pages/guides/api/joins-and-nesting.mdx
@@ -0,0 +1,206 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'joins-and-nested-tables',
+ title: 'Querying Joins and Nested tables',
+ description: 'The Serverless APIs automatically detect relationships between Postgres tables.',
+}
+
+The Serverless APIs automatically detect relationships between Postgres tables. Since Postgres is a relational database, this is a very common scenario.
+
+## One-to-many joins
+
+Let's use an example database that stores `countries` and `cities`:
+
+
+
+
+**Countries**
+
+| `id` | `name` |
+| ---- | -------------- |
+| 1 | United Kingdom |
+| 2 | United States |
+
+**Cities**
+
+| `id` | `name` | `country_id` |
+| ---- | ----------- | ------------ |
+| 1 | London | 1 |
+| 2 | Manchester | 1 |
+| 3 | Los Angeles | 2 |
+| 4 | New York | 2 |
+
+
+
+
+```sql
+create table
+ countries ("id" serial primary key, "name" text);
+
+insert into
+ countries (id, name)
+values
+ (1, 'United Kingdom'),
+ (2, 'United States');
+
+create table
+ cities (
+ "id" serial primary key,
+ "name" text,
+ "country_id" int references "countries"
+ );
+
+insert into
+ cities (name, country_id)
+values
+ ('London', 1),
+ ('Manchester', 1),
+ ('Los Angeles', 2),
+ ('New York', 2);
+```
+
+
+
+
+The APIs will automatically detect relationships based on the foreign keys:
+
+
+
+
+```js
+const { data, error } = await supabase.from('countries').select(`
+ id,
+ name,
+ cities ( id, name )
+`)
+```
+
+
+
+
+```dart
+final data = await supabase.from('todos').select('id, name, cities(id, name)');
+```
+
+
+
+
+```javascript
+const Query = `
+ query {
+ countriesCollection {
+ edges {
+ node {
+ id
+ name
+ cities {
+ id,
+ name
+ }
+ }
+ }
+ }
+ }
+`
+```
+
+
+
+
+```bash
+GET https://[REF].supabase.co/rest/v1/countries?select=id,name,cities(id,name)
+```
+
+
+
+
+## Many-to-many joins
+
+The Serverless APIs will detect many-to-many joins. For example, if you have a database which stored teams of users (where each user could below to many teams):
+
+```sql
+create table
+ users ("id" serial primary key, "name" text);
+
+create table
+ teams ("id" serial primary key, "team_name" text);
+
+create table
+ members (
+ "id" serial primary key,
+ "user_id" int references users,
+ "team_id" int references teams
+ );
+```
+
+In these cases you don't need to explicitly define the joining table (members). If we wanted to fetch all the teams and the members in each team:
+
+
+
+
+```js
+const { data, error } = await supabase.from('teams').select(`
+ id,
+ team_name,
+ users ( id, name )
+`)
+```
+
+
+
+
+```dart
+final data = await supabase.from('teams').select('id, team_name, users(id, name)');
+```
+
+
+
+
+```javascript
+const Query = `
+ query {
+ teamsCollection {
+ edges {
+ node {
+ id
+ team_name
+ users {
+ id,
+ name
+ }
+ }
+ }
+ }
+ }
+`
+```
+
+
+
+
+```bash
+GET https://[REF].supabase.co/rest/v1/teams?select=id,team_name,users(id,name)
+```
+
+
+
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/quickstart.mdx b/apps/docs/pages/guides/api/quickstart.mdx
new file mode 100644
index 00000000000..7d645a8b5f7
--- /dev/null
+++ b/apps/docs/pages/guides/api/quickstart.mdx
@@ -0,0 +1,236 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+import StepHikeCompact from '~/components/StepHikeCompact'
+
+export const meta = {
+ title: 'Build an API route in less than 2 minutes.',
+ subtitle: 'Create your first API route by creating a table called `todos` to store tasks.',
+ breadcrumb: 'API Quickstart',
+}
+
+Let's create our first REST route which we can query using `cURL` or the browser.
+
+We'll create a database table called `todos` for storing tasks. This creates a corresponding API route `/rest/v1/todos` which can accept `GET`, `POST`, `PATCH`, & `DELETE` requests.
+
+
+
+
+
+
+ [Create a new project](https://app.supabase.com) in the Supabase Dashboard.
+
+ After your project is ready, create a table in your Supabase database. You can do this with either the Table interface or the [SQL Editor](https://app.supabase.com/project/_/sql).
+
+
+
+
+
+
+
+
+ ```sql
+ -- Create a table called "todos"
+ -- with a column to store tasks.
+ create table todos (
+ id serial primary key,
+ task text
+ );
+ ```
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Let's turn on Row Level Security for this table and allow anonymous access.
+
+
+
+
+
+ ```sql
+ -- Turn on security
+ alter table "todos"
+ enable row level security;
+
+ -- Allow anonymous access
+ create policy "Allow anonymous access"
+ on todos
+ to anon
+ for select
+ using (true);
+ ```
+
+
+
+
+
+
+
+
+ Now we can add some data to our table which we can access through our API.
+
+
+
+
+
+ ```sql
+ insert into todos (task)
+ values
+ ('Create tables'),
+ ('Enable security'),
+ ('Add data'),
+ ('Fetch data from the API');
+ ```
+
+
+
+
+
+
+
+
+ Find your API URL and Keys in your Dashboard [API Settings](https://app.supabase.com/project/_/settings/api). You can now query your "todos" table by appending `/rest/v1/todos` to the API URL.
+
+ Copy this block of code, substitute `` and ``, then run it from a terminal.
+
+
+
+
+ ```bash Terminal
+ curl 'https://.supabase.co/rest/v1/todos' \
+ -H "apikey: " \
+ -H "Authorization: Bearer "
+ ```
+
+
+
+
+
+
+
+## Bonus
+
+There are several options for accessing your data:
+
+### Browser
+
+You can query the route in your browser, by appending the `anon` key as a query parameter:
+
+`https://.supabase.co/rest/v1/users?apikey=`
+
+### Client libraries
+
+We provide a numerous [Client Libraries](https://github.com/supabase/supabase#client-libraries).
+
+
+
+
+```js
+const { data, error } = await supabase.from('todos').select()
+```
+
+
+
+
+```dart
+final data = await supabase.from('todos').select('*');
+```
+
+
+
+
+```python
+response = supabase.table('todos').select("*").execute()
+```
+
+
+
+
+### GraphQL
+
+Every table can be accessed through the GraphQL API by switching `/rest/v1` with `/graphql/v1`.
+
+
+
+
+```javascript
+import { createClient, useQuery } from 'urql'
+
+const URL = '/graphql/v1'
+const ANON_KEY = ''
+
+// Prepare API key and Authorization header
+const headers = {
+ apikey: `${ANON_KEY}`,
+ authorization: `Bearer ${ANON_KEY}`,
+}
+
+const client = createClient({
+ url: URL,
+ fetchOptions: function createFetchOptions() {
+ return { headers }
+ },
+})
+
+// Prepare our GraphQL query
+const TodosQuery = `
+ query {
+ todosCollection {
+ edges {
+ node {
+ id
+ task
+ }
+ }
+ }
+ }
+`
+
+// Query for the data (React)
+const [result, reexecuteQuery] = useQuery({
+ query: TodosQuery,
+})
+
+// Read the result
+const { data, fetching, error } = result
+```
+
+
+
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/rest/auto-generated-docs.mdx b/apps/docs/pages/guides/api/rest/auto-generated-docs.mdx
new file mode 100644
index 00000000000..82709aa7a1a
--- /dev/null
+++ b/apps/docs/pages/guides/api/rest/auto-generated-docs.mdx
@@ -0,0 +1,26 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'auto-docs',
+ title: 'Auto-generated documentation',
+ description: 'Supabase provides documentation that updates automatically.',
+}
+
+Supabase generates documentation in the [Dashboard](https://app.supabase.com) which updates as you make database changes.
+
+1. Go to the [API](https://app.supabase.com/project/_/api) page in the Dashboard.
+2. Select any table under **Tables and Views** in the sidebar.
+3. Switch between the JavaScript and the cURL docs using the tabs.
+
+
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/api/rest/client-libs.mdx b/apps/docs/pages/guides/api/rest/client-libs.mdx
new file mode 100644
index 00000000000..5594ef78686
--- /dev/null
+++ b/apps/docs/pages/guides/api/rest/client-libs.mdx
@@ -0,0 +1,33 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'client-libs',
+ title: 'Client Libraries',
+ description: 'Supabase provides several client libraries for the REST and Realtime APIs.',
+ video: 'https://www.youtube.com/v/7CqlTU9aOR4',
+}
+
+Supabase provides client libraries for the REST and Realtime APIs. Some libraries are officially supported, and some are contributed by the community.
+
+## Official Libraries
+
+| `Language` | `Source Code` | `Documentation` |
+| --------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------- |
+| Javascript/Typescript | [supabase-js](https://github.com/supabase/supabase-js) | [Docs](https://supabase.com/docs/reference/javascript/introduction) |
+| Dart/Flutter | [supabase-dart](https://github.com/supabase/supabase-dart) | [Docs](https://supabase.com/docs/reference/dart/introduction) |
+
+## Community Libraries
+
+| `Language` | `Source Code` | `Documentation` |
+| ----------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------- |
+| C# | [supabase-csharp](https://github.com/supabase-community/supabase-csharp) | [Docs](https://supabase.com/docs/reference/csharp/introduction) |
+| Go | [supabase-go](https://github.com/supabase-community/supabase-go) | |
+| Kotlin | [supabase-kt](https://github.com/supabase-community/supabase-kt) | |
+| Python | [supabase-py](https://github.com/supabase-community/supabase-py) | [Docs](https://supabase.com/docs/reference/python/initializing) |
+| Ruby | [supabase-rb](https://github.com/supabase-community/supabase-rb) | |
+| Swift | [supabase-swift](https://github.com/supabase-community/supabase-swift) | |
+| Godot Engine (GDScript) | [supabase-gdscript](https://github.com/supabase-community/godot-engine.supabase) | |
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/database/api/generating-types.mdx b/apps/docs/pages/guides/api/rest/generating-types.mdx
similarity index 100%
rename from apps/docs/pages/guides/database/api/generating-types.mdx
rename to apps/docs/pages/guides/api/rest/generating-types.mdx
diff --git a/apps/docs/pages/guides/api/securing-your-api.mdx b/apps/docs/pages/guides/api/securing-your-api.mdx
new file mode 100644
index 00000000000..70fa2ef38ae
--- /dev/null
+++ b/apps/docs/pages/guides/api/securing-your-api.mdx
@@ -0,0 +1,66 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'securing-your-api',
+ title: 'Securing your API',
+ description: 'Securing your Serverless API with Postgres Row Level Security.',
+}
+
+The Serverless APIs are designed to work with Postgres Row Level Security (RLS). If you use [Supabase Auth](/docs/guides/auth), you can restrict data based on the logged-in user.
+To control access to your data, you can use [Policies](/docs/guides/auth#policies).
+
+## Enabling Row Level Security
+
+If you create a table through the Dashboard, RLS will be enabled by default. This is not the case, however, if you create a table or view using SQL.
+To enable RLS on any table:
+
+
+
+
+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.
+
+
+
+
+```sql
+alter table
+ todos enable row level security;
+```
+
+
+
+
+With RLS enabled, you can create Policies that allow or disallow users to access and update data. We provide a detailed guide for creating Row Level Security Policies in our [Authorization documentation](/docs/guides/auth/row-level-security).
+
+## Safeguards towards accidental deletes and updates
+
+By default, all projects have the [safeupdate](https://github.com/eradman/pg-safeupdate) Postgres extension enabled for API queries.
+This ensures that `delete()` and `update()` requests will fail if there are no filters provided.
+To confirm that safeupdate is enabled for API queries, run the following query:
+
+```sql
+select
+ usename,
+ useconfig
+from
+ pg_shadow
+where
+ usename = 'authenticator';
+```
+
+The expected value for `useconfig` should be:
+
+```sql
+['session_preload_libraries=supautils, safeupdate']
+```
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/auth/overview.mdx b/apps/docs/pages/guides/auth.mdx
similarity index 100%
rename from apps/docs/pages/guides/auth/overview.mdx
rename to apps/docs/pages/guides/auth.mdx
diff --git a/apps/docs/pages/guides/auth/auth-helpers/auth-ui.mdx b/apps/docs/pages/guides/auth/auth-helpers/auth-ui.mdx
index 52f2e5acf68..e52a421e9cb 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/auth-ui.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/auth-ui.mdx
@@ -66,7 +66,7 @@ const App = () => (
### Social Providers
-The Auth component also supports login with [offical social providers](../../auth#providers).
+The Auth component also supports login with [official social providers](../../auth#providers).
```js lines=13 title=/src/index.js
import { createClient } from '@supabase/supabase-js'
@@ -322,6 +322,8 @@ const App = () => (
)
```
+Currently, translating error messages (e.g. "Invalid credentials") is not supported. Check [related issue.](https://github.com/supabase/auth-ui/issues/86)
+
export const Page = ({ children }) =>
export default Page
diff --git a/apps/docs/pages/guides/auth/auth-helpers/nextjs-server-components.mdx b/apps/docs/pages/guides/auth/auth-helpers/nextjs-server-components.mdx
index 21ec7369f1f..5cad755ec61 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/nextjs-server-components.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/nextjs-server-components.mdx
@@ -2,13 +2,15 @@ import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'nextjs-server-components',
- title: 'Supabase Auth with Next.js Server Components',
+ title: 'Supabase Auth with Next.js app directory',
description:
- 'Authentication helpers for creating an authenticated Supabase client in Next.js 13 app directory Server Components.',
- sidebar_label: 'Next.js Server Components',
+ 'Authentication helpers for creating an authenticated Supabase client in Next.js 13 app directory Server Components and Route Handlers.',
+ sidebar_label: 'Next.js (app)',
}
-This submodule provides experimental convenience helpers for implementing user authentication in Next.js Server Components - the `app` directory. For examples using the `pages` directory check out [Auth Helpers in Next.js](/docs/guides/auth/auth-helpers/nextjs).
+The Next.js Auth Helpers package configures Supabase Auth to store the user's session in a cookie, rather than `localStorage`. This makes the users's session available server-side - in Server Components and Route Handlers - and is automatically sent along with any requests to Supabase.
+
+> The `app` directory in Next.js is still in beta and expected to change. For examples using the `pages` directory check out [Auth Helpers in Next.js](/docs/guides/auth/auth-helpers/nextjs).
-> For a complete implementation example, check out [this repo](https://github.com/supabase/auth-helpers/tree/main/examples/nextjs-server-components).
-
-> To learn more about fetching and caching Supabase data with Next.js 13 Server Components, check out our [blog](/blog/fetching-and-caching-supabase-data-in-next-js-server-components) or [live stream](https://www.youtube.com/watch?v=QH0P5xZt5wY).
+> To learn more about Supabase and the Next.js 13 app directory, check out [this playlist](https://youtube.com/playlist?list=PL5S4mPUpp4OtwG-qCxm8gA_hjaBq0OPdz).
## Install the Next.js helper library
@@ -61,9 +61,7 @@ NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
-## Creating a Supabase Client
-
-### Server-side
+## Configure Middleware
-Create a new file at `/utils/supabase-server.js` and populate with the following:
+Middleware runs immediately before each route in rendered. Next.js only provides read access to headers and cookies in Server Components and Route Handlers, however, Supabase needs to be able to set cookies and headers to refresh expired access tokens. Therefore, you must call the `getSession` function in `middleware.js` in order to use a Supabase client in Server Components or Route Handlers.
-```js title="/utils/supabase-server.js"
-import { headers, cookies } from 'next/headers'
-import { createServerComponentSupabaseClient } from '@supabase/auth-helpers-nextjs'
-
-export const createClient = () =>
- createServerComponentSupabaseClient({
- headers,
- cookies,
- })
-```
-
-> This needs to export a function, as the headers and cookies are not populated with values until the Server Component is requesting data.
-
-
-
-
-
-Create a new file at `/utils/supabase-server.ts` and populate with the following:
-
-```ts title="/utils/supabase-server.ts"
-import { headers, cookies } from 'next/headers'
-import { createServerComponentSupabaseClient } from '@supabase/auth-helpers-nextjs'
-
-import type { Database } from '../lib/database.types'
-
-export const createClient = () =>
- createServerComponentSupabaseClient({
- headers,
- cookies,
- })
-```
-
-> TypeScript types can be [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/typescript-support) and passed to `createServerSupabaseClient` to add type support to the Supabase client.
-
-> This needs to export a function, as the headers and cookies are not populated with values until the Server Component is requesting data.
-
-
-
-
-This will be used any time we need to create a Supabase client _server-side_ - in a Server Component, for example.
-
-Next, we need a middleware file to refresh the user's session on navigation.
-
-> If you were using Middleware prior to 12.2, see the [upgrade guide](https://nextjs.org/docs/messages/middleware-upgrade-guide).
-
-
-
-
-Create a new `middleware.js` file at the same level as your `app` (in the root or `src` directory) and populate with the following:
+Create a new `middleware.js` file in the root of your project and populate with the following:
```jsx title="middleware.js"
import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs'
@@ -136,13 +81,8 @@ import { NextResponse } from 'next/server'
export async function middleware(req) {
const res = NextResponse.next()
-
const supabase = createMiddlewareSupabaseClient({ req, res })
-
- const {
- data: { session },
- } = await supabase.auth.getSession()
-
+ await supabase.auth.getSession()
return res
}
```
@@ -151,24 +91,21 @@ export async function middleware(req) {
-Create a new `middleware.ts` file at the same level as your `app` (in the root or `src` directory) and populate with the following:
+Middleware runs immediately before each route in rendered. Next.js only provides read access to headers and cookies in Server Components and Route Handlers, however, Supabase needs to be able to set cookies and headers to refresh expired access tokens. Therefore, you must call the `getSession` function in `middleware.ts` in order to use a Supabase client in Server Components or Route Handlers.
+
+Create a new `middleware.ts` file in the root of your project and populate with the following:
```tsx title="middleware.ts"
import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
-import type { Database } from './lib/database.types'
+import type { Database } from '@/lib/database.types'
export async function middleware(req: NextRequest) {
const res = NextResponse.next()
-
const supabase = createMiddlewareSupabaseClient({ req, res })
-
- const {
- data: { session },
- } = await supabase.auth.getSession()
-
+ await supabase.auth.getSession()
return res
}
```
@@ -178,27 +115,9 @@ export async function middleware(req: NextRequest) {
-We can now use our server-side Supabase client to fetch data in Server Components.
+## Supabase Provider
-```jsx
-import 'server-only'
-
-import { createClient } from '../../utils/supabase-server'
-
-// do not cache this page
-export const revalidate = 0
-
-export default async function ServerComponent() {
- const supabase = createClient()
- const { data } = await supabase.from('posts').select('*')
-
- return
{JSON.stringify({ data }, null, 2)}
-}
-```
-
-### Client-side
-
-We still need a Supabase instance client-side for authentication and realtime subscriptions. It is important, when using Supabase client-side, to have a single instance of a client. We can share this singleton instance across our components using providers and React context.
+All Client Components need to share a single instance of the Supabase client. We can wrap our application in a `` and use React Context to create a global Supabase instance.
-Create a new file at `/utils/supabase-browser.js` and populate with the following:
+Create a new file at `/app/supabase-provider.jsx` and populate with the following:
-```js title="/utils/supabase-browser.js"
-import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-export const createClient = () => createBrowserSupabaseClient()
-```
-
-
-
-
-
-Create a new file at `/utils/supabase-browser.ts` and populate with the following:
-
-```ts
-import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { Database } from '../lib/database.types'
-
-export const createClient = () => createBrowserSupabaseClient()
-```
-
-> TypeScript types can be [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/typescript-support) and passed to `createBrowserSupabaseClient` to add type support to the Supabase client.
-
-
-
-
-
-
-
-Next, we need to create a single instance of Supabase to use client-side. Let's create a new Provider for Supabase at `/components/supabase-provider.jsx` and populate with the following:
-
-```jsx title=components/supabase-provider.jsx
+```jsx title="app/supabase-provider.jsx"
'use client'
-import { createContext, useContext, useState } from 'react'
-import { createClient } from '../utils/supabase-browser'
+import { createContext, useContext, useEffect, useState } from 'react'
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { useRouter } from 'next/navigation'
-const Context = createContext()
+const Context = createContext(undefined)
export default function SupabaseProvider({ children }) {
- const [supabase] = useState(() => createClient())
+ const [supabase] = useState(() => createBrowserSupabaseClient())
+ const router = useRouter()
useEffect(() => {
- const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
- if (session?.access_token !== accessToken) {
- router.refresh()
- }
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange(() => {
+ router.refresh()
})
- return () => subscription.unsubscribe()
- }, [accessToken])
-
- return (
-
- <>{children}>
-
- )
-}
-
-export const useSupabase = () => useContext(Context)
-```
-
-
-
-
-
-Next, we need to create a single instance of Supabase to use client-side. Let's create a new Provider for Supabase at `/components/supabase-provider.tsx` and populate with the following:
-
-```tsx title=components/supabase-provider.tsx
-'use client'
-
-import { createContext, useContext, useState } from 'react'
-import { createClient } from '../utils/supabase-browser'
-
-import type { SupabaseClient } from '@supabase/auth-helpers-nextjs'
-import type { Database } from '../lib/database.types'
-
-type SupabaseContext = {
- supabase: SupabaseClient
-}
-
-const Context = createContext(undefined)
-
-export default function SupabaseProvider({ children }: { children: React.ReactNode }) {
- const [supabase] = useState(() => createClient())
+ return () => {
+ subscription.unsubscribe()
+ }
+ }, [router, supabase])
return (
@@ -306,12 +162,69 @@ export default function SupabaseProvider({ children }: { children: React.ReactNo
}
export const useSupabase = () => {
- let context = useContext(Context);
+ const context = useContext(Context)
+
if (context === undefined) {
- throw new Error("useSupabase must be used inside SupabaseProvider");
- } else {
- return context;
+ throw new Error('useSupabase must be used inside SupabaseProvider')
}
+
+ return context
+}
+```
+
+
+
+
+
+Create a new file at `/app/supabase-provider.tsx` and populate with the following:
+
+```tsx title="app/supabase-provider.tsx"
+'use client'
+
+import { createContext, useContext, useEffect, useState } from 'react'
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { useRouter } from 'next/navigation'
+
+import type { SupabaseClient } from '@supabase/auth-helpers-nextjs'
+import type { Database } from '@/lib/database.types'
+
+type SupabaseContext = {
+ supabase: SupabaseClient
+}
+
+const Context = createContext(undefined)
+
+export default function SupabaseProvider({ children }: { children: React.ReactNode }) {
+ const [supabase] = useState(() => createBrowserSupabaseClient())
+ const router = useRouter()
+
+ useEffect(() => {
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange(() => {
+ router.refresh()
+ })
+
+ return () => {
+ subscription.unsubscribe()
+ }
+ }, [router, supabase])
+
+ return (
+
+ <>{children}>
+
+ )
+}
+
+export const useSupabase = () => {
+ const context = useContext(Context)
+
+ if (context === undefined) {
+ throw new Error('useSupabase must be used inside SupabaseProvider')
+ }
+
+ return context
}
```
@@ -320,16 +233,6 @@ export const useSupabase = () => {
-We need to set up a listener to fetch fresh data whenever our user logs in or out. For this we need to check whether our client and server sessions match. Let's start by installing the `server-only` package.
-
-```bash
-npm install server-only
-```
-
-This will ensure that any component that imports this package will be a Server Component, and excluded from the browser bundle.
-
-Next, let's modify our root layout to fetch the user's session, wrap our application in our Supabase Provider, and pass the server access token as a prop to the `` component (we will create this next).
-
-```jsx title=app/layout.jsx
-import 'server-only'
+Modify `layout.jsx` to wrap the application with the `` component:
-import SupabaseListener from '../components/supabase-listener'
-import SupabaseProvider from '../components/supabase-provider'
+```jsx title="app/layout.jsx"
import './globals.css'
-import { createClient } from '../utils/supabase-server'
+import SupabaseProvider from './supabase-provider'
-// do not cache this layout
-export const revalidate = 0
-
-export default async function RootLayout({ children }) {
- const supabase = createClient()
-
- const {
- data: { session },
- } = await supabase.auth.getSession()
+export const metadata = {
+ title: 'Create Next App',
+ description: 'Generated by create next app',
+}
+export default function RootLayout({ children }) {
return (
- {/*
- will contain the components returned by the nearest parent
- head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
- */}
-
-
-
- {children}
-
+ {children}
)
@@ -378,36 +267,22 @@ export default async function RootLayout({ children }) {
-```tsx title=app/layout.tsx
-import 'server-only'
+Modify `layout.tsx` to wrap the application with the `` component:
-import SupabaseListener from '../components/supabase-listener'
-import SupabaseProvider from '../components/supabase-provider'
+```tsx title="app/layout.tsx"
import './globals.css'
-import { createClient } from '../utils/supabase-server'
+import SupabaseProvider from './supabase-provider'
-// do not cache this layout
-export const revalidate = 0
-
-export default async function RootLayout({ children }: { children: React.ReactNode }) {
- const supabase = createClient()
-
- const {
- data: { session },
- } = await supabase.auth.getSession()
+export const metadata = {
+ title: 'Create Next App',
+ description: 'Generated by create next app',
+}
+export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
- {/*
- will contain the components returned by the nearest parent
- head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
- */}
-
-
-
- {children}
-
+ {children}
)
@@ -417,7 +292,15 @@ export default async function RootLayout({ children }: { children: React.ReactNo
-And now create our Supabase listener component that uses the singleton Supabase instance to listen for auth changes.
+Now any of our Client Components can use the `useSupabase` hook to ensure they are using the same instance of a Supabase client.
+
+## Creating a Supabase Client
+
+### Client Components
+
+While Server Components are great for data fetching, we still need to use Supabase client-side for [authentication](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/login.tsx) and [realtime subscriptions](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/realtime-posts.tsx).
+
+As mentioned above, it is important that all Client Components share a single instance of the Supabase client. We can use the `useSupabase` hook we created above to ensure this is the case.
-```jsx title="/components/supabase-listener.jsx"
+```jsx title="app/new-post.jsx"
'use client'
-import { useRouter } from 'next/navigation'
-import { useEffect } from 'react'
+import { useState } from 'react'
import { useSupabase } from './supabase-provider'
-export default function SupabaseListener({ serverAccessToken }) {
+export default function NewPost() {
+ const [content, setContent] = useState('')
const { supabase } = useSupabase()
- const router = useRouter()
- useEffect(() => {
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((event, session) => {
- if (session?.access_token !== serverAccessToken) {
- router.refresh()
- }
- })
-
- return () => {
- subscription.unsubscribe()
- }
- }, [serverAccessToken, router, supabase])
-
- return null
-}
-```
-
-
-
-
-
-```tsx title="/components/supabase-listener.tsx"
-'use client'
-
-import { useRouter } from 'next/navigation'
-import { useEffect } from 'react'
-import { useSupabase } from './supabase-provider'
-
-export default function SupabaseListener({ serverAccessToken }: { serverAccessToken?: string }) {
- const { supabase } = useSupabase()
- const router = useRouter()
-
- useEffect(() => {
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((event, session) => {
- if (session?.access_token !== serverAccessToken) {
- router.refresh()
- }
- })
-
- return () => {
- subscription.unsubscribe()
- }
- }, [serverAccessToken, router, supabase])
-
- return null
-}
-```
-
-
-
-
-> `use client` tells Next.js that this is a [Client Component](https://beta.nextjs.org/docs/rendering/server-and-client-components#client-components). Only Client Components can use hooks like `useEffect` and `useRouter`.
-
-The function we pass to `onAuthStateChange` is automatically called by Supabase whenever a user's session changes. This component takes an `serverAccessToken` prop, which is the server's state for our user. If the `serverAccessToken` and the new session's `access_token` do not match then the client and server are out of sync, therefore, we want to reload the active route.
-
-Now we can use our `useSupabase` hook throughout our client-side components.
-
-### Authentication
-
-
-
-
-```jsx title="/components/login.jsx"
-'use client'
-
-import { useSupabase } from './supabase-provider'
-
-// Supabase auth needs to be triggered client-side
-export default function Login() {
- const { supabase, session } = useSupabase()
-
- const handleEmailLogin = async () => {
- await supabase.auth.signInWithPassword({
- email: 'jon@supabase.com',
- password: 'password',
- })
- }
-
- const handleGitHubLogin = async () => {
- await supabase.auth.signInWithOAuth({
- provider: 'github',
- })
- }
-
- const handleLogout = async () => {
- await supabase.auth.signOut()
+ const handleSave = async () => {
+ const { data } = await supabase.from('posts').insert({ content }).select()
}
return (
<>
-
-
-
+ setContent(e.target.value)} value={content} />
+
>
)
}
@@ -548,37 +337,24 @@ export default function Login() {
-```tsx title="/components/login.tsx"
+```jsx title="app/new-post.tsx"
'use client'
+import { useState } from 'react'
import { useSupabase } from './supabase-provider'
-// Supabase auth needs to be triggered client-side
-export default function Login() {
- const { supabase, session } = useSupabase()
+export default function NewPost() {
+ const [content, setContent] = useState('')
+ const { supabase } = useSupabase()
- const handleEmailLogin = async () => {
- await supabase.auth.signInWithPassword({
- email: 'jon@supabase.com',
- password: 'password',
- })
- }
-
- const handleGitHubLogin = async () => {
- await supabase.auth.signInWithOAuth({
- provider: 'github',
- })
- }
-
- const handleLogout = async () => {
- await supabase.auth.signOut()
+ const handleSave = async () => {
+ const { data } = await supabase.from('posts').insert({ content }).select()
}
return (
<>
-
-
-
+ setContent(e.target.value)} value={content} />
+
>
)
}
@@ -587,11 +363,11 @@ export default function Login() {
-### Realtime
+> check out [this example](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/supabase-provider.tsx) for making the user's session available to all Client Components.
-A nice pattern for fetching data server-side and subscribing to changes client-side can be done by combining Server and Client components.
+### Server Components
-> To receive realtime events, you must [enable replication on your "posts" table in Supabase](https://app.supabase.com/project/_/database/replication).
+In order to use Supabase in Server Components, you need to have implemented the `middleware.ts` steps above 👆
-Create a new file at `/app/realtime/posts.jsx` and populate with the following:
-
-```jsx title="/app/realtime/posts.jsx"
-'use client'
-
-import { useEffect, useState } from 'react'
-import { useSupabase } from '../../components/supabase-provider'
-
-export default function Posts({ serverPosts }) {
- const [posts, setPosts] = useState(serverPosts)
- const { supabase } = useSupabase()
-
- useEffect(() => {
- setPosts(serverPosts)
- }, [serverPosts])
-
- useEffect(() => {
- const channel = supabase
- .channel('*')
- .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'posts' }, (payload) =>
- setPosts((posts) => [...posts, payload.new])
- )
- .subscribe()
-
- return () => {
- supabase.removeChannel(channel)
- }
- }, [supabase, setPosts, posts])
-
- return
{JSON.stringify(posts, null, 2)}
-}
-```
-
-This can now be used in a Server Component to subscribe to realtime updates.
-
-Create a new file at `/app/realtime/page.jsx` and populate with the following:
-
-```jsx title="/app/realtime/page.jsx"
-import 'server-only'
-
-import { createClient } from '../../utils/supabase-server'
-import Posts from './posts'
+```jsx title="app/page.jsx"
+import { createServerComponentSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { headers, cookies } from 'next/headers'
// do not cache this page
export const revalidate = 0
-export default async function Realtime() {
- const supabase = createClient()
+export default async function ServerComponent() {
+ const supabase = createServerComponentSupabaseClient({
+ headers,
+ cookies,
+ })
const { data } = await supabase.from('posts').select('*')
- return
+ return
{JSON.stringify(data, null, 2)}
}
```
@@ -659,69 +399,91 @@ export default async function Realtime() {
-Create a new file at `/app/realtime/posts.tsx` and populate with the following:
+```tsx title="app/page.tsx"
+import { createServerComponentSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { headers, cookies } from 'next/headers'
-```tsx title="/app/realtime/posts.tsx"
-'use client'
-
-import { useEffect, useState } from 'react'
-import { useSupabase } from '../../components/supabase-provider'
-
-import type { Database } from '../../lib/database.types'
-
-type Post = Database['public']['Tables']['posts']['Row']
-
-export default function Posts({ serverPosts }: { serverPosts: Post[] }) {
- const [posts, setPosts] = useState(serverPosts)
- const { supabase } = useSupabase()
-
- useEffect(() => {
- setPosts(serverPosts)
- }, [serverPosts])
-
- useEffect(() => {
- const channel = supabase
- .channel('*')
- .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'posts' }, (payload) =>
- setPosts((posts) => [...posts, payload.new as Post])
- )
- .subscribe()
-
- return () => {
- supabase.removeChannel(channel)
- }
- }, [supabase, setPosts, posts])
-
- return
{JSON.stringify(posts, null, 2)}
-}
-```
-
-> TypeScript types can be [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/typescript-support) and passed to `createServerSupabaseClient` to add type support to the Supabase client.
-
-This can now be used in a Server Component to subscribe to realtime updates.
-
-Create a new file at `/app/realtime/page.tsx` and populate with the following:
-
-```tsx title="/app/realtime/page.tsx"
-import 'server-only'
-
-import { createClient } from '../../utils/supabase-server'
-import Posts from './posts'
+import type { Database } from '@/lib/database.types'
// do not cache this page
export const revalidate = 0
-export default async function Realtime() {
- const supabase = createClient()
+export default async function ServerComponent() {
+ const supabase = createServerComponentSupabaseClient({
+ headers,
+ cookies,
+ })
const { data } = await supabase.from('posts').select('*')
- return
+ return
{JSON.stringify(data, null, 2)}
}
```
+> check out [this example](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/page.tsx) for redirecting unauthenticated users - protected pages.
+
+### Route Handlers
+
+In order to use Supabase in Route Handlers, you need to have implemented the `middleware.ts` steps above 👆
+
+
+
+
+```jsx title="app/api/posts/route.jsx"
+import { createRouteHandlerSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { NextResponse } from 'next/server'
+import { headers, cookies } from 'next/headers'
+
+// do not cache this page
+export const revalidate = 0
+
+export async function GET() {
+ const supabase = createRouteHandlerSupabaseClient({
+ headers,
+ cookies,
+ })
+ const { data } = await supabase.from('posts').select('*')
+ return NextResponse.json(data)
+}
+```
+
+
+
+
+
+```tsx title="app/api/posts/route.tsx"
+import { createRouteHandlerSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { NextResponse } from 'next/server'
+import { headers, cookies } from 'next/headers'
+
+import type { Database } from '@/lib/database.types'
+
+// do not cache this page
+export const revalidate = 0
+
+export async function GET() {
+ const supabase = createRouteHandlerSupabaseClient({
+ headers,
+ cookies,
+ })
+ const { data } = await supabase.from('posts').select('*')
+
+ return NextResponse.json(data)
+}
+```
+
+
+
+
+> Check out [this repo](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs) for a full example including [authentication](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/login.tsx), [realtime](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/realtime-posts.tsx) and [protected pages](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs/app/page.tsx).
+
export const Page = ({ children }) =>
export default Page
diff --git a/apps/docs/pages/guides/auth/auth-helpers/nextjs.mdx b/apps/docs/pages/guides/auth/auth-helpers/nextjs.mdx
index 4d450f7d48b..231edb486ca 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/nextjs.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/nextjs.mdx
@@ -4,7 +4,7 @@ export const meta = {
id: 'nextjs',
title: 'Supabase Auth with Next.js',
description: 'Authentication helpers for Next.js API routes, middleware, and SSR.',
- sidebar_label: 'Next.js',
+ sidebar_label: 'Next.js (pages)',
}
This submodule provides convenience helpers for implementing user authentication in Next.js applications.
diff --git a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
index f4d71380697..424ed29ee0a 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
@@ -86,7 +86,7 @@ import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {
return {
- session: getSession()
+ session: await getSession()
};
};
```
@@ -142,13 +142,15 @@ We need to create an event listener in the root `+layout.svelte` file in order c
export let data: LayoutData;
- $: ({ supabase } = data);
+ $: ({ supabase, session } = data);
onMount(() => {
const {
data: { subscription },
- } = supabase.auth.onAuthStateChange(() => {
- invalidate('supabase:auth');
+ } = supabase.auth.onAuthStateChange((event, _session) => {
+ if (_session?.expires_at !== session?.expires_at) {
+ invalidate('supabase:auth');
+ }
});
return () => subscription.unsubscribe();
@@ -185,26 +187,6 @@ declare global {
}
```
-### Basic Setup
-
-You can now determine if a user is authenticated on the client-side by checking that the `session` object in `$page.data` is defined.
-
-```html
-
-
-
-{#if !session}
-
I am not logged in
-{:else}
-
Welcome {session.user.email}
-
I am logged in!
-{/if}
-```
-
## Client-side data fetching with RLS
For [row level security](https://supabase.com/docs/guides/auth/row-level-security) to work properly when fetching data client-side, you need to use `supabaseClient` from `PageData` and only run your query once the session is defined client-side:
@@ -217,8 +199,8 @@ For [row level security](https://supabase.com/docs/guides/auth/row-level-securit
let loadedData = [];
async function loadData() {
- const { data } = await data.supabase.from('test').select('*').limit(20);
- loadedData = data;
+ const { data: result } = await data.supabase.from('test').select('*').limit(20);
+ loadedData = result;
}
$: if (data.session) {
@@ -385,7 +367,6 @@ protect multiple routes at once.
```ts
// src/hooks.server.ts
import type { RequestHandler } from './$types';
-import { getSupabase } from '@supabase/auth-helpers-sveltekit';
import { redirect, error } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
@@ -562,13 +543,15 @@ export const load: LayoutLoad = async ({ fetch, data, depends }) => {
export let data: LayoutData;
- $: ({ supabase } = data);
+ $: ({ supabase, session } = data);
onMount(() => {
const {
data: { subscription },
- } = supabase.auth.onAuthStateChange(() => {
- invalidate('supabase:auth');
+ } = supabase.auth.onAuthStateChange((event, _session) => {
+ if (_session?.expires_at !== session?.expires_at) {
+ invalidate('supabase:auth')
+ }
});
return () => subscription.unsubscribe();
diff --git a/apps/docs/pages/guides/auth/enterprise-sso.mdx b/apps/docs/pages/guides/auth/enterprise-sso.mdx
index fbfb7b73915..5ca0dffcd0c 100644
--- a/apps/docs/pages/guides/auth/enterprise-sso.mdx
+++ b/apps/docs/pages/guides/auth/enterprise-sso.mdx
@@ -1,13 +1,11 @@
import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
- title: 'Enterprise SSO',
+ title: 'Enterprise Single Sign-On',
description: 'Learn about Single Sign-On support in Supabase Auth for enterprise applications',
}
-Supabase Auth supports building enterprise applications that require Single Sign-On (SSO) authentication. At this time only [SSO with SAML 2.0](/guides/auth/sso/auth-sso-saml) is supported in an early beta.
-
-If you are interested in using SAML 2.0 SSO with your Supabase project, please [open a new support ticket](https://app.supabase.com/support/new).
+Supabase Auth supports building enterprise applications that require Single Sign-On (SSO) authentication [with SAML 2.0](/docs/guides/auth/sso/auth-sso-saml).
export const Page = ({ children }) =>
diff --git a/apps/docs/pages/guides/auth/phone-login/twilio.mdx b/apps/docs/pages/guides/auth/phone-login/twilio.mdx
index be9da960411..11bca2d9bac 100644
--- a/apps/docs/pages/guides/auth/phone-login/twilio.mdx
+++ b/apps/docs/pages/guides/auth/phone-login/twilio.mdx
@@ -1,5 +1,4 @@
import Layout from '~/layouts/DefaultGuideLayout'
-
export const meta = {
id: 'auth-twilio',
title: 'Phone Auth with Twilio',
@@ -295,6 +294,56 @@ and the response should also be the same as above:
The user does not have a password therefore will need to sign in via this method each time they want to access your service.
+## WhatsApp OTP Logins
+
+In some cases, you may wish to use WhatsApp as a delivery channel instead. Here are some examples our users have cited:
+
+- You want higher deliverability
+- You wish for a secure channel
+- Your users mostly use WhatsApp as a messaging platform
+
+To make use of WhatsApp OTP, please complete the following steps:
+
+- Go through the [Twilio self sign up guide for WhatsApp](https://www.twilio.com/docs/whatsapp/self-sign-up)
+- Submit a template via the [Twilio Guide For Submitting WhatsApp templates](https://www.twilio.com/docs/whatsapp/tutorial/send-whatsapp-notification-messages-templates#creating-message-templates-and-submitting-them-for-approval)
+
+
+The message template submitted to Twilio must exactly match the SMS Body entered on the Supabase dashboard.
+
+
+The sign in process with WhatsApp is similar to the sign in process for SMS. Do note the additional `whatsapp` parameter added:
+
+```js
+const {data, error } = await supabase.auth.signInWithOtp({
+ phone: '+57336567365',
+ options: {
+ channel:'whatsapp'
+ }
+ })
+```
+
+You can also sign up with `whatsapp` as a channel:
+
+```js
+const {data, error }= await supabase.auth.signUp({
+ phone: '+57336567365',
+ password: 'testsupabasenow',
+ options: {
+ channel:'whatsapp',
+ }
+})
+```
+
+There is no change in the verification process, you should continue to use the `sms` type for verification
+```js
+// After receiving a WhatsApp OTP
+let { data, error } = await supabase.auth.verifyOtp({
+ phone: '+57336567365',
+ token: '123456',
+ type: 'sms',
+})
+```
+
## Resources
- [Twilio Signup](https://www.twilio.com/try-twilio)
diff --git a/apps/docs/pages/guides/auth/quickstarts/react.mdx b/apps/docs/pages/guides/auth/quickstarts/react.mdx
new file mode 100644
index 00000000000..c2ae0efb7fb
--- /dev/null
+++ b/apps/docs/pages/guides/auth/quickstarts/react.mdx
@@ -0,0 +1,137 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+import StepHikeCompact from '~/components/StepHikeCompact'
+
+export const meta = {
+ title: 'Use Supabase Auth with React',
+ subtitle: 'Learn how to Supabase Auth with React.js.',
+ breadcrumb: 'Auth Quickstarts',
+}
+
+
+
+
+
+
+ [Launch a new project](https://app.supabase.com) in the Supabase Dashboard.
+
+ Your new database has a table for storing your users. You can see that this table is currently empty by running some SQL in the [SQL Editor](https://app.supabase.com/project/_/sql).
+
+
+
+
+
+ ```sql SQL_EDITOR
+ select * from auth.users;
+ ````
+
+
+
+
+
+
+
+
+
+ Create a React app using the `create-react-app` command.
+
+
+
+
+
+ ```bash Terminal
+ npx create-react-app my-app
+ ```
+
+
+
+
+
+
+
+
+ The fastest way to get started is to use Supabase's `auth-ui-react` library which provides a convenient interface for working with Supabase Auth from a React app.
+
+ Navigate to the React app and install the Supabase libraries.
+
+
+
+
+
+ ```bash Terminal
+ cd my-app && npm install @supabase/supabase-js @supabase/auth-ui-react
+ ```
+
+
+
+
+
+
+
+
+ In `index.js`, create a Supabase client using your [Project URL and public API (anon) key](https://app.supabase.com/project/_/settings/api).
+
+ You can configure the Auth component to display whenever there is no session inside `supabase.auth.getSession()`
+
+
+
+
+
+ ```js src/index.js
+ import './index.css'
+ import { useState, useEffect } from 'react'
+ import { createClient } from '@supabase/supabase-js'
+ import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
+
+ const supabase = createClient('https://.supabase.co', '')
+
+ export default function App() {
+ const [session, setSession] = useState(null)
+
+ useEffect(() => {
+ supabase.auth.getSession().then(({ data: { session } }) => {
+ setSession(session)
+ })
+
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange((_event, session) => {
+ setSession(session)
+ })
+
+ return () => subscription.unsubscribe()
+ }, [])
+
+ if (!session) {
+ return ()
+ }
+ else {
+ return (
Logged in!
)
+ }
+ }
+ ```
+
+
+
+
+
+
+
+
+ Start the app, go to http://localhost:3000 in a browser, and open the browser console and you should be able to log in.
+
+
+
+
+
+ ```bash Terminal
+ npm start
+ ```
+
+
+
+
+
+
+export const Page = ({ children }) =>
+
+export default Page
diff --git a/apps/docs/pages/guides/auth/server-side-rendering.mdx b/apps/docs/pages/guides/auth/server-side-rendering.mdx
index 346984a63fb..7b7edb00924 100644
--- a/apps/docs/pages/guides/auth/server-side-rendering.mdx
+++ b/apps/docs/pages/guides/auth/server-side-rendering.mdx
@@ -1,4 +1,5 @@
import Layout from '~/layouts/DefaultGuideLayout'
+import { Accordion } from 'ui'
export const meta = {
id: 'server-side-rendering',
@@ -55,8 +56,25 @@ like `*` and `**` to allow redirects to different forms of URLs.
-These redirect URLs have the following structure:
+Supabase Auth supports two authentication flows: **Implicit** and **PKCE**. The **PKCE** flow is generally preferred when on the server.
+It introduces a few additional steps which guard a against replay and URL capture attacks. Unlike the implicit flow, it also allows users to access the
+`access_token` and `refresh_token` on the server.
+
+
+ Implicit}
+ id={`ssr-implicit-flow`}
+ >
+
+When using the implicit flow, a redirect URL will be returned with the following structure:
```
https://yourapp.com/...#access_token=<...>&refresh_token=<...>&...
```
@@ -77,9 +95,76 @@ 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.
-
+approach also avoids leaking credentials in request or access logs. If you wish to obtain the
+`access_token` and `refresh_token` on a server, please consider using the PKCE flow.
+
+
+
+ PKCE}
+ id={`ssr-pkce-flow`}
+ >
+ When using the PKCE flow, a redirect URL will be returned with the following structure:
+ ```
+ https://yourapp.com/...?code=<...>
+ ```
+ The `code` parameter is commonly known as the Auth Code and can be exchanged for an access token by calling `exchangeCodeForSession(code)`.
+
+ For security purposes, the code has a validity of 5 minutes and can only be exchanged for an access token once. You
+ will need to restart the authentication flow from scratch if you wish to obtain a new access token.
+
+
+ As the flow is run server side, `localStorage` may not be available. You may configure the client library to use a custom storage adapter an alternate backing storage such as cookies
+ by setting the `storage` option to an object with the following methods:
+ ```js
+ const customStorageAdapter: SupportedStorage = {
+ getItem: (key) => {
+ if (!supportsLocalStorage()) {
+ // Configure alternate storage
+ return null
+ }
+ return globalThis.localStorage.getItem(key)
+ },
+ setItem: (key, value) => {
+ if (!supportsLocalStorage()) {
+ // Configure alternate storage here
+ return
+ }
+ globalThis.localStorage.setItem(key, value)
+ },
+ removeItem: (key) => {
+ if (!supportsLocalStorage()) {
+ // Configure alternate storage here
+ return
+ }
+ globalThis.localStorage.removeItem(key)
+ },
+ }
+ ```
+ You may also configure the client library to automatically exchange it for a session after a successful redirect. This can be done by setting the `detectSessionInUrl` option to `true`.
+
+ Putting it all together, your client library initialization may look like this:
+ ```js
+ const supabase = createClient(
+ 'https://xyzcompany.supabase.co',
+ 'public-anon-key',
+ options: {
+ ...
+ auth: {
+ ...
+ detectSessionInUrl: true,
+ flowType: 'pkce',
+ storage: customStorageAdapter,
+ }
+ ...
+ }
+ )
+ ```
+ You can read more about the PKCE flow [here](https://oauth.net/2/pkce/)
+
+
+
## Bringing it together
@@ -130,6 +215,9 @@ if (refreshToken && accessToken) {
await supabase.auth.setSession({
refresh_token: refreshToken,
access_token: accessToken,
+ {
+ auth: { persistSession: false },
+ }
})
} else {
// make sure you handle this case!
@@ -217,3 +305,4 @@ cache keys every hour or less.
export const Page = ({ children }) =>
export default Page
+
diff --git a/apps/docs/pages/guides/auth/sso/auth-sso-saml.mdx b/apps/docs/pages/guides/auth/sso/auth-sso-saml.mdx
index 4ef6f345206..1923b2ed243 100644
--- a/apps/docs/pages/guides/auth/sso/auth-sso-saml.mdx
+++ b/apps/docs/pages/guides/auth/sso/auth-sso-saml.mdx
@@ -2,28 +2,37 @@ import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'auth-sso-saml',
- title: 'Single Sign-On with SAML 2.0',
- description: 'Use Single Sign-On (SSO) authentication with SAML 2.0',
+ title: 'Single Sign-On with SAML 2.0 for Projects',
+ description: 'Use Single Sign-On (SSO) authentication on your project with SAML 2.0',
video: 'https://www.youtube.com/v/em1cpOAXknM',
}
-Supabase Auth supports enterprise-level Single Sign-On (SSO) for any identity providers compatible with the using the SAML 2.0 protocol.
+Supabase Auth supports enterprise-level Single Sign-On (SSO) for any identity providers compatible with the using the SAML 2.0 protocol. This is a non-exclusive list of supported identity providers:
-
-This is an early beta release of these APIs. CLI and Dashboard support for SSO is under development.
+- Google Workspaces (formerly known as GSuite)
+- Okta, Auth0
+- Microsoft Active Directory, Azure Active Directory, Microsoft Entra
+- PingIdentity
+- OneLogin
-If you are comfortable using these APIs and would like to try out SSO with SAML 2.0 for your project, please [open a support ticket](https://app.supabase.com/support/new).
+If you're having issues with identity provider software not on this list, please [open a support ticket](https://app.supabase.com/support/new).
-These APIs are not expected to change before the feature is generally available, but we do reserve the right to modify them. Projects in the Beta will be notified of any changes.
+## Prerequisites
-
+This guide requires the use of the [Supabase CLI](/docs/guides/cli). Please make sure you're using version v1.46.4 or higher. You can use `supabase -v` to see the currently installed version.
+
+You can use the `supabase sso` [subcommands](/docs/reference/cli/supabase-sso) to manage your project's configuration.
+
+SAML 2.0 support is disabled by default on Supabase projects. You can configure this on the [Auth Providers](https://app.supabase.com/project/_/auth/providers) page on your project.
+
+Please note that SAML 2.0 support is offered on tiers Pro and above. Check the [Pricing](https://supabase.com/pricing) page for more information.
## Terminology
-The number of SAML and SSO acronyms can often overwhelming. Here's a glossary which you can refer back to at any time:
+The number of SAML and SSO acronyms can often be overwhelming. Here's a glossary which you can refer back to at any time:
- **Identity Provider**, **IdP**, or **IDP**
- This is software that manages user accounts at a company or organization. It can verify the identity of a user and exchange that information with your Supabase project. Commonly used identity providers are: Microsoft Active Directory (Azure AD, Microsoft Entra), Okta, Google Workspaces (GSuite), PingIdentity, OneLogin, and many others.
+ An identity provider is a service that manages user accounts at a company or organization. It can verify the identity of a user and exchange that information with your Supabase project and other applications. It acts as a single source of truth for user identities and access rights. Commonly used identity providers are: Microsoft Active Directory (Azure AD, Microsoft Entra), Okta, Google Workspaces (GSuite), PingIdentity, OneLogin, and many others. There are also self-hosted and on-prem versions of identity providers, and sometimes they are accessible only by having access to a company VPN or being in a specific building.
- **Service Provider**, **SP**
This is the software that is asking for user information from an identity provider. In Supabase, this is your project's Auth server.
- **Assertion**
@@ -47,17 +56,20 @@ The number of SAML and SSO acronyms can often overwhelming. Here's a glossary wh
Below is information about your project's SAML 2.0 configuration which you can share with the company or organization that you're trying to on-board.
-| Name | Value |
-| ------------ | --------------------------------------------------------- |
-| EntityID | `https://.supabase.co/auth/v1/sso/saml/metadata` |
-| Metadata URL | `https://.supabase.co/auth/v1/sso/saml/metadata` |
-| ACS URL | `https://.supabase.co/auth/v1/sso/saml/acs` |
-| SLO URL | `https://.supabase.co/auth/v1/sso/slo` |
-| NameID | Required `emailAddress` or `persistent` |
+| Name | Value |
+| --------------------------- | ----------------------------------------------------------------------- |
+| EntityID | `https://.supabase.co/auth/v1/sso/saml/metadata` |
+| Metadata URL | `https://.supabase.co/auth/v1/sso/saml/metadata` |
+| Metadata URL (download) | `https://.supabase.co/auth/v1/sso/saml/metadata?download=true` |
+| ACS URL | `https://.supabase.co/auth/v1/sso/saml/acs` |
+| SLO URL | `https://.supabase.co/auth/v1/sso/slo` |
+| NameID | Required `emailAddress` or `persistent` |
Note that SLO (Single Logout) is not supported at this time with Supabase Auth as it is a rarely supported feature by identity providers. However, the URL is registered and advertised for when this does become available.
-Append `?download=true` to the Metadata URL to get a downloadable Metadata XML file.
+Append `?download=true` to the Metadata URL to download the Metadata XML file. This is useful in cases where the identity provider requires a file.
+
+Alternatively, you can use the `supabase sso info --project-ref ` [command](/docs/reference/cli/supabase-sso-info) to get setup information for your project.
### User accounts and identities
@@ -119,18 +131,7 @@ CREATE POLICY "View organization settings."
## Managing SAML 2.0 connections
-### Prerequisites
-
-SSO support with SAML 2.0 is in an early beta release. This guide uses the following software which you need to install on your machine to configure your project:
-
-- [**cURL**](https://curl.se)
- It is typically pre-installed in macOS and GNU/Linux distributions.
-- [**jq**](https://stedolan.github.io/jq/)
- You can install it with `brew install jq` on macOS or using your distribution's package manager.
-
-You would need access to two keys -- the `anon` and `service_role` key. You can obtain these on the [Project API Keys](https://app.supabase.com/project/_/settings/api) page in the dashboard.
-
-We publish an [OpenAPI specification](https://github.com/supabase/gotrue/blob/master/openapi.yaml) which you can refer to at any time.
+Once you've enabled SAML 2.0 support on your project via the [Auth Providers](https://app.supabase.com/project/_/auth/providers) page in the dashboard, you can use the [Supabase CLI](/docs/reference/cli/supabase-sso) to add, update, remove and view information about identity providers.
### Add a connection
@@ -151,40 +152,34 @@ Commonly used SAML 2.0 Identity Providers that support Metadata URLs:
Commonly used SAML 2.0 Identity Providers that only support Metadata XML files:
- Google Workspaces (GSuite)
+- Any self-hosted or on-prem identity provider behind a VPN
-Once you've obtained the SAML 2.0 Metadata XML file or URL you can establish a connection with your project's Supabase Auth server by invoking this API:
+Once you've obtained the SAML 2.0 Metadata XML file or URL you can [establish a connection](/docs/reference/cli/supabase-sso-add) with your project's Supabase Auth server by running:
```bash
-curl -X POST \
- -H 'Content-Type: application/json' \
- -H 'apikey: ' \
- -H 'Authorization: Bearer ' \
- --data-binary '@/tmp/body.json' \
- 'https://.supabase.co/auth/v1/admin/sso/providers'
-```
-
-To create the `/tmp/body.json` file you can use this:
-
-```bash
-jq --null-input \
- --arg metadata_url "https://..." \
- '{ "type": "saml", "metadata_url": $metadata_url, "domains": ["company.com"] }' \
- > /tmp/body.json
+supabase sso add --type saml --project-ref \
+ --metadata-url 'https://company.com/idp/saml/metadata' \
+ --domains company.com
```
If you wish to use a Metadata XML file instead, you can use:
```bash
-jq --null-input \
- -M \
- --rawfile metadata_file /path/to/metadata.xml \
- '{ "type": "saml", "metadata_xml": $metadata_file, "domains": ["company.com"] }' \
- > /tmp/body.json
+supabase sso add --type saml --project-ref \
+ --metadata-file /path/to/saml/metadata.xml \
+ --domains company.com
```
-Once you've executed the cURL command with the correct body, you should see details about the registered SAML 2.0 Identity Provider.
+This command will register a new identity provider with your project's Auth server. When successful, you will see the details of the provider such as it's SAML information and registered domains.
-To initiate a sign-in request from your front-end application you can use:
+Please note that only persons with write access to the project can register, update or remove identity providers.
+
+Once you've added an identity provider, users who have access to it can sign in to your application. With SAML 2.0 there are two ways that users can sign in to your project:
+
+- By signing-in from your application's user interface, commonly known as **SP (Service Provider) Initiated Flow**
+- By clicking on an icon in the application menu on the company intranet or identity provider page, commonly known as **Identity Provider Initiated (IdP) Flow**
+
+To initiate a sign-in request from your application's user interface (i.e. the SP Initiated Flow), you can use:
```typescript
supabase.auth.signInWithSSO({
@@ -192,11 +187,11 @@ supabase.auth.signInWithSSO({
})
```
-Which will start the sign-in process using the SSO Identity Provider registered for the `company.com` domain name. If the SSO Identity Provider does not have an associated domain name, you can use `providerId` instead.
+Calling [`signInWithSSO`](/docs/reference/javascript/auth-signinwithsso) starts the sign-in process using the identity provider registered for the `company.com` domain name. It is not required that identity providers be assigned one or multiple domain names, in which case you can use the provider's unique ID instead.
### Understanding attribute mappings
-When a user signs in using the SAML 2.0 Single Sign-On protocol, an XML document called the SAML Assertion is exchanged between the Identity Provider and Supabase Auth.
+When a user signs in using the SAML 2.0 Single Sign-On protocol, an XML document called the SAML Assertion is exchanged between the identity provider and Supabase Auth.
This assertion contains information about the user's identity and other authentication information, such as:
@@ -206,9 +201,9 @@ This assertion contains information about the user's identity and other authenti
- Department or organization
- Other attributes present in the users directory managed by the identity provider
-Other than the unique ID of the user, SAML does not make it mandatory that any other attributes appear in the assertion. Identity Providers are configured about what user information is shared with your project.
+With exception of the unique user ID, SAML does not require any other attributes in the assertion. Identity providers can be configured so that only select user information is shared with your project.
-Your project can be configured to recognize these attributes and map them into your project's database using a JSON structure. This process is called attribute mapping, and varies according to the configuration of the Identity Provider.
+Your project can be configured to recognize these attributes and map them into your project's database using a JSON structure. This process is called attribute mapping, and varies according to the configuration of the identity provider.
For example, the following JSON structure configures attribute mapping for the `email` and `first_name` user identity properties.
@@ -225,7 +220,14 @@ For example, the following JSON structure configures attribute mapping for the `
}
```
-You can include this structure in the `POST /auth/v1/admin/sso/providers` call under the `attribute_mapping` property.
+When creating or updating an identity provider with the [Supabase CLI](/docs/guides/cli) you can include this JSON as a file with the `--attribute-mapping /path/to/attribute/mapping.json` flag.
+
+For example, to change the attribute mappings to an existing provider you can use:
+
+```bash
+supabase sso update --project-ref \
+ --attribute-mapping /path/to/attribute/mapping.json
+```
Given a SAML 2.0 assertion that includes these attributes:
@@ -268,24 +270,26 @@ Supabase Auth does not require specifying attribute mappings if you only need ac
At this time it is not possible to have users without an email address, so SAML assertions without one will be rejected.
-Most SAML 2.0 identity providers use LDAP attribute names. However, due to their variability and complexity operators of Identity Providers are able to customize both the `Name` and attribute value that is sent to Supabase Auth in an assertion. Please refer to the identity provider's documentation and contact the operator for details on what attributes are mapped for your project.
+Most SAML 2.0 identity providers use Lightweight Directory Access Protocol (LDAP) attribute names. However, due to their variability and complexity operators of identity providers are able to customize both the `Name` and attribute value that is sent to Supabase Auth in an assertion. Please refer to the identity provider's documentation and contact the operator for details on what attributes are mapped for your project.
### Remove a connection
-Once a connection to an identity provider is established, you can remove it by invoking the `DELETE` method on it:
+Once a connection to an identity provider is established, you can [remove it](/docs/reference/cli/supabase-sso-remove) by running:
```bash
-curl -X DELETE \
- -H 'Content-Type: application/json' \
- -H 'apikey: ' \
- -H 'Authorization: Bearer ' \
- 'https://.supabase.co/auth/v1/admin/sso/providers/'
+supabase sso remove --project-ref
```
-Once a connection is removed, all user accounts from that identity provider will be immediately logged out. User information will remain in the system, but it will no longer be possible for any of those accounts to be accessed in the future, even if you add the connection again.
+If successful, the details of the removed identity provider will be shown. All user accounts from that identity provider will be immediately logged out. User information will remain in the system, but it will no longer be possible for any of those accounts to be accessed in the future, even if you add the connection again.
If you need to reassign those user accounts to another identity provider, please [open a support ticket](https://app.supabase.com/support/new).
+A [list of all](/docs/reference/cli/supabase-sso-list) registered identity providers can be displayed by running:
+
+```bash
+supabase sso list --project-ref
+```
+
### Update a connection
You may wish to update settings about a connection to a SAML 2.0 identity provider.
@@ -293,23 +297,69 @@ You may wish to update settings about a connection to a SAML 2.0 identity provid
Commonly this is necessary when:
- Cryptographic keys are rotated or have expired
-- Metadata URL has changed, but is the same Identity Provider
-- Other SAML 2.0 Metadata attributes have changed, but it is still the same Identity Provider
+- Metadata URL has changed, but is the same identity provider
+- Other SAML 2.0 Metadata attributes have changed, but it is still the same identity provider
- You are updating the domains or attribute mapping
-```bash
-curl -X PUT \
- -H 'Content-Type: application/json' \
- -H 'apikey: ' \
- -H 'Authorization: Bearer ' \
- --data-binary '@/tmp/body.json' \
- 'https://.supabase.co/auth/v1/admin/sso/providers/'
+You can use this command to [update](/docs/reference/cli/supabase-sso-update) the configuration of an identity provider:
+```bash
+supabase sso update --project-ref
```
-The request body has the same structure as when you're adding a connection to an Identity Provider.
+Please use `--help` to see all available flags.
-It is not possible to change the Identity Provider's unique SAML identifier known as `EntityID`. Everything else can be updated. If the SAML `EntityID` of your identity provider has changed, it is regarded as a new identity provider and you will have to register it like a new connection.
+It is not possible to change the unique SAML identifier of the identity provider, known as `EntityID`. Everything else can be updated. If the SAML `EntityID` of your identity provider has changed, it is regarded as a new identity provider and you will have to register it like a new connection.
+
+### Retrieving information about a connection
+
+You can always obtain a [list](/docs/reference/cli/supabase-sso-list) of all registered providers using:
+
+```bash
+supabase sso list --project-ref
+```
+
+This list will only include basic information about each provider. To see [all of the information](/docs/reference/cli/supabase-sso-show) about a provider you can use:
+
+```bash
+supabase sso show --project-ref
+```
+
+You can use the `-o json` flag to output the information as JSON, should you need to. Other formats may be supported, please use `--help` to see all available options.
+
+## Frequently Asked Questions
+
+### How do I publish my application to an identity provider's marketplace?
+
+Many cloud-based identity providers offer a marketplace where you can register your application for easy on-boarding with customers. When you use Supabase Auth's SAML 2.0 support you can register your project in any one of these marketplaces.
+
+Please refer to the relevant documentation for each cloud-based identity provider on how you can do this. Some common marketplaces are:
+
+- [Okta Integration Network](https://developer.okta.com/docs/guides/build-sso-integration/saml2/main/)
+- [Azure Active Directory App Gallery](https://learn.microsoft.com/en-us/azure/active-directory-b2c/publish-app-to-azure-ad-app-gallery)
+- [Google Workspaces Pre-integrated SAML apps catalog](https://support.google.com/a/table/9217027)
+
+### Why do some users get: SAML Assertion does not contain email address?
+
+Identity providers do not have to send back and email address for the user, though they often do. Supabase Auth requires that an email address is present.
+
+The following list of commonly used SAML attribute names is inspected, in order of appearance, to discover the email address in the assertion:
+
+- `urn:oid:0.9.2342.19200300.100.1.3`
+- `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`
+- `http://schemas.xmlsoap.org/claims/EmailAddress`
+- `mail`
+- `email`
+
+Finally if there is no such attribute, it will use the SAML `NameID` value but only if the format is advertised as `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`.
+
+Should you run into this problem, it is most likely a misconfiguration issue **on the identity provider side.** Please instruct your contact at the company to map the user's email address to one of the above listed attribute names, typically `email`.
+
+### How do I access the private key used for SAML in my project?
+
+At this time it is not possible to extract the RSA private key used by your project's Supabase Auth server. This is done to keep the private key as secure as possible, given that SAML does not offer an easy way to rotate keys without disrupting service. (Please use a SAML 2.0 Metadata URL whenever possible for this reason!)
+
+If you really need access to the key, please [open a support ticket](https://app.supabase.com/support/new) and we'll try to support you as best as possible.
export const Page = ({ children }) =>
diff --git a/apps/docs/pages/guides/cli/local-development.mdx b/apps/docs/pages/guides/cli/local-development.mdx
index 5438b2e941c..ca38587e786 100644
--- a/apps/docs/pages/guides/cli/local-development.mdx
+++ b/apps/docs/pages/guides/cli/local-development.mdx
@@ -9,7 +9,7 @@ export const meta = {
Supabase is a flexible platform that lets you decide how you want to build your projects. You can use the Dashboard directly to get up and running quickly, or use a proper local setup. We suggest you work locally and deploy your changes to a linked project on the [Supabase Platform](https://app.supabase.io/).
-Doing things directly on the platform via the [Dashboard](https://app.supabase.io/) is fine when you're getting started, but it's a good idea to move to a proper local workflow before you get too far. Working locally, generating migrations as you change your tables, and appling those migrations to a linked project on the [Platform](https://app.supabase.io/) keeps everything nicely organized as you grow.
+Doing things directly on the platform via the [Dashboard](https://app.supabase.io/) is fine when you're getting started, but it's a good idea to move to a proper local workflow before you get too far. Working locally, generating migrations as you change your tables, and applying those migrations to a linked project on the [Platform](https://app.supabase.io/) keeps everything nicely organized as you grow.
## Why develop locally?
@@ -23,7 +23,7 @@ The Dashboard provides a wide range of features for setting up your project: cre
4. **Configuration in code**: If you directly change your tables via the Dashboard, none of that gets captured in code. If you follow these local development practices, you'll store all of your table schemas in code.
-5. **Work offline**: Need to work from a train? A plain? An automobile? No problem. Developing your project locally allows you to work offline.
+5. **Work offline**: Need to work from a train? A plane? An automobile? No problem. Developing your project locally allows you to work offline.