diff --git a/.gitignore b/.gitignore index 21a99fc3ccd..791321540e4 100644 --- a/.gitignore +++ b/.gitignore @@ -126,3 +126,7 @@ apps/new-docs/* packages/ui/styles/tokens packages/ui/tokens.json + +# Google cloud + +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/Navigation/NavBar.tsx b/apps/docs/components/Navigation/NavBar.tsx deleted file mode 100644 index eb7ee10434f..00000000000 --- a/apps/docs/components/Navigation/NavBar.tsx +++ /dev/null @@ -1,207 +0,0 @@ -import { useTheme } from 'common/Providers' -import Image from 'next/image' -import Link from 'next/link' -import { useRouter } from 'next/router' -import { FC, useEffect, useState } from 'react' -import { IconCommand, IconMenu, IconMoon, IconSearch, IconSun, Listbox, SearchButton } from 'ui' -import { REFERENCES } from './Navigation.constants' - -import { getPageType } from '~/lib/helpers' - -const NavBar: FC = () => { - const { isDarkMode, toggleTheme } = useTheme() - const [mounted, setMounted] = useState(false) - const [mobileMenuOpen, setMobileMenuOpen] = useState(false) - - const { asPath, push } = useRouter() - const pathSegments = asPath.split('/') - - const library = pathSegments.length >= 3 ? pathSegments[2] : undefined - const libraryMeta = REFERENCES?.[library] ?? undefined - const versions = libraryMeta?.versions ?? [] - - const version = versions.includes(pathSegments[pathSegments.indexOf(library) + 1]) - ? pathSegments[pathSegments.indexOf(library) + 1] - : versions[0] - - const pageType = getPageType(asPath) - - useEffect(() => { - setMounted(true) - }, [isDarkMode]) - - const pageLinks = [ - { text: 'Guides', key: 'docs', link: '/' }, - { text: 'Reference', key: 'reference', link: '/reference' }, - ] - - const onSelectVersion = (version: string) => { - // [Joshen] Ideally we use but this works for now - if (!library) return - if (version === versions[0]) { - push(`/reference/${library}`) - } else { - push(`/reference/${library}/${version}`) - } - } - - // [Joshen] Kaizen: Use UI library's SidePanel for this - const toggleMobileMenu = () => { - setMobileMenuOpen(!mobileMenuOpen) - const sidebar = document.querySelector('.sidebar-menu-container') - const contentPane = document.querySelector('.main-content-pane') - - sidebar.classList.toggle('hidden') - contentPane.classList.toggle('hidden') - } - - return ( - - ) -} -export default NavBar diff --git a/apps/docs/components/Navigation/Navigation.constants.ts b/apps/docs/components/Navigation/Navigation.constants.ts deleted file mode 100644 index 5a89f426a91..00000000000 --- a/apps/docs/components/Navigation/Navigation.constants.ts +++ /dev/null @@ -1,431 +0,0 @@ -// [Terry] Also need to look at getPageType() in ./lib/helpers -// to set a menu to a page -import SupabaseJsV1Nav from 'data/nav/supabase-js/v1' -import SupabaseJsV2Nav from 'data/nav/supabase-js/v2' -import SupabaseDartV0Nav from 'data/nav/supabase-dart/v0' -import SupabaseDartV1Nav from 'data/nav/supabase-dart/v1' -import SupabaseCLINav from 'data/nav/supabase-cli' -import SupabaseAPINav from 'data/nav/supabase-api' -import AuthServerNav from 'data/nav/auth-server' -import RealtimeServerNav from 'data/nav/realtime-server' -import StorageServerNav from 'data/nav/storage-server' - -import { NavMenu, References } from './Navigation.types' - -export const REFERENCES: References = { - javascript: { - name: 'supabase-js', - library: 'supabase-js', - versions: ['v2', 'v1'], - icon: '/docs/img/icons/javascript-icon.svg', - }, - dart: { - name: 'Flutter', - library: 'supabase-dart', - versions: ['v1', 'v0'], - icon: '/docs/img/icons/flutter-icon.svg', - }, - cli: { - name: 'CLI', - library: undefined, - versions: [], - icon: '/docs/img/icons/cli-icon.svg', - }, - api: { - name: 'API', - library: undefined, - versions: [], - icon: '/docs/img/icons/api-icon.svg', - }, -} - -export const menuItems: NavMenu = { - docs: [ - { - label: 'Overview', - items: [ - { name: 'Introduction', url: '/', items: [] }, - { name: 'Features', url: '/features', items: [] }, - { name: 'Architecture', url: '/architecture', items: [] }, - ], - }, - { - label: 'Quickstarts', - items: [ - { name: 'Angular', url: '/guides/with-angular', items: [] }, - { name: 'Expo', url: '/guides/with-expo', items: [] }, - { name: 'Flutter', url: '/guides/with-flutter', items: [] }, - { name: 'Ionic Angular', url: '/guides/with-ionic-angular', items: [] }, - { name: 'Ionic React', url: '/guides/with-ionic-react', items: [] }, - { name: 'Ionic Vue', url: '/guides/with-ionic-vue', items: [] }, - { name: 'Next.js', url: '/guides/with-nextjs', items: [] }, - { name: 'Nuxt 3', url: '/guides/with-nuxt-3', items: [] }, - { name: 'React', url: '/guides/with-react', items: [] }, - { name: 'RedwoodJS', url: '/guides/with-redwoodjs', items: [] }, - { name: 'SolidJS', url: '/guides/with-solidjs', items: [] }, - { name: 'Svelte', url: '/guides/with-svelte', items: [] }, - { name: 'SvelteKit', url: '/guides/with-sveltekit', items: [] }, - { name: 'Vue 3', url: '/guides/with-vue-3', items: [] }, - ], - }, - { - label: 'CLI', - items: [ - { name: 'Overview', url: '/guides/cli', items: [] }, - { name: 'Local Development', url: '/guides/cli/local-development', items: [] }, - { name: 'Managing Environments', url: '/guides/cli/managing-environments', items: [] }, - ], - }, - { - label: 'Auth', - items: [ - { name: 'Overview', url: '/guides/auth', items: [] }, - { name: 'Quickstarts', url: '/guides/auth/quickstarts/react', items: [] }, - { - name: 'Authentication', - url: undefined, - items: [ - { name: 'Login with Email', url: '/guides/auth/auth-email', items: [] }, - { name: 'Login with Magic Link', url: '/guides/auth/auth-magic-link', items: [] }, - { name: 'Login with Apple', url: '/guides/auth/auth-apple', items: [] }, - { name: 'Login with Azure', url: '/guides/auth/auth-azure', items: [] }, - { name: 'Login with Bitbucket', url: '/guides/auth/auth-bitbucket', items: [] }, - { name: 'Login with Discord', url: '/guides/auth/auth-discord', items: [] }, - { name: 'Login with Facebook', url: '/guides/auth/auth-facebook', items: [] }, - { name: 'Login with Github', url: '/guides/auth/auth-github', items: [] }, - { name: 'Login with Gitlab', url: '/guides/auth/auth-gitlab', items: [] }, - { name: 'Login with Google', url: '/guides/auth/auth-google', items: [] }, - { name: 'Login with Keycloak', url: '/guides/auth/auth-keycloak', items: [] }, - { name: 'Login with LinkedIn', url: '/guides/auth/auth-linkedin', items: [] }, - { name: 'Login with Notion', url: '/guides/auth/auth-notion', items: [] }, - { name: 'Login with Slack', url: '/guides/auth/auth-slack', items: [] }, - { name: 'Login with Spotify', url: '/guides/auth/auth-spotify', items: [] }, - { name: 'Login with Twitch', url: '/guides/auth/auth-twitch', items: [] }, - { name: 'Login with Twitter', url: '/guides/auth/auth-twitter', items: [] }, - { name: 'Login with WorkOS', url: '/guides/auth/auth-workos', items: [] }, - { name: 'Login with Zoom', url: '/guides/auth/auth-zoom', items: [] }, - { name: 'Phone Auth with Twilio', url: '/guides/auth/auth-twilio', items: [] }, - { name: 'Phone Auth with Vonage', url: '/guides/auth/auth-vonage', items: [] }, - { - name: 'Phone Auth with MessageBird', - url: '/guides/auth/auth-messagebird', - items: [], - }, - ], - }, - { - name: 'Authorization', - url: undefined, - items: [ - { name: 'Row Level Security', url: '/guides/auth/row-level-security', items: [] }, - { name: 'Managing User Data', url: '/guides/auth/managing-user-data', items: [] }, - { name: 'Enable Captcha Protection', url: '/guides/auth/auth-captcha', items: [] }, - { name: 'Server-side Rendering', url: '/guides/auth/server-side-rendering', items: [] }, - { name: 'Multi-Factor Authentication', url: '/guides/auth/auth-mfa', items: [] }, - ], - }, - { - name: 'Auth Helpers', - url: undefined, - items: [ - { name: 'Overview', url: '/guides/auth/auth-helpers', items: [] }, - { name: 'Auth UI', url: '/guides/auth/auth-helpers/auth-ui', items: [] }, - { name: 'Next.js', url: '/guides/auth/auth-helpers/nextjs', items: [] }, - { - name: 'Next.js Server Components', - url: '/guides/auth/auth-helpers/nextjs-server-components', - items: [], - }, - { name: 'SvelteKit', url: '/guides/auth/auth-helpers/sveltekit', items: [] }, - { name: 'Remix', url: '/guides/auth/auth-helpers/remix', items: [] }, - ], - }, - { - name: 'Deep Dive', - url: undefined, - items: [ - { - name: 'Part One: JWTs', - url: '/learn/auth-deep-dive/auth-deep-dive-jwts', - items: [], - }, - { - name: 'Part Two: Row Level Security', - url: '/learn/auth-deep-dive/auth-row-level-security', - items: [], - }, - { name: 'Part Three: Policies', url: '/learn/auth-deep-dive/auth-policies', items: [] }, - { name: 'Part Four: GoTrue', url: '/learn/auth-deep-dive/auth-gotrue', items: [] }, - { - name: 'Part Five: Google OAuth', - url: '/learn/auth-deep-dive/auth-google-oauth', - items: [], - }, - ], - }, - ], - }, - { - label: 'Database', - items: [ - { name: 'Overview', url: '/guides/database', items: [] }, - { name: 'Database Connections', url: '/guides/database/connecting-to-postgres', items: [] }, - { name: 'Tables and Data', url: '/guides/database/tables', items: [] }, - { name: 'Database Functions', url: '/guides/database/functions', items: [] }, - { name: 'Database Webhooks', url: '/guides/database/webhooks', items: [] }, - { name: 'Full Text Search', url: '/guides/database/full-text-search', items: [] }, - { name: 'Database Testing', url: '/guides/database/testing', items: [] }, - { - name: 'Extensions', - url: undefined, - items: [ - { name: 'Overview', url: '/guides/database/extensions', items: [] }, - { name: 'http: RESTful Client', url: '/guides/database/extensions/http', items: [] }, - { - name: 'pg_cron: Job Scheduling', - url: '/guides/database/extensions/pgcron', - items: [], - }, - { - name: 'pg_net: Async Networking', - url: '/guides/database/extensions/pgnet', - items: [], - }, - { name: 'pgTAP: Unit Testing', url: '/guides/database/extensions/pgtap', items: [] }, - { - name: 'plv8: Javascript Language', - url: '/guides/database/extensions/plv8', - items: [], - }, - { - name: 'PostGIS: Geo queries', - url: '/guides/database/extensions/postgis', - items: [], - }, - { - name: 'uuid-ossp: Unique Identifiers', - url: '/guides/database/extensions/uuid-ossp', - items: [], - }, - ], - }, - { - name: 'Configuration', - url: undefined, - items: [ - { name: 'Timeouts', url: '/guides/database/timeouts', items: [] }, - { name: 'Replication', url: '/guides/database/replication', items: [] }, - { name: 'Passwords', url: '/guides/database/managing-passwords', items: [] }, - { name: 'Timezones', url: '/guides/database/managing-timezones', items: [] }, - ], - }, - ], - }, - { - label: 'Serverless APIs', - items: [ - { name: 'Overview', url: '/guides/api', items: [] }, - { name: 'Generating Types', url: '/guides/api/generating-types', items: [] }, - ], - }, - { - label: 'Edge Functions', - items: [ - { name: 'Overview', url: '/guides/functions', items: [] }, - { name: 'Quickstart', url: '/guides/functions/quickstart', items: [] }, - { name: 'Auth', url: '/guides/functions/auth', items: [] }, - { name: 'Best Practices', url: '/guides/functions/best-practices', items: [] }, - { name: 'CI/CD Workflow', url: '/guides/functions/cicd-workflow', items: [] }, - ], - }, - { - label: 'Realtime', - items: [ - { - name: 'Overview', - url: '/guides/realtime', - items: [], - }, - { - name: 'Quickstart', - url: '/guides/realtime/quickstart', - items: [], - }, - { - name: 'Features', - url: undefined, - items: [ - { name: 'Channels', url: '/guides/realtime/channels', items: [] }, - { - name: 'Extensions', - url: '/guides/realtime/extensions', - items: [ - { name: 'Broadcast', url: '/guides/realtime/broadcast', items: [] }, - { name: 'Presence', url: '/guides/realtime/presence', items: [] }, - { name: 'Postgres Changes', url: '/guides/realtime/postgres-changes', items: [] }, - ], - }, - ], - }, - { - name: 'Guides', - url: undefined, - items: [ - { - name: 'Subscribing to Database Changes', - url: '/guides/realtime/subscribing-to-database-changes', - items: [], - }, - { - name: 'Bring Your Own Database', - url: '/guides/realtime/bring-your-own-database', - items: [], - }, - { - name: 'Using Realtime with Next.js', - url: '/guides/realtime/realtime-with-nextjs', - items: [], - }, - ], - }, - { - name: 'Deep dive', - url: undefined, - items: [ - { name: 'Rate Limits', url: '/guides/realtime/rate-limits', items: [] }, - { name: 'Architecture', url: '/guides/realtime/architecture', items: [] }, - { name: 'Protocol', url: '/guides/realtime/protocol', items: [] }, - ], - }, - ], - }, - { - label: 'Storage', - items: [ - { name: 'Overview', url: '/guides/storage', items: [] }, - { name: 'Quickstart', url: '/guides/storage/quickstart', items: [] }, - { name: 'Access Control', url: '/guides/storage/access-control', items: [] }, - { name: 'CDN', url: '/guides/storage/cdn', items: [] }, - { name: 'Image Transformations', url: '/guides/storage/image-transformations', items: [] }, - ], - }, - { - label: 'Platform', - items: [ - { name: 'Overview', url: '/guides/platform', items: [] }, - { name: 'Compute Add-ons', url: '/guides/platform/compute-add-ons', items: [] }, - { name: 'Custom Domains', url: '/guides/platform/custom-domains', items: [] }, - { name: 'Database Usage', url: '/guides/platform/database-usage', items: [] }, - { name: 'HTTP Status Codes', url: '/guides/platform/http-status-codes', items: [] }, - { name: 'Logging', url: '/guides/platform/logs', items: [] }, - { name: 'Metrics', url: '/guides/platform/metrics', items: [] }, - { - name: 'Migrating and upgrading', - url: '/guides/platform/migrating-and-upgrading-projects', - items: [], - }, - { name: 'Network Restrictions', url: '/guides/platform/network-restrictions', items: [] }, - { name: 'Performance Tuning', url: '/guides/platform/performance', items: [] }, - { name: 'Permissions', url: '/guides/platform/permissions', items: [] }, - { name: 'Production Readiness', url: '/guides/platform/going-into-prod', items: [] }, - { name: 'SSL Enforcement', url: '/guides/platform/ssl-enforcement', items: [] }, - { name: 'Troubleshooting', url: '/guides/platform/troubleshooting', items: [] }, - ], - }, - { - label: 'Self Hosting', - items: [ - { name: 'Overview', url: '/guides/hosting/overview', items: [] }, - { name: 'Docker', url: '/guides/hosting/docker', items: [] }, - ], - }, - { - label: 'Migrate to Supabase', - items: [ - { name: 'Firebase Auth', url: '/guides/migrations/firebase-auth', items: [] }, - { name: 'Firestore Data', url: '/guides/migrations/firestore-data', items: [] }, - { name: 'Firebase Storage', url: '/guides/migrations/firebase-storage', items: [] }, - { name: 'Heroku', url: '/guides/migrations/heroku', items: [] }, - ], - }, - { - label: 'Integrations', - items: [ - { name: 'Supabase Marketplace', url: '/guides/integrations/integrations', items: [] }, - { - name: 'Auth', - url: undefined, - items: [ - { name: 'Auth0', url: '/guides/integrations/auth0', items: [] }, - { name: 'Authsignal', url: '/guides/integrations/authsignal', items: [] }, - { name: 'Clerk', url: '/guides/integrations/clerk', items: [] }, - { name: 'keyri', url: '/guides/integrations/keyri', items: [] }, - { name: 'Picket', url: '/guides/integrations/picket', items: [] }, - { name: 'Stytch', url: '/guides/integrations/stytch', items: [] }, - { name: 'SuperTokens', url: '/guides/integrations/supertokens', items: [] }, - ], - }, - { - name: 'Caching / Offline-first', - url: undefined, - items: [{ name: 'Polyscale', url: '/guides/integrations/polyscale', items: [] }], - }, - { - name: 'Developer Tools', - url: undefined, - items: [ - { name: 'Estuary', url: '/guides/integrations/estuary', items: [] }, - { name: 'pgMustard', url: '/guides/integrations/pgmustard', items: [] }, - { name: 'Prisma', url: '/guides/integrations/prisma', items: [] }, - { name: 'Sequin', url: '/guides/integrations/sequin', items: [] }, - { name: 'Snaplet', url: '/guides/integrations/snaplet', items: [] }, - { name: 'Vercel', url: '/guides/integrations/vercel', items: [] }, - { name: 'Zuplo', url: '/guides/integrations/zuplo', items: [] }, - ], - }, - { - name: 'Low-code', - url: undefined, - items: [ - { name: 'Appsmith', url: '/guides/integrations/appsmith', items: [] }, - { name: 'DhiWise', url: '/guides/integrations/dhiwise', items: [] }, - { name: 'Directus', url: '/guides/integrations/directus', items: [] }, - { name: 'Draftbit', url: '/guides/integrations/draftbit', items: [] }, - { name: 'Plasmic', url: '/guides/integrations/plasmic', items: [] }, - { name: 'WeWeb', url: '/guides/integrations/weweb', items: [] }, - { name: 'ILLA', url: '/guides/integrations/illa', items: [] }, - ], - }, - ], - }, - ], - reference: [ - { - label: 'Official', - items: [ - { name: 'Reference Documentation', url: '/reference', items: [] }, - { name: 'Supabase JavaScript Library', url: '/reference/javascript', items: [] }, - { name: 'Supabase Flutter Library', url: '/reference/dart', items: [] }, - { name: 'Supabase CLI', url: '/reference/cli', items: [] }, - { name: 'Management API', url: '/reference/api', items: [] }, - ], - }, - { - label: 'Self-hosting', - items: [ - { name: 'Auth Server', url: '/reference/auth', items: [] }, - { name: 'Realtime Server', url: '/reference/realtime', items: [] }, - { name: 'Storage Server', url: '/reference/storage', items: [] }, - ], - }, - ], - 'reference/javascript': SupabaseJsV2Nav, - 'reference/javascript/v1': SupabaseJsV1Nav, - 'reference/dart': SupabaseDartV1Nav, - 'reference/dart/v0': SupabaseDartV0Nav, - 'reference/cli': SupabaseCLINav, - 'reference/api': SupabaseAPINav, - 'reference/auth': AuthServerNav, - 'reference/realtime': RealtimeServerNav, - 'reference/storage': StorageServerNav, -} diff --git a/apps/docs/components/Navigation/NavigationMenu/HomeMenu.tsx b/apps/docs/components/Navigation/NavigationMenu/HomeMenu.tsx index 1798c82798d..db93e1616a2 100644 --- a/apps/docs/components/Navigation/NavigationMenu/HomeMenu.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/HomeMenu.tsx @@ -115,6 +115,13 @@ const home = [ level: 'reference_csharp', community: true, }, + { + label: 'Swift', + icon: '/img/icons/menu/reference-swift', + href: '/reference/swift/introduction', + level: 'reference_swift', + community: true, + }, { label: 'Tools', }, diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts index 8b88fe60fa9..c4739ffc3ab 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts @@ -1,13 +1,4 @@ -// import SupabaseJsV1Nav from 'data/nav/supabase-js/v1' -// import SupabaseJsV2Nav from 'data/nav/supabase-js/v2' -// import SupabaseDartV0Nav from 'data/nav/supabase-dart/v0' -// import SupabaseDartV1Nav from 'data/nav/supabase-dart/v1' -// import SupabaseCLINav from 'data/nav/supabase-cli' -// import SupabaseAPINav from 'data/nav/supabase-api' -// import AuthServerNav from 'data/nav/auth-server' -// import StorageServerNav from 'data/nav/storage-server' - -import { NavMenu, References } from '../Navigation.types' +import { References } from '../Navigation.types' export const REFERENCES: References = { javascript: { @@ -28,6 +19,12 @@ export const REFERENCES: References = { versions: ['v0'], icon: '/docs/img/libraries/c-sharp-icon.svg', }, + swift: { + name: 'Swift', + library: 'supabase-swift', + versions: ['v1'], + icon: '/docs/img/libraries/swift-icon.svg', + }, cli: { name: 'CLI', library: undefined, @@ -48,12 +45,13 @@ export const gettingstarted = { items: [ { name: 'Features', url: '/guides/getting-started/features' }, { name: 'Architecture', url: '/guides/getting-started/architecture' }, - { name: 'Local Development', url: '/guides/cli/local-development' }, + // { name: 'Local Development', url: '/guides/cli/local-development' }, // Disabling this until we actually move the doc into this section { name: 'Framework Quickstarts', items: [ { name: 'React', url: '/guides/getting-started/quickstarts/reactjs' }, { name: 'NextJS', url: '/guides/getting-started/quickstarts/nextjs' }, + { name: 'RedwoodJS', url: '/guides/getting-started/quickstarts/redwoodjs' }, { name: 'Flutter', url: '/guides/getting-started/quickstarts/flutter' }, { name: 'SvelteKit', url: '/guides/getting-started/quickstarts/sveltekit' }, { name: 'SolidJS', url: '/guides/getting-started/quickstarts/solidjs' }, @@ -127,6 +125,15 @@ export const gettingstarted = { }, ], }, + { + name: 'AI & ML', + items: [ + { + name: 'Vector Search with OpenAI', + url: '/guides/getting-started/openai/vector-search', + }, + ], + }, ], } @@ -284,7 +291,7 @@ export const auth = { url: '/guides/auth/enterprise-sso', items: [ { - name: 'SAML 2.0 (Beta)', + name: 'SAML 2.0', url: '/guides/auth/sso/auth-sso-saml', }, ], @@ -309,9 +316,9 @@ export const auth = { items: [ { name: 'Overview', url: '/guides/auth/auth-helpers' }, { name: 'Auth UI', url: '/guides/auth/auth-helpers/auth-ui' }, - { name: 'Next.js', url: '/guides/auth/auth-helpers/nextjs' }, + { name: 'Next.js (pages)', url: '/guides/auth/auth-helpers/nextjs' }, { - name: 'Next.js Server Components', + name: 'Next.js (app)', url: '/guides/auth/auth-helpers/nextjs-server-components', }, { name: 'Remix', url: '/guides/auth/auth-helpers/remix' }, @@ -795,6 +802,11 @@ export const resources = { name: 'Render', url: '/guides/resources/migrating-to-supabase/render', }, + { + name: 'Amazon RDS', + url: '/guides/resources/migrating-to-supabase/amazon-rds', + items: [], + }, ], }, ], @@ -828,6 +840,13 @@ export const self_hosting = { { name: 'Configuration', url: '/guides/self-hosting/realtime/config' }, ], }, + { + name: 'Analytics Server', + items: [ + { name: 'Reference', url: '/reference/self-hosting-analytics/introduction', items: [] }, + { name: 'Configuration', url: '/guides/self-hosting/analytics/config', items: [] }, + ], + }, ], } @@ -840,6 +859,7 @@ export const migrate = { { name: 'Firebase Storage', url: '/guides/migrations/firebase-storage' }, { name: 'Heroku', url: '/guides/migrations/heroku' }, { name: 'Render', url: '/guides/migrations/render' }, + { name: 'Amazon RDS', url: '/guides/migrations/amazon-rds' }, ], } @@ -937,6 +957,13 @@ export const reference = { level: 'reference_python', icon: '/img/icons/menu/reference-python', }, + { + name: 'supbase-swift', + url: '/reference/swift/start', + level: 'reference_swift', + items: [], + icon: '/img/icons/menu/reference-swift', + }, // { // name: 'supabase-python', // url: '/reference/python/start', @@ -1006,6 +1033,13 @@ export const reference_python_v2 = { parent: '/reference', } +export const reference_swift_v1 = { + icon: 'reference-swift', + title: 'swift', + url: 'guides/reference/swift', + parent: '/reference', +} + export const reference_cli = { icon: 'reference-cli', title: 'Supabase CLI', @@ -1034,12 +1068,19 @@ export const reference_self_hosting_storage = { } export const reference_self_hosting_realtime = { - icon: 'reference-auth', + icon: 'reference-realtime', title: 'Self-Hosting Realtime', url: '/guides/reference/self-hosting/realtime', parent: '/reference', } +export const reference_self_hosting_analytics = { + icon: 'reference-analytics', + title: 'Self-Hosting Analytics', + url: '/guides/reference/self-hosting/analytics', + parent: '/reference', +} + // export const reference: [ // { // label: 'Official' @@ -1106,6 +1147,13 @@ export const references = [ icon: '/docs/img/icons/c-sharp-icon.svg', url: '/reference/csharp/start', }, + { + label: 'supabase-swift', + versions: ['v1'], + description: 'something about the reference', + icon: '/docs/img/icons/swift-icon.svg', + url: '/reference/swift/start', + }, ], }, { diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.tsx b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.tsx index 0b481973cb8..945d817abcf 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.tsx @@ -15,6 +15,8 @@ import spec_dart_v0 from '~/../../spec/supabase_dart_v0.yml' assert { type: 'yml import spec_csharp_v0 from '~/../../spec/supabase_csharp_v0.yml' assert { type: 'yml' } // @ts-expect-error import spec_python_v2 from '~/../../spec/supabase_py_v2.yml' assert { type: 'yml' } +// @ts-expect-error +import spec_swift_v1 from '~/../../spec/supabase_swift_v1.yml' assert { type: 'yml' } // import { gen_v3 } from '~/lib/refGenerator/helpers' import apiCommonSections from '~/../../spec/common-api-sections.json' @@ -22,6 +24,7 @@ import cliCommonSections from '~/../../spec/common-cli-sections.json' import libCommonSections from '~/../../spec/common-client-libs-sections.json' import authServerCommonSections from '~/../../spec/common-self-hosting-auth-sections.json' import realtimeServerCommonSections from '~/../../spec/common-self-hosting-realtime-sections.json' +import analyticsServerCommonSections from '~/../../spec/common-self-hosting-analytics-sections.json' import storageServerCommonSections from '~/../../spec/common-self-hosting-storage-sections.json' import { flattenSections } from '~/lib/helpers' import NavigationMenuHome from './HomeMenu' @@ -54,22 +57,26 @@ export type RefIdOptions = | 'reference_dart_v1' | 'reference_csharp_v0' | 'reference_python_v2' + | 'reference_swift_v1' | 'reference_cli' | 'reference_api' | 'reference_self_hosting_auth' | 'reference_self_hosting_storage' | 'reference_self_hosting_realtime' + | 'reference_self_hosting_analytics' export type RefKeyOptions = | 'javascript' | 'dart' | 'csharp' | 'python' + | 'swift' | 'cli' | 'api' | 'self-hosting-auth' | 'self-hosting-storage' | 'self-hosting-realtime' + | 'self-hosting-analytics' const NavigationMenu = () => { const router = useRouter() @@ -135,10 +142,14 @@ const NavigationMenu = () => { case url.includes(`/docs/reference/csharp`) && url: menuState.setMenuLevelId('reference_csharp_v0') break - // puthon v2 (latest) + // python v2 (latest) case url.includes(`/docs/reference/python`) && url: menuState.setMenuLevelId('reference_python_v2') break + // swift v1 (latest) + case url.includes(`/docs/reference/swift`) && url: + menuState.setMenuLevelId('reference_swift_v1') + break case url.includes(`/docs/reference/cli/config`) && url: menuState.setMenuLevelId('supabase_cli') break @@ -157,6 +168,9 @@ const NavigationMenu = () => { case url.includes(`/docs/reference/self-hosting-realtime`) && url: menuState.setMenuLevelId('reference_self_hosting_realtime') break + case url.includes(`/docs/reference/self-hosting-analytics`) && url: + menuState.setMenuLevelId('reference_self_hosting_analytics') + break default: break @@ -195,11 +209,13 @@ const NavigationMenu = () => { const isReference_Dart_V1 = 'reference_dart_v1' === level const isReference_Csharp_V0 = 'reference_csharp_v0' === level const isReference_Python_V2 = 'reference_python_v2' === level + const isReference_Swift_V1 = 'reference_swift_v1' === level const isReference_Cli = 'reference_cli' === level const isReference_Api = 'reference_api' === level const isReference_Self_Hosting_Auth = 'reference_self_hosting_auth' === level const isReference_Self_Hosting_Storage = 'reference_self_hosting_storage' === level const isReference_Self_Hosting_Realtime = 'reference_self_hosting_realtime' === level + const isReference_Self_Hosting_Analytics = 'reference_self_hosting_analytics' === level return (
@@ -263,7 +279,14 @@ const NavigationMenu = () => { lib="csharp" spec={spec_csharp_v0} /> - + { commonSections={realtimeServerCommonSections} lib="self-hosting-realtime" /> +
) } diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuCliList.tsx b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuCliList.tsx index e4a7eb5c8f7..cae120747b8 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuCliList.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuCliList.tsx @@ -86,7 +86,7 @@ const NavigationMenuCliList = ({ currentLevel, setLevel, id }) => { return (
= ({ id, active, value }) => { type={value ? 'multiple' : 'single'} value={value ?? firstLevelRoute} className={[ - 'transition-all ml-8 duration-150 ease-out', + 'transition-all duration-150 ease-out', // enabled active && 'opacity-100 ml-0 delay-150', // level === 'home' && 'ml-12', diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx index 285c63bcf09..22a7d049827 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx @@ -4,7 +4,6 @@ import Link from 'next/link' import { useRouter } from 'next/router' import React from 'react' import { IconChevronLeft } from '~/../../packages/ui' -import * as NavItems from './NavigationMenu.constants' import * as Accordion from '@radix-ui/react-accordion' const HeaderImage = React.memo(function HeaderImage(props: any) { diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuRefList.tsx b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuRefList.tsx index d3c527b8032..58bd5b7f9a2 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuRefList.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuRefList.tsx @@ -32,7 +32,7 @@ const NavigationMenuRefList: React.FC = ({ return (
{ const { isDarkMode, toggleTheme } = useTheme() @@ -33,17 +31,10 @@ const TopNavBar: FC = () => { ? pathSegments[pathSegments.indexOf(library) + 1] : versions[0] - const pageType = getPageType(asPath) - useEffect(() => { setMounted(true) }, [isDarkMode]) - const pageLinks = [ - { text: 'Guides', key: 'docs', link: '/' }, - { text: 'Reference', key: 'reference', link: '/reference' }, - ] - const onSelectVersion = (version: string) => { // [Joshen] Ideally we use but this works for now if (!library) return diff --git a/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx b/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx index 7501f116c2a..6a56ee7d544 100644 --- a/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx @@ -4,9 +4,9 @@ import Link from 'next/link' import { useRouter } from 'next/router' import { FC, useEffect, useState } from 'react' import { Button, IconCommand, IconGitHub, IconMoon, IconSearch, IconSun, SearchButton } from 'ui' -import { REFERENCES } from '~/components/Navigation/Navigation.constants' import { getPageType } from '~/lib/helpers' +import { REFERENCES } from './NavigationMenu.constants' const TopNavBarRef: FC = () => { const { isDarkMode, toggleTheme } = useTheme() @@ -126,16 +126,15 @@ const TopNavBarRef: FC = () => { Dashboard
  • diff --git a/apps/docs/components/Navigation/SideBar.tsx b/apps/docs/components/Navigation/SideBar.tsx index d6ffa3473b9..d679b7c7414 100644 --- a/apps/docs/components/Navigation/SideBar.tsx +++ b/apps/docs/components/Navigation/SideBar.tsx @@ -2,7 +2,8 @@ import Link from 'next/link' import Image from 'next/image' import { useRouter } from 'next/router' import { IconChevronRight, IconArrowLeft } from '~/../../packages/ui' -import { REFERENCES } from './Navigation.constants' +import { REFERENCES } from './NavigationMenu/NavigationMenu.constants' + import { NavMenuGroup, NavMenuSection } from './Navigation.types' import * as Accordion from '@radix-ui/react-accordion' diff --git a/apps/docs/components/reference/CLICommandSection.tsx b/apps/docs/components/reference/CLICommandSection.tsx index d20c1db8086..f25d32e74cf 100644 --- a/apps/docs/components/reference/CLICommandSection.tsx +++ b/apps/docs/components/reference/CLICommandSection.tsx @@ -14,6 +14,8 @@ export type Flag = { default_value: string accepted_values: AcceptedValue[] required?: boolean + /** Whether subcommands inherit this flag. */ + inherit?: boolean } export type AcceptedValue = { @@ -46,6 +48,14 @@ export type Command = { const CliCommandSection = (props) => { const command = spec.commands.find((x: any) => x.id === props.funcData.id) + const parentCommand = spec.commands.find( + (x: any) => x.subcommands && x.subcommands.find((y: any) => y === props.funcData.id) + ) + + const commandFlags = [ + ...(parentCommand?.flags?.filter((x: any) => x.inherit) || []), + ...command.flags, + ] return ( { )} - {command.subcommands.length > 0 && ( + {command.subcommands?.length > 0 && (

    Available Commands

      @@ -96,11 +106,11 @@ const CliCommandSection = (props) => {
    )} - {command.flags.length > 0 && ( + {commandFlags.length > 0 && ( <>

    Flags

      - {command.flags.map((flag: Flag) => ( + {commandFlags.map((flag: Flag) => ( <>
    • 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. +

+
diff --git a/apps/docs/docs/ref/self-hosting-analytics/introduction.mdx b/apps/docs/docs/ref/self-hosting-analytics/introduction.mdx new file mode 100644 index 00000000000..ccf1ee1c932 --- /dev/null +++ b/apps/docs/docs/ref/self-hosting-analytics/introduction.mdx @@ -0,0 +1,168 @@ +--- +id: introduction +title: Introduction +hideTitle: true +--- + +
+ +
+

Self-Hosting Analytics

+
+
+ + + + +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 f3be981a2c0..035bc004a0d 100644 --- a/apps/docs/layouts/SiteLayout.tsx +++ b/apps/docs/layouts/SiteLayout.tsx @@ -38,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', @@ -86,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', @@ -106,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() { @@ -302,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/package.json b/apps/docs/package.json index 2539deda7b3..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", @@ -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 50e062e2c9c..09059df64c5 100644 --- a/apps/docs/pages/_app.tsx +++ b/apps/docs/pages/_app.tsx @@ -30,7 +30,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, @@ -43,7 +43,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) { /* * handle telemetry */ - telemetry(url) + handlePageTelemetry(url) /* * handle "scroll to top" behaviour on route change */ @@ -65,6 +65,15 @@ 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) => { @@ -84,7 +93,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) { ( + MarkdownHandler={(props) => ( )} > 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 index 8e45a1243c7..3b518ced47b 100644 --- a/apps/docs/pages/guides/api.mdx +++ b/apps/docs/pages/guides/api.mdx @@ -11,8 +11,8 @@ export const meta = { 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. -- Realtime - for listening to database changes. -- GraphQL - a fast and auto-generate GraphQL API. +- 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. @@ -29,17 +29,40 @@ You can use them directly from the browser (two-tier architecture), or as a comp ## 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: +It provides everything you need from a CRUD API at the URL `https://.supabase.co/rest/v1/`. -- Basic CRUD operations -- Deeply nested joins, allowing you to fetch data from multiple tables in a single fetch -- Works with Postgres Views +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] -GraphQL in Supabase works through [pg_graphql](https://supabase.com/blog/pg-graphql), an open source PostgreSQL extension for GraphQL. +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] diff --git a/apps/docs/pages/guides/api/rest/client-libs.mdx b/apps/docs/pages/guides/api/rest/client-libs.mdx index 4b6272e1f6d..5594ef78686 100644 --- a/apps/docs/pages/guides/api/rest/client-libs.mdx +++ b/apps/docs/pages/guides/api/rest/client-libs.mdx @@ -20,7 +20,7 @@ Supabase provides client libraries for the REST and Realtime APIs. Some librarie | `Language` | `Source Code` | `Documentation` | | ----------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------- | -| C# | [supabase-js](https://github.com/supabase-community/supabase-csharp) | [Docs](https://supabase.com/docs/reference/csharp/introduction) | +| 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) | 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..5559550f3d2 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' 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 c819a3f745f..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() - } + } = 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 ( @@ -308,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 } + + 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 } ``` @@ -322,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} ) @@ -380,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} ) @@ -419,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 }) { - 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() { +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} /> + ) } @@ -550,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() { +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} /> + ) } @@ -589,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)}
} ``` @@ -661,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 99449d191e0..424ed29ee0a 100644 --- a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx +++ b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx @@ -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/server-side-rendering.mdx b/apps/docs/pages/guides/auth/server-side-rendering.mdx index 87235781711..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 @@ -220,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 aec434ecea1..ca38587e786 100644 --- a/apps/docs/pages/guides/cli/local-development.mdx +++ b/apps/docs/pages/guides/cli/local-development.mdx @@ -407,12 +407,44 @@ If your project uses Edge Functions, you can deploy these using [`functions depl supabase functions deploy ``` +### Enabling Local Logging + +Local logs rely on the Supabase Analytics Server. This can be enabled via the CLI configuration, and requires a Google Cloud project and BigQuery access. + + + The Google Cloud project must have billing enabled. Read more about this requirement + [here](https://supabase.com/docs/reference/self-hosting-analytics/introduction#bigquery). + + +Requirements: + +1. Google Cloud project number +2. Google Cloud project ID +3. Google Cloud Service Account Key, obtained through [Google Cloud IAM dashboard](https://console.cloud.google.com/iam-admin/iam), with BigQuery Admin role assigned to the service account. + +Once you have these 3 items, follow these steps: + +1. Update your project's `config.toml` and fill in the following: + +``` +[analytics] +enabled = true +gcp_project_number = "123456" +gcp_project_id = "my-project-id" +gcp_jwt_path = "supabase/gcloud.json" +``` + +2. Place your service account key (a JSON file) at the corresponding path and ensure that it is correctly named. + +3. Start your local stack using `supabase start` + +This will switch the logging drivers and will direct logs to the Analytics server. You will be able to view and query your logs via the Studio Logs Explorer and Logs UI. + ## Limitations and considerations The local development environment is not as feature-complete as the Supabase Platform. We're working towards parity between the hosted platform and the local environment. Here are some of the differences: - The Functions interface is coming soon. -- Logs are not supported through the interface, but you can access them through the Docker containers. - You cannot update your project settings in the Dashboard. This must be done using the CLI. export const Page = ({ children }) => diff --git a/apps/docs/pages/guides/database/arrays.mdx b/apps/docs/pages/guides/database/arrays.mdx index e59be4a6d4b..45f258195e4 100644 --- a/apps/docs/pages/guides/database/arrays.mdx +++ b/apps/docs/pages/guides/database/arrays.mdx @@ -140,7 +140,7 @@ returns: This returns the entire array field: ```js -const { data, error } = await supabase.from('arraytest').select('textarray[]') +const { data, error } = await supabase.from('arraytest').select('textarray') console.log(JSON.stringify(data, null, 2)) ``` @@ -161,7 +161,7 @@ returns: - [Supabase JS Client](https://github.com/supabase/supabase-js) - [Supabase Account - Free Tier OK](https://supabase.com) -- [PostgreSQL Arrays](https://www.postgresql.org/docs/12/arrays.html) +- [PostgreSQL Arrays](https://www.postgresql.org/docs/15/arrays.html) export const Page = ({ children }) => diff --git a/apps/docs/pages/guides/functions/cicd-workflow.mdx b/apps/docs/pages/guides/functions/cicd-workflow.mdx index 01c30d69182..a1836c20b53 100644 --- a/apps/docs/pages/guides/functions/cicd-workflow.mdx +++ b/apps/docs/pages/guides/functions/cicd-workflow.mdx @@ -2,7 +2,7 @@ import Layout from '~/layouts/DefaultGuideLayout' export const meta = { id: 'cicd-workflow', - title: 'Deploying with Git', + title: 'Deploying with GitHub Actions', description: 'How to deploy Supabase Edge Functions with a CI / CD pipeline.', video: 'https://www.youtube.com/v/6OMVWiiycLs', } diff --git a/apps/docs/pages/guides/getting-started.mdx b/apps/docs/pages/guides/getting-started.mdx index bb335915b34..8032bc3a0b8 100644 --- a/apps/docs/pages/guides/getting-started.mdx +++ b/apps/docs/pages/guides/getting-started.mdx @@ -36,6 +36,22 @@ export const meta = {
+### Use Cases + +
+ {useCases.map((item) => { + return ( + + + + {item.description} + + + + ) + })} +
+ ### Framework Quickstarts
@@ -84,6 +100,27 @@ export const meta = { })}
+export const useCases = [ + { + title: 'OpenAI Vector Search', + href: '/guides/getting-started/openai/vector-search', + description: `Build your own custom ChatGPT with Next.js, OpenAI and pg_vector.`, + icon: '/docs/img/icons/openai_logo', + }, + { + title: 'Subscription Payments (SaaS)', + href: 'https://github.com/vercel/nextjs-subscription-payments#nextjs-subscription-payments-starter', + description: `Clone, deploy, and fully customize a SaaS subscription application with Next.js.`, + icon: '/docs/img/icons/nextjs-icon', + }, + { + title: 'Partner Gallery', + href: 'https://github.com/supabase-community/partner-gallery-example#supabase-partner-gallery-example', + description: `Postgres full-text search, image storage, and more.`, + icon: '/docs/img/icons/nextjs-icon', + }, +] + export const quickstarts = [ { title: 'React', @@ -99,6 +136,13 @@ export const quickstarts = [ 'Learn how to create a Supabase project, add some sample data to your database, and query the data from a NextJS app.', icon: '/docs/img/icons/nextjs-icon', }, + { + title: 'RedwoodJS', + href: '/guides/getting-started/quickstarts/redwoodjs', + description: + 'Learn how to create a Supabase project, add some sample data to your database using Prisma migration and seeds, and query the data from a RedwoodJS app.', + icon: '/docs/img/icons/redwood-icon', + }, { title: 'Flutter', href: '/guides/getting-started/quickstarts/flutter', @@ -106,6 +150,27 @@ export const quickstarts = [ 'Learn how to create a Supabase project, add some sample data to your database, and query the data from a Flutter app.', icon: '/docs/img/icons/flutter-icon', }, + { + title: 'SvelteKit', + href: '/guides/getting-started/quickstarts/sveltekit', + description: + 'Learn how to create a Supabase project, add some sample data to your database, and query the data from a SvelteKit app.', + icon: '/docs/img/icons/svelte-icon', + }, + { + title: 'SolidJS', + href: '/guides/getting-started/quickstarts/solidjs', + description: + 'Learn how to create a Supabase project, add some sample data to your database, and query the data from a SolidJS app.', + icon: '/docs/img/icons/solidjs-icon', + }, + { + title: 'Vue', + href: '/guides/getting-started/quickstarts/solidjs', + description: + 'Learn how to create a Supabase project, add some sample data to your database, and query the data from a Vue app.', + icon: '/docs/img/icons/vuejs-icon', + }, ] export const webapps = [ diff --git a/apps/docs/pages/guides/getting-started/openai/vector-search.mdx b/apps/docs/pages/guides/getting-started/openai/vector-search.mdx new file mode 100644 index 00000000000..580d52262e0 --- /dev/null +++ b/apps/docs/pages/guides/getting-started/openai/vector-search.mdx @@ -0,0 +1,544 @@ +import Layout from '~/layouts/DefaultGuideLayout' +import StepHikeCompact from '~/components/StepHikeCompact' + +export const meta = { + title: 'OpenAI Embeddings & Vector Search', + subtitle: + 'Learn how to build a ChatGPT-style doc search powered by Next.js, OpenAI, and Supabase.', + breadcrumb: 'OpenAI', +} + +In this tutorial we'll look at how you can build a custom ChatGPT-like search experience for your own knowledge base. See our [Supabase Clippy](https://supabase.com/blog/chatgpt-supabase-docs) blog post for an example of how this will look. + +We assume that you have a Next.js project with a collection of `.mdx` files nested inside your `pages` directory. We will start developing locally with the Supabase CLI and then push our local database changes to our hosted Supabase project. + + + You can find the [full example on + GitHub](https://github.com/supabase-community/nextjs-openai-doc-search). + + +## Create a project + +1. [Create a new project](https://app.supabase.com) in the Supabase Dashboard. +1. Enter your project details. +1. Wait for the new database to launch. + +## Prepare the database + +Let's prepare the database schema. We can use the "OpenAI Vector Search" quickstart in the [SQL Editor](https://app.supabase.com/project/_/sql), or you can copy/paste the SQL below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **OpenAI Vector Search**. +3. Click **Run**. + + + + + + + + + + + Make sure you have the latest version of the [Supabase CLI installed](). + + Initialize Supabase in the root directory of your app. + + + + + + ```bash + supabase init + ``` + + + + + + + + + To make changes to our local database, we need to create a new migration. This will create a new `.sql` file in our `supabase/migrations` folder, where we can write SQL that will be applied to our local database when starting Supabase locally. + + + + + + ```bash + supabase migration new init + ``` + + + + + + + + + Copy the following SQL line into the newly created migration file to enable the pgvector extension. + + + + + + ```sql + -- Enable pgvector extension + create extension if not exists vector with schema public; + ``` + + + + + + + + + Copy these SQL queries to your migration file. It will create two tables in our database schema. + + + + + + ```sql + -- Stores the checksum of our pages. + -- This ensures that we only regenerate embeddings + -- when the page content has changed. + create table "public"."nods_page" ( + id bigserial primary key, + parent_page_id bigint references public.nods_page, + path text not null unique, + checksum text, + meta jsonb, + type text, + source text + ); + alter table "public"."nods_page" + enable row level security; + + -- Stores the actual embeddings with some metadata + create table "public"."nods_page_section" ( + id bigserial primary key, + page_id bigint not null references public.nods_page on delete cascade, + content text, + token_count int, + embedding vector(1536), + slug text, + heading text + ); + alter table "public"."nods_page_section" + enable row level security; + ``` + + + + + + + + + Anytime the user sends a query, we want to find the content that's relevant to their questions. We can do this using pgvector's similarity search. + + These are quite complex SQL operations, so let's wrap them in database functions that we can call from our frontend using [RPC](https://supabase.com/docs/reference/javascript/rpc). + + + + + + ```sql + -- Create embedding similarity search functions + create or replace function match_page_sections( + embedding vector(1536), + match_threshold float, + match_count int, + min_content_length int + ) + returns table ( + id bigint, + page_id bigint, + slug text, + heading text, + content text, + similarity float + ) + language plpgsql + as $$ + #variable_conflict use_variable + begin + return query + select + nods_page_section.id, + nods_page_section.page_id, + nods_page_section.slug, + nods_page_section.heading, + nods_page_section.content, + (nods_page_section.embedding <#> embedding) * -1 as similarity + from nods_page_section + + -- We only care about sections that have a useful amount of content + where length(nods_page_section.content) >= min_content_length + + -- The dot product is negative because of a Postgres limitation, so we negate it + and (nods_page_section.embedding <#> embedding) * -1 > match_threshold + + -- OpenAI embeddings are normalized to length 1, so + -- cosine similarity and dot product will produce the same results. + -- Using dot product which can be computed slightly faster. + -- + -- For the different syntaxes, see https://github.com/pgvector/pgvector + order by nods_page_section.embedding <#> embedding + + limit match_count; + end; + $$; + ``` + + + + + + + + + Start Supabase locally. At this point all files in `supabase/migrations` will be applied to your database and you're ready to go. + + + + + + ```bash + supabase start + ``` + + + + + + + + + Once ready, you can link your local project to your cloud hosted Supabase project and push the local changes to your hosted instance. + + + + + + ```bash + supabase link --project-ref=your-project-ref + + supabase db push + ``` + + + + + + + + + + +## Pre-process the knowledge base at build time + +With our database set up, we need to process and store all `.mdx` files in the `pages` directory. You can find the full script [here](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/lib/generate-embeddings.ts), or follow the steps below: + + + + + + + Create a new file `lib/generate-embeddings.ts` and copy the code over from [GitHub](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/lib/generate-embeddings.ts). + + + + + + ```bash + curl \ + https://raw.githubusercontent.com/supabase-community/nextjs-openai-doc-search/main/lib/generate-embeddings.ts \ + -o "lib/generate-embeddings.ts" + ``` + + + + + + + + + We need some environment variables to run the script. Add them to your `.env` file and make sure your `.env` file is not committed to source control! + You can get your local Supabase credentials by running `supabase status`. + + + + + + ```txt + NEXT_PUBLIC_SUPABASE_URL= + NEXT_PUBLIC_SUPABASE_ANON_KEY= + SUPABASE_SERVICE_ROLE_KEY= + + # Get your key at https://platform.openai.com/account/api-keys + OPENAI_KEY= + ``` + + + + + + + + + Include the script in your `package.json` script commands to enable Vercel to automaticall run it at build time. + + + + + + ```json + "scripts": { + "dev": "next dev", + "build": "pnpm run embeddings && next build", + "start": "next start", + "embeddings": "tsx lib/generate-embeddings.ts" + }, + ``` + + + + + + + +## Create Text Completion with OpenAI API + +Anytime a user asks a question, we need to create an embedding for their question, perform a similarity search, and then send a text completion request to the OpenAI API with the query and then context content merged together into a prompt. + +All of this is glued together in a [Vercel Edge Function](https://vercel.com/docs/concepts/functions/edge-functions), the code for which can be found on [GitHub](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/pages/api/vector-search.ts). + + + + + + + In order to perform similarity search we need to turn the question into an embedding. + + + + + + ```ts + const embeddingResponse = await fetch('https://api.openai.com/v1/embeddings', { + method: 'POST', + headers: { + Authorization: `Bearer ${openAiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model: 'text-embedding-ada-002', + input: sanitizedQuery.replaceAll('\n', ' '), + }), + }) + + if (embeddingResponse.status !== 200) { + throw new ApplicationError('Failed to create embedding for question', embeddingResponse) + } + + const { + data: [{ embedding }], + } = await embeddingResponse.json() + ``` + + + + + + + + + Using the `embeddingResponse` we can now perform similarity search by performing an remote procedure call (RPC) to the database function we created earlier. + + + + + + ```ts + const { error: matchError, data: pageSections } = await supabaseClient.rpc( + 'match_page_sections', + { + embedding, + match_threshold: 0.78, + match_count: 10, + min_content_length: 50, + } + ) + ``` + + + + + + + + + With the relevant content for the user's question identified, we can now build the prompt and make a text completion request via the OpenAI API. + + If successful, the OpenAI API will respond with a `text/event-stream` response that we can simply forward to the client where we'll process the event stream to smoothly print the answer to the user. + + + + + + ```ts + const prompt = codeBlock` + ${oneLine` + You are a very enthusiastic Supabase representative who loves + to help people! Given the following sections from the Supabase + documentation, answer the question using only that information, + outputted in markdown format. If you are unsure and the answer + is not explicitly written in the documentation, say + "Sorry, I don't know how to help with that." + `} + + Context sections: + ${contextText} + + Question: """ + ${sanitizedQuery} + """ + + Answer as markdown (including related code snippets if available): + ` + + const completionOptions: CreateCompletionRequest = { + model: 'text-davinci-003', + prompt, + max_tokens: 512, + temperature: 0, + stream: true, + } + + const response = await fetch('https://api.openai.com/v1/completions', { + method: 'POST', + headers: { + Authorization: `Bearer ${openAiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(completionOptions), + }) + + if (!response.ok) { + const error = await response.json() + throw new ApplicationError('Failed to generate completion', error) + } + + // Proxy the streamed SSE response from OpenAI + return new Response(response.body, { + headers: { + 'Content-Type': 'text/event-stream', + }, + }) + ``` + + + + + + + +## Display the answer on the frontend + +In a last step, we need to process the event stream from the OpenAI API and print the answer to the user. The full code for this can be found on [GitHub](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/components/SearchDialog.tsx). + +```tsx +const handleConfirm = React.useCallback( + async (query: string) => { + setAnswer(undefined) + setQuestion(query) + setSearch('') + dispatchPromptData({ index: promptIndex, answer: undefined, query }) + setHasError(false) + setIsLoading(true) + + const eventSource = new SSE(`api/vector-search`, { + headers: { + apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '', + Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`, + 'Content-Type': 'application/json', + }, + payload: JSON.stringify({ query }), + }) + + function handleError(err: T) { + setIsLoading(false) + setHasError(true) + console.error(err) + } + + eventSource.addEventListener('error', handleError) + eventSource.addEventListener('message', (e: any) => { + try { + setIsLoading(false) + + if (e.data === '[DONE]') { + setPromptIndex((x) => { + return x + 1 + }) + return + } + + const completionResponse: CreateCompletionResponse = JSON.parse(e.data) + const text = completionResponse.choices[0].text + + setAnswer((answer) => { + const currentAnswer = answer ?? '' + + dispatchPromptData({ + index: promptIndex, + answer: currentAnswer + text, + }) + + return (answer ?? '') + text + }) + } catch (err) { + handleError(err) + } + }) + + eventSource.stream() + + eventSourceRef.current = eventSource + + setIsLoading(true) + }, + [promptIndex, promptData] +) +``` + +## Learn More + +Want to learn more about the awesome tech that is powering this? + +- Read about how we built [ChatGPT for the Supabase Docs](https://supabase.com/blog/chatgpt-supabase-docs). +- Read the pgvector Docs for [Embeddings and vector similarity](https://supabase.com/docs/guides/database/extensions/pgvector) +- Watch Greg's video for a full breakdown: + +
+ +
+ +export const Page = ({ children }) => +export default Page diff --git a/apps/docs/pages/guides/getting-started/quickstarts/redwoodjs.mdx b/apps/docs/pages/guides/getting-started/quickstarts/redwoodjs.mdx new file mode 100644 index 00000000000..ac716078403 --- /dev/null +++ b/apps/docs/pages/guides/getting-started/quickstarts/redwoodjs.mdx @@ -0,0 +1,242 @@ +import Layout from '~/layouts/DefaultGuideLayout' +import StepHikeCompact from '~/components/StepHikeCompact' + +export const meta = { + title: 'Use Supabase with RedwoodJS', + subtitle: + 'Learn how to create a Supabase project, add some sample data to your database using Prisma migration and seeds, and query the data from a RedwoodJS app.', + breadcrumb: 'Framework Quickstarts', +} + + + + + + [Create a new project](https://app.supabase.com) in the Supabase Dashboard. + + + Be sure to make note of the Database Password you used as you will need this later to connect to your database. + + + + + ![New Project](/docs/img/redwoodjs-qs-new-project.png) + + + + + + + After your project is ready, gather the following information about your [database connections](https://app.supabase.com/project/_/settings/database): + + * Connection String (port 5432) + * Connection Pooling / Connection String (port 6543) + + You will need these to setup environment variables in Step 5. + + + You can copy and paste these connection strings from the Supabase Dashboard when needed in later steps. + + + + + ![New Project](/docs/img/redwoodjs-qs-connection-strings-pool.png) + + + + + + + Create a RedwoodJS app with TypeScript. + + + The [`yarn` package manager](https://yarnpkg.com) is required to create a RedwoodJS app. You will use it to run RedwoodJS commands later. + + While TypeScript is recommended, If you want a JavaScript app, omit the `--ts` flag. + + + + + ```bash Terminal + yarn create redwood-app my-app --ts + ``` + + + + + + + You'll develop your app, manage database migrations, and run your app in VS Code. + + + + ```bash Terminal + cd my-app + code . + ``` + + + + + + + In your `.env` file, add the following environment variables for your database connection: + + * The `DIRECT_URL` should use the `Connection String` from your Supabase project. Hint: the port is `5432`. + + * The `DATABASE_URL` should use the `Connection Pooling / Connection String` from your Supabase project. Hint: the port is `6432`. + + + Be sure to append `?pgbouncer=true` to the end of the `DATABASE_URL` connection string. + Also, replace `[YOUR-PASSWORD]` and `[YOUR-PROJECT-REF]` with the password you used when creating your Supabase project and the project reference from the URL in your browser. + + + + + ```bash terminal + # .env + # PostgreSQL connection string used for migrations + DIRECT_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:5432/postgres" + # PostgreSQL connection string with pgBouncer config — used by Prisma Client + DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:6543/postgres?pgbouncer=true" + + ``` + + + + + + + By default, RedwoodJS ships with a SQLite database, but we want to use PostgreSQL. + + Update your Prisma schema file `api/db/schema.prisma` to use your Supabase PostgreSQL database connection environment variables you setup in Step 5. + + + + ```file="api/prisma/schema.prisma" title="api/prisma/schema.prisma" + // api/db/schema.prisma + + datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directUrl = env("DIRECT_URL") + } + ``` + + + + + + + Create the Country model in `api/db/schema.prisma` and then run `yarn rw prisma migrate dev` from your terminal to apply the migration. + + + + ```js + // api/db/schema.prisma + + model Country { + id Int @id @default(autoincrement()) + name String @unique + } + ``` + + + + + + + Let's seed the database with a few countries. + + Update the file `scripts/seeds.ts` to contain the following code: + + + + + ```ts + // scripts/seed.ts + + import type { Prisma } from '@prisma/client' + import { db } from 'api/src/lib/db' + + export default async () => { + try { + const data: Prisma.CountryCreateArgs['data'][] = [ + { name: 'United States' }, + { name: 'Canada' }, + { name: 'Mexico' }, + ] + + console.log('Seeding countries ...') + + const countries = await db.country.createMany({ data }) + + console.log('Done.', countries) + } catch (error) { + console.error(error) + } + } + ``` + + + + + + + Run the seed database command to populate the `Country` table with the countries you just created. + + + The reset database command `yarn rw prisma db reset` will recreate the tables and will also run the seed script. + + + + + ```bash Terminal + yarn rw prisma db seed + ``` + + + + + + + Now, we'll use RedwoodJS generators to scaffold a CRUD UI for the `Country` model. + + + + ```bash Terminal + yarn rw g scaffold country + ``` + + + + + + + Start the app via `yarn rw dev`. A browser will open to the RedwoodJS Splash page. + + + + ![RedwoodJS Splash Page](/docs/img/redwoodjs-qs-splash.png) + + + + + + + + Click on `/countries` to visit http://localhost:8910/countries where should see the list of countries. + + You may now edit, delete, and add new countries using the scaffolded UI. + + + + ![RedwoodJS Splash Page](/docs/img/redwoodjs-qs-countries-ui.png) + + + + + +export const Page = ({ children }) => + +export default Page diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx index 2c2c5de48a5..14c32a07bbb 100644 --- a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx +++ b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx @@ -318,6 +318,8 @@ export default function Account({ session }) { Let's create a new component for that called `Account.tsx` within a `components` folder. +First, [generate type definitions from your database using the Supabase CLI](https://supabase.com/docs/guides/database/api/generating-types) to `../utils/database.types`. + ```tsx title=components/Account.tsx import { useState, useEffect } from 'react' import { useUser, useSupabaseClient, Session } from '@supabase/auth-helpers-react' diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx index 22b154c836c..c67ccea9008 100644 --- a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx +++ b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx @@ -179,11 +179,13 @@ Update your `src/routes/+layout.svelte`: export let data: LayoutData - $: ({ supabase } = data) + $: ({ supabase, session } = data) onMount(() => { - const { data } = supabase.auth.onAuthStateChange(() => { - invalidate('supabase:auth') + const { data } = supabase.auth.onAuthStateChange((event, _session) => { + if (_session?.expires_at !== session?.expires_at) { + invalidate('supabase:auth') + } }) return () => data.subscription.unsubscribe() diff --git a/apps/docs/pages/guides/platform/custom-domains.mdx b/apps/docs/pages/guides/platform/custom-domains.mdx index 441ebef2f87..d6f838187f8 100644 --- a/apps/docs/pages/guides/platform/custom-domains.mdx +++ b/apps/docs/pages/guides/platform/custom-domains.mdx @@ -7,12 +7,6 @@ export const meta = { video: 'https://www.youtube.com/v/6rcGnW_Mh-0', } - - -Custom Domains are currently in beta, and are being slowly made available to projects. - - - Custom domains allow you to present a branded experience to your users. Custom domains are available as a [add-on for projects on a paid tier](https://app.supabase.com/project/_/settings/billing/update). Setting up a custom domain requires [Owner or Admin permissions](/docs/guides/platform/access-control#manage-team-members) for the project. Currently, you must use a subdomain (e.g., `api.example.com`, rather than `example.com`) for the purposes of this guide.
@@ -99,12 +93,6 @@ As with the final activation stage of the process for setting up a custom domain ## Vanity Subdomains - - -Vanity Subdomains are currently in beta, and are being slowly made available to projects. [Contact Support](https://app.supabase.com/support/new) if you'd like to request early access. - - - Vanity Subdomains allow you to present a basic branded experience, compared to custom domains. They allow you to host your services at a custom subdomain on Supabase (e.g., `my-example-brand.supabase.co`) instead of the default, randomly-assigned `foobarbaz.supabase.co`. To get started: diff --git a/apps/docs/pages/guides/realtime/extensions/postgres-changes.mdx b/apps/docs/pages/guides/realtime/extensions/postgres-changes.mdx index 07b819990ac..aa93a0482cf 100644 --- a/apps/docs/pages/guides/realtime/extensions/postgres-changes.mdx +++ b/apps/docs/pages/guides/realtime/extensions/postgres-changes.mdx @@ -335,7 +335,8 @@ const channel = supabase You may choose to sign your own tokens to customize claims that can be checked in your RLS policies. In order for this to work you must pass `apikey` in both Realtime's `headers` and `params` when creating the client. -The `apikey` in `headers` must be either the `anon` or `service_role` token that Supabase signed. +The `apikey` in `headers` must be either the `anon` or `service_role` token that Supabase provides for every project. +You can find these tokens under [Project API keys](https://app.supabase.com/project/_/settings/api) in your project's dashboard. This will authenticate your request in the API gateway. @@ -362,6 +363,18 @@ const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY }) ``` +### Refreshed Tokens + +You will need to refresh tokens on your own, but once generated, you can pass them to Realtime. + +For example, if you're using the `supabase-js` `v2` client then you can pass your token like this: + +```js +// Client setup + +supabase.realtime.setAuth('fresh-token') +``` + export const Page = ({ children }) => export default Page diff --git a/apps/docs/pages/guides/resources.mdx b/apps/docs/pages/guides/resources.mdx index c2f2e4aa2a3..5bda171db2f 100644 --- a/apps/docs/pages/guides/resources.mdx +++ b/apps/docs/pages/guides/resources.mdx @@ -141,6 +141,12 @@ export const migrationGuides = [ href: '/guides/resources/migrating-to-supabase/render', description: 'Migrate your Render Postgres database to Supabase.', }, + { + title: 'Amazon RDS', + icon: '/docs/img/icons/aws-rds-icon', + href: '/guides/resources/migrating-to-supabase/amazon-rds', + description: 'Migrate your Amazon RDS database to Supabase.', + }, ] export const postgres = [ diff --git a/apps/docs/pages/guides/resources/migrating-to-supabase/amazon-rds.mdx b/apps/docs/pages/guides/resources/migrating-to-supabase/amazon-rds.mdx new file mode 100644 index 00000000000..6eacca05a42 --- /dev/null +++ b/apps/docs/pages/guides/resources/migrating-to-supabase/amazon-rds.mdx @@ -0,0 +1,95 @@ +import Layout from '~/layouts/DefaultGuideLayout' + +export const meta = { + title: 'Migrate from Amazon RDS to Supabase', + description: 'Migrate your Amazon RDS MySQL or MS SQL database to Supabase Postgres database.', +} + +This guide aims to exhibit the process of transferring your Amazon RDS database from any of these engines Postgres, MySQL or MS SQL to Supabase's Postgres database. Although Amazon RDS is a favored managed database service provided by AWS, it may not suffice for all use cases. Supabase, on the other hand, provides an excellent free and open source option that encompasses all the necessary backend features to develop a product: a Postgres database, authentication, instant APIs, edge functions, real-time subscriptions, and storage. + +Supabase's core is Postgres, enabling the use of row-level security and providing access to over 40 Postgres extensions. By migrating from Amazon RDS to Supabase, you can leverage Postgres to its fullest potential and acquire all the features you need to complete your project. + +## Retrieve your Amazon RDS database credentials [#retrieve-rds-credentials] + +1. Log in to your [Amazon RDS account](https://aws.amazon.com/rds/). +1. Select the region where your RDS database is located. +1. Navigate to the **Databases** tab. +1. Select the database that you want to migrate. +1. In the **Connectivity & Security** tab, note down the Endpoint and the port number. +1. In the **Configuration** tab, note down the Database name and the Username. +1. If you do not have the password, create a new one and note it down. + +![Copying RDS credentials from AWS Management Console](/docs/img/guides/resources/migrating-to-supabase/amazon-rds/amazon-rds_credentials.png) + +## Retrieve your Supabase Host [#retrieve-supabase-host] + +1. If you're new to Supabase, [create a project](https://app.supabase.com). +1. Go to the [Database settings](https://app.supabase.com/project/_/settings/database) for your project in the Supabase Dashboard. +1. Under **Connection Info**, note your Host (`$SUPABASE_HOST`). +1. Save your password or [reset it](https://app.supabase.com/project/_/settings/database) if you forgot it. + +![Finding Supabase host address](/docs/img/guides/resources/migrating-to-supabase/amazon-rds/supabase_dashboard.png) + +## Migrate the database + +The fastest way to migrate your database is with the Supabase migration tool on + [Google Colab](https://colab.research.google.com/github/mansueli/Supa-Migrate/blob/main/Amazon_RDS_to_Supabase.ipynb). + +Alternatively, you can use [pgloader](https://github.com/dimitri/pgloader), a flexible and powerful data migration tool that supports a wide range of source database engines, including MySQL and MS SQL, and migrates the data to a Postgres database. For databases using the Postgres engine, we recommend using the pg_dump and psql command line tools, which are included in a full PostgreSQL installation. + + + + +1. Select the Dabase Engine from the Source database in the dropdown +1. Set the environment variables (`HOST`, `USER`, `SOURCE_DB`,`PASSWORD`, `SUPABASE_URL`, and `SUPABASE_PASSWORD`) in the Colab notebook. +2. Run the first two steps in [the notebook](https://colab.research.google.com/github/mansueli/Supa-Migrate/blob/main/Amazon_RDS_to_Supabase.ipynb) in order. The first sets engine and installs the necessary files. +3. Run the third step to start the migration. This will take a few minutes. + + + + + Install pgloader. + Create a configuration file (e.g., config.load). + +```sql +LOAD DATABASE + FROM mysql://USER:PASSWORD@HOST/SOURCE_DB + INTO postgres://postgres:password@db.xxxx.supabase.co:6543/postgres +ALTER SCHEMA 'public' OWNER TO 'postgres'; +set wal_buffers = '64MB', max_wal_senders = 0, statement_timeout = 0, work_mem to '2GB'; +```` + +##Run the migration with pgloader + +```bash +pgloader config.load +``` + + + + Install pgloader. + Create a configuration file (e.g., config.load). + +```sql +LOAD DATABASE + FROM mssql://USER:PASSWORD@HOST/SOURCE_DB + INTO postgres://postgres:password@db.xxxx.supabase.co:6543/postgres +ALTER SCHEMA 'public' OWNER TO 'postgres'; +set wal_buffers = '64MB', max_wal_senders = 0, statement_timeout = 0, work_mem to '2GB'; +```` + +##Run the migration with pgloader + +```bash +pgloader config.load +``` + + + +export const Page = ({ children }) => +export default Page diff --git a/apps/docs/pages/guides/self-hosting.mdx b/apps/docs/pages/guides/self-hosting.mdx index cdd7b69cc57..9c80c496788 100644 --- a/apps/docs/pages/guides/self-hosting.mdx +++ b/apps/docs/pages/guides/self-hosting.mdx @@ -54,6 +54,7 @@ We recommend installing all extensions into an `extensions` schema. This will ke since all tables in the `public` schema are exposed via the API. ```sql +{/* prettier-ignore */} create schema if not exists extensions; create extension if not exists "uuid-ossp" with schema extensions; create extension if not exists pgcrypto with schema extensions; diff --git a/apps/docs/pages/guides/self-hosting/analytics/config.mdx b/apps/docs/pages/guides/self-hosting/analytics/config.mdx new file mode 100644 index 00000000000..8267f6a913e --- /dev/null +++ b/apps/docs/pages/guides/self-hosting/analytics/config.mdx @@ -0,0 +1,38 @@ +import Layout from '~/layouts/DefaultGuideLayout' +import { getAnalyticsConfigV0 } from '~/lib/mdx/getConfig' +import Param from '~/components/Params' + +export const spec = getAnalyticsConfigV0() + +export const meta = { + title: 'Analytics Self-hosting Config', + description: 'How to configure and deploy Supabase Analytics.', +} + +
{spec.info.description}
+ +
+{spec.info.tags.map(tag => { + return ( + <> +

{tag.title}

+

{tag.description}

+
+
Parameters
+
    + {spec.parameters.filter(param => param.tags.includes(tag.id)).map((param) => { + return + })} + +
+
+ + ) + +})} + +
+ +export const Page = ({ children }) => + +export default Page diff --git a/apps/docs/pages/index.mdx b/apps/docs/pages/index.mdx index d8aebeb4157..cb079575e9b 100644 --- a/apps/docs/pages/index.mdx +++ b/apps/docs/pages/index.mdx @@ -72,6 +72,11 @@ export const meta = { + + + + + @@ -310,6 +315,13 @@ export const apis = [ href: 'reference/self-hosting-realtime/introduction', description: 'Self-host your own Realtime server.', }, + { + title: 'Self-Hosting Analytics', + icon: '/docs/img/icons/menu/reference-analytics', + hasLightIcon: true, + href: 'reference/self-hosting-analytics/introduction', + description: 'Self-host your own Analytics server.', + }, ] export const platform = [ diff --git a/apps/docs/pages/reference/analytics/[...slug].tsx b/apps/docs/pages/reference/analytics/[...slug].tsx new file mode 100644 index 00000000000..3fcf010110f --- /dev/null +++ b/apps/docs/pages/reference/analytics/[...slug].tsx @@ -0,0 +1,167 @@ +import specFile from '~/../../spec/transforms/analytics_v0_openapi_deparsed.json' assert { type: 'json' } +import { gen_v3, enrichedOperation } from '~/lib/refGenerator/helpers' +import { Tabs, CodeBlock } from 'ui' + +import RefSubLayout from '~/layouts/ref/RefSubLayout' + +export type AcceptedValue = { + id: string + name: string + type: 'string' | 'boolean' | 'object' + description?: string +} + +export type Flag = { + id: string + name: string + description: string + default_value: string + accepted_values: AcceptedValue[] +} + +export type ApiParameter = { + example: string + in: string + name: string + required: boolean + schema: { + type: string + example: string + } +} +// @ts-ignore +const generatedSpec = gen_v3(specFile, 'wat', { apiUrl: 'apiv0' }) + +export default function Config() { + return ( + +
+
+
+

{generatedSpec.info.title}

+

{generatedSpec.info.description}

+
+ +
+ {generatedSpec.operations.map((operation: any) => ( +
+ + +
+ + {operation.operation} + {operation.fullPath} + +
+ {/* Path Parameters */} + {operation.parameters && + operation.parameters.filter((parameter) => parameter.in === 'path').length > + 0 && ( +
+

Path parameters

+
    + {operation.parameters && + operation.parameters + .filter((parameter: any) => parameter.in === 'path') + .map((parameter: any) => ( +
  • +
    +
    + {parameter.name} +
    + {parameter.required && ( +
    + REQUIRED +
    + )} +
    +
    +

    {parameter.description}

    +
    + {parameter.example && ( +
    + Example: + + {parameter.example} + +
    + )} +
  • + ))} +
+
+ )} + + {/* Header Parameters */} + {operation.parameters && + operation.parameters.filter((parameter) => parameter.in === 'header').length > + 0 && ( +
+

Header parameters

+
    + {operation.parameters && + operation.parameters + .filter((parameter: any) => parameter.in === 'header') + .map((parameter: any) => ( +
  • +
    + {parameter.name} + + {parameter.required && 'required'} + +
    +
    + Example: + + {parameter.example} + +
    +
  • + ))} +
+
+ )} +
+ + {operation.responseList.length > 0 && ( + <> +

Responses

+ + {operation.responseList.map((response: any) => ( + +

{response.description}

+ {response?.content && response?.content['application/json'] && ( +
+ + {JSON.stringify(response.content['application/json'], null, 2)} + +
+ )} +
+ ))} +
+ + )} +
+
+
+ ))} +
+
+
+
+ ) +} diff --git a/apps/docs/pages/reference/analytics/config.tsx b/apps/docs/pages/reference/analytics/config.tsx new file mode 100644 index 00000000000..e22dfe2e911 --- /dev/null +++ b/apps/docs/pages/reference/analytics/config.tsx @@ -0,0 +1,115 @@ +import fs from 'fs' +import matter from 'gray-matter' +import components from '~/components/index' +import { MDXRemote } from 'next-mdx-remote' +import { serialize } from 'next-mdx-remote/serialize' + +// @ts-expect-error +import specFile from '~/../../spec/analytics_v0_config.yaml' assert { type: 'yml' } +import { Parameter } from '~/lib/refGenerator/refTypes' + +import ReactMarkdown from 'react-markdown' + +// Parameters are grouped on the page by tag +const TAGS = ['general', 'database'] + +export default function Config(props) { + return ( +
+ ) +} +export async function getServerSideProps() { + // an array of ids of the intro sections for this library + const introPages = ['analytics'] + + const pages = [...introPages] + + // Grab custom markdown intro page files + const allMarkdownDocs = await Promise.all( + pages.map(async (x: any, i) => { + const pathName = `docs/ref/analytics/${x}.mdx` + + const markdownExists = fs.existsSync(pathName) + + const fileContents = markdownExists ? fs.readFileSync(pathName, 'utf8') : '' + const { data, content } = matter(fileContents) + + return { + id: x, + title: x, + // ...content, + meta: data, + introPage: introPages.includes(x), + content: content ? await serialize(content || '') : null, + } + }) + ) + + return { + props: { + docs: allMarkdownDocs, + }, + } +} diff --git a/apps/docs/pages/reference/self-hosting-analytics/[...slug].tsx b/apps/docs/pages/reference/self-hosting-analytics/[...slug].tsx new file mode 100644 index 00000000000..5f78d5830ff --- /dev/null +++ b/apps/docs/pages/reference/self-hosting-analytics/[...slug].tsx @@ -0,0 +1,24 @@ +import analyticsSpec from '~/../../spec/transforms/analytics_v0_openapi_deparsed.json' assert { type: 'json' } +import selfHostingAnalyticsCommonSections from '~/../../spec/common-self-hosting-analytics-sections.json' +import RefSectionHandler from '~/components/reference/RefSectionHandler' +import { flattenSections } from '~/lib/helpers' +import handleRefGetStaticPaths from '~/lib/mdx/handleRefStaticPaths' +import handleRefStaticProps from '~/lib/mdx/handleRefStaticProps' +import { gen_v3 } from '~/lib/refGenerator/helpers' + +const sections = flattenSections(selfHostingAnalyticsCommonSections) + +// @ts-ignore +const spec = gen_v3(analyticsSpec, 'wat', { apiUrl: 'apiv0' }) + +export default function JSReference(props) { + return +} + +export async function getStaticProps() { + return handleRefStaticProps(sections, '/self-hosting-analytics') +} + +export function getStaticPaths() { + return handleRefGetStaticPaths() +} diff --git a/apps/docs/pages/reference/swift/[...slug].tsx b/apps/docs/pages/reference/swift/[...slug].tsx new file mode 100644 index 00000000000..d0991316c1f --- /dev/null +++ b/apps/docs/pages/reference/swift/[...slug].tsx @@ -0,0 +1,21 @@ +import clientLibsCommonSections from '~/../../spec/common-client-libs-sections.json' +// @ts-expect-error +import spec from '~/../../spec/supabase_swift_v1.yml' assert { type: 'yml' } +import RefSectionHandler from '~/components/reference/RefSectionHandler' +import { flattenSections } from '~/lib/helpers' +import handleRefGetStaticPaths from '~/lib/mdx/handleRefStaticPaths' +import handleRefStaticProps from '~/lib/mdx/handleRefStaticProps' + +const sections = flattenSections(clientLibsCommonSections) + +export default function JSReference(props) { + return +} + +export async function getStaticProps() { + return handleRefStaticProps(sections, '/swift') +} + +export function getStaticPaths() { + return handleRefGetStaticPaths() +} diff --git a/apps/docs/pages/reference/swift/crawlers/[...slug].tsx b/apps/docs/pages/reference/swift/crawlers/[...slug].tsx new file mode 100644 index 00000000000..00d29a772db --- /dev/null +++ b/apps/docs/pages/reference/swift/crawlers/[...slug].tsx @@ -0,0 +1,44 @@ +import clientLibsCommonSections from '~/../../spec/common-client-libs-sections.json' +import typeSpec from '~/../../spec/enrichments/tsdoc_v2/combined.json' +// @ts-expect-error +import spec from '~/../../spec/supabase_swift_v1.yml' assert { type: 'yml' } +import RefSectionHandler from '~/components/reference/RefSectionHandler' +import { flattenSections } from '~/lib/helpers' +import handleRefGetStaticPaths from '~/lib/mdx/handleRefStaticPaths' +import handleRefStaticProps from '~/lib/mdx/handleRefStaticProps' +import { useRouter } from 'next/router' +import RefSEO from '~/components/reference/RefSEO' + +const sections = flattenSections(clientLibsCommonSections) + +export default function JSReference(props) { + const router = useRouter() + const slug = router.query.slug[0] + const filteredSection = sections.filter((section) => section.id === slug) + + const pageTitle = filteredSection[0]?.title + ? `${filteredSection[0]?.title} | Supabase` + : 'Supabase' + + return ( + <> + + + + + ) +} + +export async function getStaticProps() { + return handleRefStaticProps(sections, '/swift') +} + +export function getStaticPaths() { + return handleRefGetStaticPaths() +} diff --git a/apps/docs/pages/reference/swift/v1/[...slug].tsx b/apps/docs/pages/reference/swift/v1/[...slug].tsx new file mode 100644 index 00000000000..1ffdebde8c3 --- /dev/null +++ b/apps/docs/pages/reference/swift/v1/[...slug].tsx @@ -0,0 +1,21 @@ +import clientLibsCommonSections from '~/../../spec/common-client-libs-sections.json' +// @ts-expect-error +import spec from '~/../../spec/supabase_swift_v1.yml' assert { type: 'yml' } +import RefSectionHandler from '~/components/reference/RefSectionHandler' +import { flattenSections } from '~/lib/helpers' +import handleRefGetStaticPaths from '~/lib/mdx/handleRefStaticPaths' +import handleRefStaticProps from '~/lib/mdx/handleRefStaticProps' + +const sections = flattenSections(clientLibsCommonSections) + +export default function JSReference(props) { + return +} + +export async function getStaticProps() { + return handleRefStaticProps(sections, '/swift/v1') +} + +export function getStaticPaths() { + return handleRefGetStaticPaths() +} diff --git a/apps/docs/pages/reference/swift/v1/crawlers/[...slug].tsx b/apps/docs/pages/reference/swift/v1/crawlers/[...slug].tsx new file mode 100644 index 00000000000..13ae4435ddd --- /dev/null +++ b/apps/docs/pages/reference/swift/v1/crawlers/[...slug].tsx @@ -0,0 +1,43 @@ +import clientLibsCommonSections from '~/../../spec/common-client-libs-sections.json' +import typeSpec from '~/../../spec/enrichments/tsdoc_v2/combined.json' +// @ts-expect-error +import spec from '~/../../spec/supabase_swift_v1.yml' assert { type: 'yml' } +import RefSectionHandler from '~/components/reference/RefSectionHandler' +import { flattenSections } from '~/lib/helpers' +import handleRefGetStaticPaths from '~/lib/mdx/handleRefStaticPaths' +import handleRefStaticProps from '~/lib/mdx/handleRefStaticProps' +import { useRouter } from 'next/router' +import RefSEO from '~/components/reference/RefSEO' + +const sections = flattenSections(clientLibsCommonSections) + +export default function JSReference(props) { + const router = useRouter() + const slug = router.query.slug[0] + const filteredSection = sections.filter((section) => section.id === slug) + + const pageTitle = filteredSection[0]?.title + ? `${filteredSection[0]?.title} | Supabase` + : 'Supabase' + return ( + <> + + + + + ) +} + +export async function getStaticProps() { + return handleRefStaticProps(sections, '/swift/v1') +} + +export function getStaticPaths() { + return handleRefGetStaticPaths() +} diff --git a/apps/docs/public/favicon/android-chrome-192x192.png b/apps/docs/public/favicon/android-chrome-192x192.png index f45e47c8a9c..f0a2817a744 100644 Binary files a/apps/docs/public/favicon/android-chrome-192x192.png and b/apps/docs/public/favicon/android-chrome-192x192.png differ diff --git a/apps/docs/public/favicon/android-chrome-512x512.png b/apps/docs/public/favicon/android-chrome-512x512.png index 3a0ba2b52aa..1c658733e6e 100644 Binary files a/apps/docs/public/favicon/android-chrome-512x512.png and b/apps/docs/public/favicon/android-chrome-512x512.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-114x114.png b/apps/docs/public/favicon/apple-touch-icon-114x114.png new file mode 100644 index 00000000000..d2ee4b9e139 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-114x114.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-120x120.png b/apps/docs/public/favicon/apple-touch-icon-120x120.png new file mode 100644 index 00000000000..5bd0e4963a1 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-120x120.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-144x144.png b/apps/docs/public/favicon/apple-touch-icon-144x144.png new file mode 100644 index 00000000000..c73891c985d Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-144x144.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-152x152.png b/apps/docs/public/favicon/apple-touch-icon-152x152.png new file mode 100644 index 00000000000..65f90a02357 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-152x152.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-57x57.png b/apps/docs/public/favicon/apple-touch-icon-57x57.png new file mode 100644 index 00000000000..bfa1628afb5 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-57x57.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-60x60.png b/apps/docs/public/favicon/apple-touch-icon-60x60.png new file mode 100644 index 00000000000..15c5dca8005 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-60x60.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-72x72.png b/apps/docs/public/favicon/apple-touch-icon-72x72.png new file mode 100644 index 00000000000..fb0c4fb3663 Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-72x72.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon-76x76.png b/apps/docs/public/favicon/apple-touch-icon-76x76.png new file mode 100644 index 00000000000..7d950f0862e Binary files /dev/null and b/apps/docs/public/favicon/apple-touch-icon-76x76.png differ diff --git a/apps/docs/public/favicon/apple-touch-icon.png b/apps/docs/public/favicon/apple-touch-icon.png deleted file mode 100644 index 330e352fa5f..00000000000 Binary files a/apps/docs/public/favicon/apple-touch-icon.png and /dev/null differ diff --git a/apps/docs/public/favicon/archive/android-chrome-192x192.png b/apps/docs/public/favicon/archive/android-chrome-192x192.png new file mode 100644 index 00000000000..c0ac2bb1cdb Binary files /dev/null and b/apps/docs/public/favicon/archive/android-chrome-192x192.png differ diff --git a/apps/docs/public/favicon/archive/android-chrome-512x512.png b/apps/docs/public/favicon/archive/android-chrome-512x512.png new file mode 100644 index 00000000000..4de626fcc9e Binary files /dev/null and b/apps/docs/public/favicon/archive/android-chrome-512x512.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-114x114.png b/apps/docs/public/favicon/archive/apple-touch-icon-114x114.png new file mode 100644 index 00000000000..4aa46d4d25d Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-114x114.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-120x120.png b/apps/docs/public/favicon/archive/apple-touch-icon-120x120.png new file mode 100644 index 00000000000..d2b0e50ef41 Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-120x120.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-144x144.png b/apps/docs/public/favicon/archive/apple-touch-icon-144x144.png new file mode 100644 index 00000000000..00a5d8b5180 Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-144x144.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-152x152.png b/apps/docs/public/favicon/archive/apple-touch-icon-152x152.png new file mode 100644 index 00000000000..310532c4648 Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-152x152.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-57x57.png b/apps/docs/public/favicon/archive/apple-touch-icon-57x57.png new file mode 100644 index 00000000000..1314e02c744 Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-57x57.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-60x60.png b/apps/docs/public/favicon/archive/apple-touch-icon-60x60.png new file mode 100644 index 00000000000..0615675e809 Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-60x60.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-72x72.png b/apps/docs/public/favicon/archive/apple-touch-icon-72x72.png new file mode 100644 index 00000000000..e4418058cef Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-72x72.png differ diff --git a/apps/docs/public/favicon/archive/apple-touch-icon-76x76.png b/apps/docs/public/favicon/archive/apple-touch-icon-76x76.png new file mode 100644 index 00000000000..9a76327f94b Binary files /dev/null and b/apps/docs/public/favicon/archive/apple-touch-icon-76x76.png differ diff --git a/apps/docs/public/favicon/archive/favicon-128.png b/apps/docs/public/favicon/archive/favicon-128.png new file mode 100644 index 00000000000..d5dca345802 Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon-128.png differ diff --git a/apps/docs/public/favicon/archive/favicon-16x16.png b/apps/docs/public/favicon/archive/favicon-16x16.png new file mode 100644 index 00000000000..6361bcecd15 Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon-16x16.png differ diff --git a/apps/docs/public/favicon/archive/favicon-196x196.png b/apps/docs/public/favicon/archive/favicon-196x196.png new file mode 100644 index 00000000000..adb05b43453 Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon-196x196.png differ diff --git a/apps/docs/public/favicon/archive/favicon-32x32.png b/apps/docs/public/favicon/archive/favicon-32x32.png new file mode 100644 index 00000000000..4ea0fba2e3c Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon-32x32.png differ diff --git a/apps/docs/public/favicon/archive/favicon-96x96.png b/apps/docs/public/favicon/archive/favicon-96x96.png new file mode 100644 index 00000000000..92a3d735dff Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon-96x96.png differ diff --git a/apps/docs/public/favicon/archive/favicon.ico b/apps/docs/public/favicon/archive/favicon.ico new file mode 100644 index 00000000000..4e808093c05 Binary files /dev/null and b/apps/docs/public/favicon/archive/favicon.ico differ diff --git a/apps/docs/public/favicon/archive/mstile-144x144.png b/apps/docs/public/favicon/archive/mstile-144x144.png new file mode 100644 index 00000000000..00a5d8b5180 Binary files /dev/null and b/apps/docs/public/favicon/archive/mstile-144x144.png differ diff --git a/apps/docs/public/favicon/archive/mstile-150x150.png b/apps/docs/public/favicon/archive/mstile-150x150.png new file mode 100644 index 00000000000..4de1d9b1cc1 Binary files /dev/null and b/apps/docs/public/favicon/archive/mstile-150x150.png differ diff --git a/apps/docs/public/favicon/archive/mstile-310x150.png b/apps/docs/public/favicon/archive/mstile-310x150.png new file mode 100644 index 00000000000..b1121df62aa Binary files /dev/null and b/apps/docs/public/favicon/archive/mstile-310x150.png differ diff --git a/apps/docs/public/favicon/archive/mstile-310x310.png b/apps/docs/public/favicon/archive/mstile-310x310.png new file mode 100644 index 00000000000..7ea95ae09c0 Binary files /dev/null and b/apps/docs/public/favicon/archive/mstile-310x310.png differ diff --git a/apps/docs/public/favicon/archive/mstile-70x70.png b/apps/docs/public/favicon/archive/mstile-70x70.png new file mode 100644 index 00000000000..d5dca345802 Binary files /dev/null and b/apps/docs/public/favicon/archive/mstile-70x70.png differ diff --git a/apps/docs/public/favicon/favicon-128.png b/apps/docs/public/favicon/favicon-128.png new file mode 100644 index 00000000000..2206096f21b Binary files /dev/null and b/apps/docs/public/favicon/favicon-128.png differ diff --git a/apps/docs/public/favicon/favicon-16x16.png b/apps/docs/public/favicon/favicon-16x16.png index 4b7e28143e7..2e07b15e106 100644 Binary files a/apps/docs/public/favicon/favicon-16x16.png and b/apps/docs/public/favicon/favicon-16x16.png differ diff --git a/apps/docs/public/favicon/favicon-196x196.png b/apps/docs/public/favicon/favicon-196x196.png new file mode 100644 index 00000000000..d10fc7e36d9 Binary files /dev/null and b/apps/docs/public/favicon/favicon-196x196.png differ diff --git a/apps/docs/public/favicon/favicon-32x32.png b/apps/docs/public/favicon/favicon-32x32.png index 1a268444bf9..4101a08499b 100644 Binary files a/apps/docs/public/favicon/favicon-32x32.png and b/apps/docs/public/favicon/favicon-32x32.png differ diff --git a/apps/docs/public/favicon/favicon-96x96.png b/apps/docs/public/favicon/favicon-96x96.png new file mode 100644 index 00000000000..b23072a2c02 Binary files /dev/null and b/apps/docs/public/favicon/favicon-96x96.png differ diff --git a/apps/docs/public/favicon/favicon.ico b/apps/docs/public/favicon/favicon.ico index 5c4d1dcc5cf..51b9988fdcb 100644 Binary files a/apps/docs/public/favicon/favicon.ico and b/apps/docs/public/favicon/favicon.ico differ diff --git a/apps/docs/public/favicon/mstile-144x144.png b/apps/docs/public/favicon/mstile-144x144.png new file mode 100644 index 00000000000..c73891c985d Binary files /dev/null and b/apps/docs/public/favicon/mstile-144x144.png differ diff --git a/apps/docs/public/favicon/mstile-150x150.png b/apps/docs/public/favicon/mstile-150x150.png index 836aed416a0..bd10ae0a5df 100644 Binary files a/apps/docs/public/favicon/mstile-150x150.png and b/apps/docs/public/favicon/mstile-150x150.png differ diff --git a/apps/docs/public/favicon/mstile-310x150.png b/apps/docs/public/favicon/mstile-310x150.png new file mode 100644 index 00000000000..fb4d58022df Binary files /dev/null and b/apps/docs/public/favicon/mstile-310x150.png differ diff --git a/apps/docs/public/favicon/mstile-310x310.png b/apps/docs/public/favicon/mstile-310x310.png new file mode 100644 index 00000000000..0adc45ea0ac Binary files /dev/null and b/apps/docs/public/favicon/mstile-310x310.png differ diff --git a/apps/docs/public/favicon/mstile-70x70.png b/apps/docs/public/favicon/mstile-70x70.png new file mode 100644 index 00000000000..2206096f21b Binary files /dev/null and b/apps/docs/public/favicon/mstile-70x70.png differ diff --git a/apps/docs/public/favicon/safari-pinned-tab.svg b/apps/docs/public/favicon/safari-pinned-tab.svg deleted file mode 100644 index 7e408790eb0..00000000000 --- a/apps/docs/public/favicon/safari-pinned-tab.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - -Created by potrace 1.11, written by Peter Selinger 2001-2013 - - - - - diff --git a/apps/docs/public/favicon/site.webmanifest b/apps/docs/public/favicon/site.webmanifest index 8da2b0f3d44..c72ae95e89d 100644 --- a/apps/docs/public/favicon/site.webmanifest +++ b/apps/docs/public/favicon/site.webmanifest @@ -3,12 +3,12 @@ "short_name": "Supabase", "icons": [ { - "src": "/favicons/android-chrome-192x192.png", + "src": "/favicon/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { - "src": "/favicons/android-chrome-512x512.png", + "src": "/favicon/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } diff --git a/apps/docs/public/humans.txt b/apps/docs/public/humans.txt index a87525bceb6..6407c1bb7a2 100644 --- a/apps/docs/public/humans.txt +++ b/apps/docs/public/humans.txt @@ -11,6 +11,7 @@ Ariuna K Beng Eu Bo Lu Bobbie Soedirgo +Chandana Anumula Chase Granberry Chris Copplestone Dave Wilson @@ -50,6 +51,7 @@ Qiao Han Ramiro Nuñez Dosio Rodrigo Martins Mansueli Rory Wilding +Sreyas Udayavarman Stanislav M Steve Chavez Stojan Dimitrovski diff --git a/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/amazon-rds_credentials.png b/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/amazon-rds_credentials.png new file mode 100644 index 00000000000..9a692329b15 Binary files /dev/null and b/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/amazon-rds_credentials.png differ diff --git a/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/supabase_dashboard.png b/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/supabase_dashboard.png new file mode 100644 index 00000000000..3a1ff5b9daf Binary files /dev/null and b/apps/docs/public/img/guides/resources/migrating-to-supabase/amazon-rds/supabase_dashboard.png differ diff --git a/apps/docs/public/img/icons/aws-rds-icon.svg b/apps/docs/public/img/icons/aws-rds-icon.svg new file mode 100644 index 00000000000..37e7661d465 --- /dev/null +++ b/apps/docs/public/img/icons/aws-rds-icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/docs/public/img/icons/menu/analytics-light.svg b/apps/docs/public/img/icons/menu/analytics-light.svg new file mode 100644 index 00000000000..3cea218cd72 --- /dev/null +++ b/apps/docs/public/img/icons/menu/analytics-light.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/apps/docs/public/img/icons/menu/analytics.svg b/apps/docs/public/img/icons/menu/analytics.svg new file mode 100644 index 00000000000..2c3be34319e --- /dev/null +++ b/apps/docs/public/img/icons/menu/analytics.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/apps/docs/public/img/icons/menu/reference-analytics-light.svg b/apps/docs/public/img/icons/menu/reference-analytics-light.svg new file mode 100644 index 00000000000..840fb813f92 --- /dev/null +++ b/apps/docs/public/img/icons/menu/reference-analytics-light.svg @@ -0,0 +1,4 @@ + + + + diff --git a/apps/docs/public/img/icons/menu/reference-analytics.svg b/apps/docs/public/img/icons/menu/reference-analytics.svg new file mode 100644 index 00000000000..840fb813f92 --- /dev/null +++ b/apps/docs/public/img/icons/menu/reference-analytics.svg @@ -0,0 +1,4 @@ + + + + diff --git a/apps/docs/public/img/icons/menu/reference-csharp.svg b/apps/docs/public/img/icons/menu/reference-csharp.svg index 40d0375079d..84c1dcf8966 100644 --- a/apps/docs/public/img/icons/menu/reference-csharp.svg +++ b/apps/docs/public/img/icons/menu/reference-csharp.svg @@ -1,9 +1,9 @@ - - - - - - - - + + + + + + + + diff --git a/apps/docs/public/img/icons/menu/reference-swift-light.svg b/apps/docs/public/img/icons/menu/reference-swift-light.svg new file mode 100644 index 00000000000..149f5459b15 --- /dev/null +++ b/apps/docs/public/img/icons/menu/reference-swift-light.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/docs/public/img/icons/menu/reference-swift.svg b/apps/docs/public/img/icons/menu/reference-swift.svg new file mode 100644 index 00000000000..10bec817613 --- /dev/null +++ b/apps/docs/public/img/icons/menu/reference-swift.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/docs/public/img/icons/menu/swift.svg b/apps/docs/public/img/icons/menu/swift.svg new file mode 100644 index 00000000000..d11ab08bb58 --- /dev/null +++ b/apps/docs/public/img/icons/menu/swift.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/apps/docs/public/img/icons/openai_logo-light.svg b/apps/docs/public/img/icons/openai_logo-light.svg new file mode 100644 index 00000000000..3b4eff961f3 --- /dev/null +++ b/apps/docs/public/img/icons/openai_logo-light.svg @@ -0,0 +1,2 @@ + +OpenAI icon \ No newline at end of file diff --git a/apps/docs/public/img/icons/openai_logo.svg b/apps/docs/public/img/icons/openai_logo.svg new file mode 100644 index 00000000000..9aacd2a1115 --- /dev/null +++ b/apps/docs/public/img/icons/openai_logo.svg @@ -0,0 +1,2 @@ + +OpenAI icon \ No newline at end of file diff --git a/apps/docs/public/img/icons/swift-icon.svg b/apps/docs/public/img/icons/swift-icon.svg new file mode 100644 index 00000000000..d11ab08bb58 --- /dev/null +++ b/apps/docs/public/img/icons/swift-icon.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/apps/docs/public/img/redwoodjs-qs-connection-strings-pool.png b/apps/docs/public/img/redwoodjs-qs-connection-strings-pool.png new file mode 100644 index 00000000000..3718cd797e3 Binary files /dev/null and b/apps/docs/public/img/redwoodjs-qs-connection-strings-pool.png differ diff --git a/apps/docs/public/img/redwoodjs-qs-countries-ui.png b/apps/docs/public/img/redwoodjs-qs-countries-ui.png new file mode 100644 index 00000000000..50e98e5630c Binary files /dev/null and b/apps/docs/public/img/redwoodjs-qs-countries-ui.png differ diff --git a/apps/docs/public/img/redwoodjs-qs-new-project.png b/apps/docs/public/img/redwoodjs-qs-new-project.png new file mode 100644 index 00000000000..46cc1555991 Binary files /dev/null and b/apps/docs/public/img/redwoodjs-qs-new-project.png differ diff --git a/apps/docs/public/img/redwoodjs-qs-splash.png b/apps/docs/public/img/redwoodjs-qs-splash.png new file mode 100644 index 00000000000..750e5ad68f3 Binary files /dev/null and b/apps/docs/public/img/redwoodjs-qs-splash.png differ diff --git a/apps/temp-community-forum/.eslintrc.js b/apps/temp-community-forum/.eslintrc.js deleted file mode 100644 index e0b422e408e..00000000000 --- a/apps/temp-community-forum/.eslintrc.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/eslint-preset') diff --git a/apps/temp-community-forum/next-env.d.ts b/apps/temp-community-forum/next-env.d.ts deleted file mode 100644 index 4f11a03dc6c..00000000000 --- a/apps/temp-community-forum/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/apps/temp-community-forum/next.config.js b/apps/temp-community-forum/next.config.js deleted file mode 100644 index 6e4744fdc65..00000000000 --- a/apps/temp-community-forum/next.config.js +++ /dev/null @@ -1,5 +0,0 @@ -const withTM = require('next-transpile-modules')(['common']) - -module.exports = withTM({ - reactStrictMode: true, -}) diff --git a/apps/temp-community-forum/package.json b/apps/temp-community-forum/package.json deleted file mode 100644 index 6a63ff17f3a..00000000000 --- a/apps/temp-community-forum/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "forum", - "version": "0.0.0", - "private": true, - "scripts": { - "dev": "next dev --port 3002", - "build": "next build", - "start": "next start", - "lint": "next lint" - }, - "dependencies": { - "@octokit/graphql": "^4.8.0", - "colorette": "^1.4.0", - "common": "*", - "next": "12.0.8", - "react": "17.0.2", - "react-dom": "17.0.2", - "string-hash": "^1.1.3" - }, - "devDependencies": { - "@types/node": "^17.0.12", - "@types/react": "17.0.37", - "config": "*", - "eslint": "7.32.0", - "next-transpile-modules": "9.0.0", - "tsconfig": "*", - "typescript": "^4.5.3" - } -} diff --git a/apps/temp-community-forum/postcss.config.js b/apps/temp-community-forum/postcss.config.js deleted file mode 100644 index 29c447cb54b..00000000000 --- a/apps/temp-community-forum/postcss.config.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/postcss.config') diff --git a/apps/temp-community-forum/src/pages/_app.tsx b/apps/temp-community-forum/src/pages/_app.tsx deleted file mode 100644 index 2d0cd5807e9..00000000000 --- a/apps/temp-community-forum/src/pages/_app.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react' -import Main from '.' -import '../styles/tailwind.css' - -const Index = () => { - return
-} - -export default Index diff --git a/apps/temp-community-forum/src/pages/index.tsx b/apps/temp-community-forum/src/pages/index.tsx deleted file mode 100644 index c7381379165..00000000000 --- a/apps/temp-community-forum/src/pages/index.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { fetchDiscussions } from '../utils/api' -import { Button, Layouts } from 'common' -import { useEffect, useState } from 'react' - -export default function Main() { - const [discussionList, setDiscussionList] = useState([] as any[]) - - useEffect(() => { - async function fetchData() { - const discussions = await fetchDiscussions() - setDiscussionList(discussions) - } - fetchData() - }, []) - - return ( - -
Categories
-
One
-
Two
-
- } - > -

Discussions

- {discussionList.map((x) => ( -
-

{x.title}

-

{x.body}

-
- ))} - - ) -} diff --git a/apps/temp-community-forum/src/styles/tailwind.css b/apps/temp-community-forum/src/styles/tailwind.css deleted file mode 100644 index b5c61c95671..00000000000 --- a/apps/temp-community-forum/src/styles/tailwind.css +++ /dev/null @@ -1,3 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; diff --git a/apps/temp-community-forum/src/utils/api.ts b/apps/temp-community-forum/src/utils/api.ts deleted file mode 100644 index dfdb13906fb..00000000000 --- a/apps/temp-community-forum/src/utils/api.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { graphql } from '@octokit/graphql' - -const query = ` -{ - repository(owner: "supabase", name: "supabase") { - discussions(first: 10) { - nodes { - id - author { - avatarUrl - url - login - } - body - title - answer { - author { - avatarUrl - login - } - body - createdAt - } - createdAt - } - totalCount - pageInfo { - startCursor - endCursor - hasNextPage - hasPreviousPage - } - } - } -} -` -export async function fetchDiscussions() { - // @ts-ignore - const { repository } = await graphql(query, { - headers: { - authorization: `token ${process.env.NEXT_PUBLIC_DISCUSSIONS_TOKEN}`, - }, - }) - return repository.discussions.nodes -} diff --git a/apps/temp-community-forum/tailwind.config.js b/apps/temp-community-forum/tailwind.config.js deleted file mode 100644 index 9c2af498997..00000000000 --- a/apps/temp-community-forum/tailwind.config.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/tailwind.config') diff --git a/apps/temp-community-forum/tsconfig.json b/apps/temp-community-forum/tsconfig.json deleted file mode 100644 index a355365ba65..00000000000 --- a/apps/temp-community-forum/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "tsconfig/nextjs.json", - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], - "exclude": ["node_modules"] -} diff --git a/apps/temp-community-tutorials/.eslintrc.js b/apps/temp-community-tutorials/.eslintrc.js deleted file mode 100644 index e0b422e408e..00000000000 --- a/apps/temp-community-tutorials/.eslintrc.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/eslint-preset') diff --git a/apps/temp-community-tutorials/README.md b/apps/temp-community-tutorials/README.md deleted file mode 100644 index 1d67ece731b..00000000000 --- a/apps/temp-community-tutorials/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## Getting Started - -First, run the development server: - -```bash -yarn dev -``` - -Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. - -You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file. - -[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`. - -The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. - -## Learn More - -To learn more about Next.js, take a look at the following resources: - -- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. -- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. - -You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! - -## Deploy on Vercel - -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js. - -Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. diff --git a/apps/temp-community-tutorials/next-env.d.ts b/apps/temp-community-tutorials/next-env.d.ts deleted file mode 100644 index 4f11a03dc6c..00000000000 --- a/apps/temp-community-tutorials/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/apps/temp-community-tutorials/next.config.js b/apps/temp-community-tutorials/next.config.js deleted file mode 100644 index 6e4744fdc65..00000000000 --- a/apps/temp-community-tutorials/next.config.js +++ /dev/null @@ -1,5 +0,0 @@ -const withTM = require('next-transpile-modules')(['common']) - -module.exports = withTM({ - reactStrictMode: true, -}) diff --git a/apps/temp-community-tutorials/package.json b/apps/temp-community-tutorials/package.json deleted file mode 100644 index 473ca829340..00000000000 --- a/apps/temp-community-tutorials/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "tutorials", - "version": "0.0.0", - "private": true, - "scripts": { - "dev": "next dev --port 3003", - "build": "next build", - "start": "next start", - "lint": "next lint" - }, - "dependencies": { - "colorette": "^1.4.0", - "common": "*", - "next": "12.0.8", - "react": "17.0.2", - "react-dom": "17.0.2" - }, - "devDependencies": { - "@types/node": "^17.0.12", - "@types/react": "17.0.37", - "config": "*", - "eslint": "7.32.0", - "next-transpile-modules": "9.0.0", - "tsconfig": "*", - "typescript": "^4.5.3" - } -} diff --git a/apps/temp-community-tutorials/postcss.config.js b/apps/temp-community-tutorials/postcss.config.js deleted file mode 100644 index 29c447cb54b..00000000000 --- a/apps/temp-community-tutorials/postcss.config.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/postcss.config') diff --git a/apps/temp-community-tutorials/src/pages/_app.tsx b/apps/temp-community-tutorials/src/pages/_app.tsx deleted file mode 100644 index 2d0cd5807e9..00000000000 --- a/apps/temp-community-tutorials/src/pages/_app.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react' -import Main from '.' -import '../styles/tailwind.css' - -const Index = () => { - return
-} - -export default Index diff --git a/apps/temp-community-tutorials/src/pages/index.tsx b/apps/temp-community-tutorials/src/pages/index.tsx deleted file mode 100644 index 2e5771c0ae1..00000000000 --- a/apps/temp-community-tutorials/src/pages/index.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { fetchPosts, DevPost } from '../utils/api' -import { Button, Layouts } from 'common' -import { useEffect, useState } from 'react' - -export default function Main() { - const [postList, setPostList] = useState([] as DevPost[]) - - useEffect(() => { - async function fetchData() { - const posts = await fetchPosts() - setPostList(posts) - } - fetchData() - }, []) - - return ( - Shared Sidebar}> -

Tutorials

- {postList.map((x) => ( -
-

{x.title}

-

{x.description}

-
- ))} -
- ) -} diff --git a/apps/temp-community-tutorials/src/styles/tailwind.css b/apps/temp-community-tutorials/src/styles/tailwind.css deleted file mode 100644 index b5c61c95671..00000000000 --- a/apps/temp-community-tutorials/src/styles/tailwind.css +++ /dev/null @@ -1,3 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; diff --git a/apps/temp-community-tutorials/src/utils/api.ts b/apps/temp-community-tutorials/src/utils/api.ts deleted file mode 100644 index baa1b180f00..00000000000 --- a/apps/temp-community-tutorials/src/utils/api.ts +++ /dev/null @@ -1,55 +0,0 @@ -const username = 'supabase' -const postsUrl = `https://dev.to/api/articles?username=${username}` - -// Defines a Post returned from the DEV API -export type DevPost = { - id: Number - title: string - description: string - slug: string - url: string - path: string - readable_publish_date: string - published_at: string - tags: string - tag_list: string[] - comments_count: Number - public_reactions_count: Number - positive_reactions_count: Number - published: boolean - first_published_at: string - edited_at: string - user: { - username: string - name: string - profile_image_90: string - cover_image_90: string - profile_image_original: string - cover_image_original: string - location: string - website: string - bio: string - twitter_username: string - github_username: string - dribbble_username: string - path: string - } - organization: { - id: Number - name: string - slug: string - profile_image_90: string - profile_imag: string - } -} - -export async function fetchPosts() { - try { - const res = await fetch(postsUrl) - const data: DevPost[] = await res.json() - return data - } catch (err) { - console.log(err) - return [] - } -} diff --git a/apps/temp-community-tutorials/tailwind.config.js b/apps/temp-community-tutorials/tailwind.config.js deleted file mode 100644 index 9c2af498997..00000000000 --- a/apps/temp-community-tutorials/tailwind.config.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('config/tailwind.config') diff --git a/apps/temp-community-tutorials/tsconfig.json b/apps/temp-community-tutorials/tsconfig.json deleted file mode 100644 index a355365ba65..00000000000 --- a/apps/temp-community-tutorials/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "tsconfig/nextjs.json", - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], - "exclude": ["node_modules"] -} diff --git a/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx b/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx index 85b061947c7..e0b1c949f8c 100644 --- a/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx +++ b/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx @@ -114,3 +114,7 @@ While you're at it, consider supporting [@ankane](https://github.com/ankane)'s g Want to try Supabase Clippy? It's a hidden feature while in MVP - visit [supabase.com/docs](/docs) and hit `cmd` + `/` to pull up the search box (sorry mobile users). If you have any comments we'd love to hear them in our [ShowHN](https://news.ycombinator.com/item?id=34695306). + +## Deploy your own + +Want to build your own Clippy based on your own content? Use our [Next.js OpenAI Doc Search Template](https://github.com/supabase-community/nextjs-openai-doc-search) to deploy your own now! diff --git a/apps/www/_blog/2023-04-01-supaclub.mdx b/apps/www/_blog/2023-04-01-supaclub.mdx new file mode 100644 index 00000000000..9d52ef8a387 --- /dev/null +++ b/apps/www/_blog/2023-04-01-supaclub.mdx @@ -0,0 +1,38 @@ +--- +title: SupaClub +description: The Worlds First Software Engineering Nightclub. +author: ant_wilson +image: supaclub/supaclub-thumb.png +thumb: supaclub/supaclub-thumb.png +tags: + - announcements +date: '2023-04-01' +toc_depth: 3 +--- + +Announcing SupaClub (pronounced “Super-Clurb”), the world’s first Software Engineering Nightclub. + +Located on the Indonesian island of Bali, SupaClub is where the digital nomads of South East Asia are mixing Hardcore Techno with Hardcore Engineering. + +![Main Dance Floor](/images/blog/supaclub/supaclub1.png) + +In March this year, some members of the Supabase team took advantage of the fact that they can work fully remotely, and spent a week working in Bali. The island is a great place to relax in coffee shops during the day, but when night time rolled around our team faced a major problem - the large established nightclubs of Bali would not allow our engineers to bring their laptops into the club. They have strict rules against EMACS on the dance floor, killing our dream of fixing bugs whilst jamming to 90s club anthems. + +Our team got together and decided that we would do what we do best at Supabase. We’d ship a fix, and today that fix becomes a reality. + +![coding in the club](/images/blog/supaclub/supaclub2.png) + +SupaClub, situated near the beach in the Canggu neighborhood of Bali, will open its doors this coming Friday. It can house 4000 developers across 4 floors, each with a dedicated DJ and breakout rooms. It has UltraSpeed 1Gbps WiFi and bookable standing desks on every floor. VIP [SupaBrew bottle service](https://supabase.com/blog/supabrew) is available inside private conference rooms, complete with whiteboards and UltraWide monitors for full immersion (Think WeWork-meets-Pacha). + +![dancefloor meets coding](/images/blog/supaclub/supaclub3.png) + +In terms of beverage selection, [SupaBrew](https://supabase.com/blog/supabrew) will of course be available behind the bar, along with a cocktail list that includes: + +- **Bjarne Pisco Stroustrup** - A back-to-basics tantalizing mix of tart, sweet, and silky pisco brandy that won't leave your pointers dangling +- **The Linus** - A spicy twist on the Bloody Mary, this aggressive blend will have you shouting for more +- **Mojito-js** - we would list the ingredients but our mixologists keep changing the spec +- **HTML Highball** - Not a real cocktail, more of a mocktail + +SupaClub was made possible with the help of infamous Fyre Fest investor Ja Rule and “Super Bass” songstress Niki Minaj, both of which will also be performing on the opening night. + +If you would like to reserve a spot on the guest list for the opening night please email us at noreply@supabase.com with a link to your GitHub account and "Re: april fools" in the subject line. See you there. diff --git a/apps/www/_blog/2023-04-04-infinite-scroll-with-nextjs-framer-motion.mdx b/apps/www/_blog/2023-04-04-infinite-scroll-with-nextjs-framer-motion.mdx new file mode 100644 index 00000000000..a670abe9610 --- /dev/null +++ b/apps/www/_blog/2023-04-04-infinite-scroll-with-nextjs-framer-motion.mdx @@ -0,0 +1,338 @@ +--- +title: Infinite scroll with Next.js, Framer Motion, and Supabase +description: Lazy load and paginate data on scroll with Next.js and a sprinkle of Framer Motion magic ✨ +author: fsansalvadore +image: infinite-scroll-thumb.jpg +thumb: infinite-scroll-thumb.jpg +launchweek: 7 +tags: + - tutorial + - launch-week + - Next-js +date: '2023-04-04' +toc_depth: 6 +--- + +Every Launch Week, we strive to approach things differently as part of our Kaizen mindset. For [Launch Week 7](https://www.supabase.com/launch-week), we decided to add some twists to our popular ticket system. While we made several changes, this post will focus on one specific modification (we'll share more about the rest this week!). + +Our goal was to feature all the amazing people who generated tickets on a [single page](https://supabase.com/launch-week/tickets). However, displaying them all at once could take a toll on the loading time and negatively affect the user experience. That's where lazy loading smaller subsets via infinite scrolling came in as the solution. + +With infinite scrolling, users can effortlessly scroll through content while only loading the necessary data as they go. This not only enhances performance but also creates a seamless and enjoyable user experience. + +In this post, we'll detail our process of implementing infinite scrolling using Next.js, Framer Motion, and Supabase. + +## Step 0. Load the first batch + +First things first, let's install the dependencies we'll need. + +```bash +npm install @supabase/supabase-js lodash framer-motion +``` + +Set up the supabase-js client and fetch the first 20 tickets through `getServerSideProps` so we don't start with an empty screen. + +We'll assume our table in the db is called `my_tickets_table`. + +```jsx +import { useEffect, useState } from 'react' +import { createClient } from '@supabase/supabase-js' + +const supabase = createClient('supabase-url', 'supabase-key') + +export default function TicketsPage({ tickets }) { + const [loadedTickets, setLoadedTickets] = useState(tickets) + + return ( +
+ {loadedTickets.map((ticket, index) => ( + {/* We'll get to this part later */} + ))} +
+ ) + +export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { + const { data: tickets } = await supabase! + .from('my_tickets_table') + .select('*') + .order('createdAt', { ascending: false }) + .limit(20) + + return { + props: { + tickets, + }, + } +} +``` + +## Step 1. Listen to the scroll + +To detect if the user is scrolling we can listen to the window `scroll` event. + +If you try to `console.log()` the event returned in the listener callback, you'll notice that it fires on every single pixel scrolled. We want to avoid triggering like crazy, so we'll use a [lodash debounce function](https://www.geeksforgeeks.org/lodash-_-debounce-method/) to limit how often we call this event to once every 200 milliseconds. + +Here's what it looks like: + +```jsx +import { useEffect } from 'react' +import { debounce } from 'lodash' + +const handleScroll = () => { + // Do stuff when scrolling +} + +useEffect(() => { + const handleDebouncedScroll = debounce(() => handleScroll(), 200) + window.addEventListener('scroll', handleDebouncedScroll) + return () => { + window.removeEventListener('scroll', handleDebouncedScroll) + } +}, []) +``` + +## Step 2. Check if the container intersects the viewport + +Next, we want to check if the bottom of the tickets container intersects with the bottom of the viewport. We can use the `getBoundingClientRect` method to get the position of the container and then compare it with the height of the viewport. + +```jsx +import { useRef, useState } from 'react' + +// ... + +const containerRef = useRef(null) +const [offset, setOffset] = useState(1) +const [isInView, setIsInView] = useState(false) + +const handleScroll = (container) => { + if (containerRef.current && typeof window !== 'undefined') { + const container = containerRef.current + const { bottom } = container.getBoundingClientRect() + const { innerHeight } = window + setIsInView((prev) => bottom <= innerHeight) + } +} + +useEffect(() => { + if (isInView) { + loadMoreUsers(offset) + } +}, [isInView]) + +return
{/* List of loaded tickets */}
+``` + +## Step 3. Load tickets based on the offset + +Now we can load more tickets based on the current offset. We'll use the [range](https://supabase.com/docs/reference/javascript/range) method from the supabase-js library to easily work with the pagination logic. + +```jsx +export default function TicketsPage() { + const PAGE_COUNT = 20 + const [offset, setOffset] = useState(1) + const [isLoading, setIsLoading] = useState(false) + const [isInView, setIsInView] = useState(false) + + useEffect(() => { + if (isInView) { + loadMoreTickets(offset) + } + }, [isInView]) + + const loadMoreTickets = async (offset: number) => { + setIsLoading(true) + // Every time we fetch, we want to increase + // the offset to load fresh tickets + setOffset((prev) => prev + 1) + const { data: newTickets } = await fetchTickets(offset, PAGE_COUNT) + // Merge new tickets with all previously loaded + setLoadedTickets((prevTickets) => [...prevTickets, ...newTickets]) + setIsLoading(false) + } + + const fetchTickets = async (offset, limit) => { + const from = offset * PAGE_COUNT + const to = from + PAGE_COUNT - 1 + + const { data } = await supabase! + .from('my_tickets_table') + .select('*') + .range(from, to) + .order('createdAt', { ascending: false }) + + + return data + } +} +``` + +## Step 4. Animate the tickets + +Now that we have our tickets loaded, we want to add some animation to make them pop like dominos as they appear on the screen. For this, we're going to use the [Framer Motion](https://www.framer.com/motion/) library. + +We'll wrap each ticket in a motion component and add a transition effect to stagger their appearance on the screen: + +```jsx +import { motion } from 'framer-motion' + +// ... + +{ + loadedTickets.map((ticket, index) => { + // each ticket will be delayed based on it's index + // but we need to subtract the delay from all the previously loaded tickets + const recalculatedDelay = i >= PAGE_COUNT * 2 ? (i - PAGE_COUNT * (offset - 1)) / 15 : i / 15 + + return ( + + {/* Actual ticket component */} + + ) + }) +} +``` + +With this code, each ticket will start with an opacity of 0 and a y position of 20. As it animates into view, it will fade in and move up to its final position. The delay for each ticket will be based on its index in the array, creating a nice staggered effect. + +## Step 5. Stop listening when finished + +Once all the tickets have been loaded, we want to stop listening to the scroll event to avoid unnecessary requests. We can do this by setting a state variable called `isLast` to true whenever the length of the response will be less than `PAGE_COUNT`: + +```jsx +if (newTickets.length < PAGE_COUNT) { + setIsLast(true) +} +``` + +We'll use this code to conditionally remove the event listener: + +```jsx +useEffect(() => { + const handleDebouncedScroll = debounce(() => !isLast && handleScroll(), 200) + window.addEventListener('scroll', handleScroll) + return () => { + window.removeEventListener('scroll', handleScroll) + } +}, []) +``` + +Now, when the `isLast` state variable is true, the event listener will be removed and the component will stop listening to the scroll event. + +## Wrap up + +That's it! We hope this post enabled you to build the next awesome infinite scroll. + +Here's the complete code: + +```jsx +import { useEffect, useState, useRef } from 'react' +import { createClient } from '@supabase/supabase-js' +import { debounce } from 'lodash' +import { motion } from 'framer-motion' + +const supabase = createClient('supabase-url', 'supabase-key') + +export default function TicketsPage({ tickets }) { + const PAGE_COUNT = 20 + const containerRef = useRef(null) + const [loadedTickets, setLoadedTickets] = useState(tickets) + const [offset, setOffset] = useState(1) + const [isLoading, setIsLoading] = useState(false) + const [isInView, setIsInView] = useState(false) + + const handleScroll = (container) => { + if (containerRef.current && typeof window !== 'undefined') { + const container = containerRef.current + const { bottom } = container.getBoundingClientRect() + const { innerHeight } = window + setIsInView((prev) => bottom <= innerHeight) + } + } + + useEffect(() => { + const handleDebouncedScroll = debounce(() => !isLast && handleScroll(), 200) + window.addEventListener('scroll', handleScroll) + return () => { + window.removeEventListener('scroll', handleScroll) + } + }, []) + + useEffect(() => { + if (isInView) { + loadMoreTickets(offset) + } + }, [isInView]) + + const loadMoreTickets = async (offset: number) => { + setIsLoading(true) + setOffset((prev) => prev + 1) + const { data: newTickets } = await fetchTickets(offset, PAGE_COUNT) + setLoadedTickets((prevTickets) => [...prevTickets, ...newTickets]) + setIsLoading(false) + } + + const fetchTickets = async (offset) => { + const from = offset * PAGE_COUNT + const to = from + PAGE_COUNT - 1 + + const { data } = await supabase! + .from('my_tickets_table') + .select('*') + .range(from, to) + .order('createdAt', { ascending: false }) + + return data + } + + return ( +
+ { + loadedTickets.map((ticket, index) => { + const recalculatedDelay = + i >= PAGE_COUNT * 2 ? (i - PAGE_COUNT * (offset - 1)) / 15 : i / 15 + + return ( + + {/* Actual ticket component */} + + ) + }) + } +
+ ) + +export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { + const { data: tickets } = await supabase! + .from('my_tickets_table') + .select('*') + .order('createdAt', { ascending: false }) + .limit(20) + + return { + props: { + tickets, + }, + } +} +``` + +If you also want to feature in the endless tickets page and have a chance to win cool swag, you're invited to [generate your unique ticket](https://www.supabase.com/launch-week) until April 16th. + +See you at Launch Week! 👋 diff --git a/apps/www/_blog/2023-04-07-designing-with-ai-midjourney.mdx b/apps/www/_blog/2023-04-07-designing-with-ai-midjourney.mdx new file mode 100644 index 00000000000..2a82e547dce --- /dev/null +++ b/apps/www/_blog/2023-04-07-designing-with-ai-midjourney.mdx @@ -0,0 +1,292 @@ +--- +title: 'Designing with AI: Generating unique artwork for every user' +description: Using MidJourney to generative artwork and serving ticket images with Edge Functions +author: marijana,thor_schaeff +image: launch-week-7/designing-with-ai-midjourney/header.png +thumb: launch-week-7/designing-with-ai-midjourney/header.png +launchweek: 7 +tags: + - launch-week +date: '2023-04-07' +toc_depth: 6 +--- + +While Supabase Launch Weeks happen online, we love the idea of bringing everyone together as if it was an in-person conference. Our ticketing system is one of the ways that we emulate this. + +We have been issuing tickets since Launch Week 5, and they were so successful that we have done them ever since. It’s become a challenge to outdo the previous effort with something better every time. + +## Prompts with Midjourney + +You've probably heard of this "AI" tech, and most likely tired of the low-effort SkyNet memes. We wanted to do something more integrated with our developer/designer workflow. Something that we could share with developers & designers that they might find useful. + +[Midjourney](https://www.midjourney.com/) was where we started for art generation. We experimented with prompts, blends, and colors to create eye-catching visuals for each ticket connected to a GitHub profile. Some first attempts and ideas included prompts like: + +``` +/imagine abstract 3 layers of waves on a dark background with light refracting through it, very cool subtle minimal dark illustration, purple light leak with subtle highlights +``` + +In our exploration of different commands and prompts, we found that the `/blend` command was particularly enjoyable and helpful for creating the desired visuals. This command allowed us to quickly upload multiple images and experiment with different combinations and aesthetics to create a cohesive new image. For designers, the `/blend` command is like `/imagine` but visual, making it easy to visually experiment with different elements. Experiments included blurred edges, planetoid shapes, light leaks, shadows, swirls, motion blurs, waves, cubes, reflections, bokeh, and lots and lots of _“make it look really really blurred”_. + +![midjoruney experiments](/images/blog/launch-week-7/designing-with-ai-midjourney/experiments.jpg) + +After exploring a variety of text prompts, blends, and styles, we decided that most of the visuals we generated were too chaotic and busy for our Launch Week tickets. Images felt cluttered and overwhelming, making it difficult to read overlaid text. We shifted our focus to creating a cleaner, simpler aesthetic. This required a selective approach to the visual components we wanted to include. + +After what-seemed-like hours (okay, just a few), we were able to generate some interesting artwork that could be useful. We chose purple hues and simpler swirls - minimalist visuals that could serve as backgrounds for our tickets and landing page. + +![midjourney variations](/images/blog/launch-week-7/designing-with-ai-midjourney/midjourney-variations.png) + +### Chasing Gold Behind the Scenes + +When we were happy with the main visual for Launch Week 7, we also needed to create gold visuals for the extra special tickets, and those needed to look the same… but gold. Initially, we thought we could simply use the prompt `/imagine *seed number* make it gold` to generate the desired effect. To our surprise, MidJourney did not cooperate with this idea: + +![midjourney failed attempts.jpg](/images/blog/launch-week-7/designing-with-ai-midjourney/failed-attempts.jpg) + +We tried excluding certain elements, such as faces or circles to refine the output, and at one point every prompt ended with a `-- no faces, -- no circles, -- no gold bars ...`, but the occasional gold bars still appeared. + +We needed to come up with a different approach (even though this approach seemed more fun). + +Eventually, we just added a golden overlay gradient to previously generated images and then used `/blend` to blend the purple and the gold together. + +And voila, we had a baseline for generating variations: + +![midjourney blending variations](/images/blog/launch-week-7/designing-with-ai-midjourney/midjourney-blending-variations.png) + +The final visual that you see everywhere won us over because of its vibrant swirls. While each swirl looks slightly different, a consistent style is still maintained throughout. + +Fortunately, we didn't require full-width images for each ticket. Upscaled MidJourney images sufficed. Nevertheless, we had to recreate the main visual on the landing page in vectors to use it effectively. You can view it in full glory at [https://supabase.com/launch-week](https://supabase.com/launch-week). + +![Screenshot 2023-04-06 at 09.47.47.png](/images/blog/launch-week-7/designing-with-ai-midjourney/launch-week-7-ticket-home.png) + +## Open Graph images + +An important aspect of Launch Week tickets is their shareability. Each Launch Week we’ve been blown away by how many developers post their tickets on social channels (and we absolutely love seeing them!). + +When you share your unique ticket URL, the image shown on the social preview is called an Open Graph image (or OG image for short). + +These images are generated for each unique URL and ticket. This requires a bit of magic, which in our case means using a [Supabase Edge Function](https://supabase.com/docs/guides/functions) together with [Supabase Storage](https://supabase.com/docs/guides/storage) for smart caching. + +### Supabase Edge Function 🤝 Supabase Storage + +Our Edge Function handles the generation of each ticket image, and also does a bunch of other things under the hood, like detecting if the ticket was shared on socials. This will become important later! + +```jsx +if (userAgent?.toLocaleLowerCase().includes('twitter')) { + // Attendee shared on Twitter + await supabaseAdminClient + .from('lw7_tickets') + .update({ sharedOnTwitter: 'now' }) + .eq('username', username) + .is('sharedOnTwitter', null) +} else if (userAgent?.toLocaleLowerCase().includes('linkedin')) { + // Attendee shared on LinkedIn + await supabaseAdminClient + .from('lw7_tickets') + .update({ sharedOnLinkedIn: 'now' }) + .eq('username', username) + .is('sharedOnLinkedIn', null) +} +``` + +We want to be as efficient as possible because generating a png file in an edge function is an expensive operation. We generate each ticket only once and then save it to Supabase Storage (which has a [smart CDN cache built in](https://supabase.com/blog/storage-image-resizing-smart-cdn#smart-cdn-deep-dive)). + +So in the first step we check if we can fetch the user’s image from storage: + +```tsx +// Try to get image from Supabase Storage CDN. +storageResponse = await fetch( + `${STORAGE_URL}/tickets/regular/${BUCKET_FOLDER_VERSION}/${username}.png` +) +``` + +If we can’t find the image in storage, then we kick off the ticket generation pipeline, using Vercel’s awesome [open-source satori library](https://github.com/vercel/satori) transforms HTML & CSS into svgs! + +Each image includes the user’s GitHub details. We use [`supabase-js`](https://supabase.com/docs/reference/javascript/installing) for authentication: users log in with their GitHub account and we store their username in a table in Postgres. + +Since this table includes email addresses, we secure it using [RLS](https://supabase.com/docs/guides/auth/row-level-security) to ensure each user can only view their own data. At the same time, we want these tickets to be publicly shareable, and that’s where [Postgres Views](https://supabase.com/blog/postgresql-views) come in handy. + +By creating a view, we can selectively publicize parts of our table and also compute some additional values on the fly: + +```sql +drop + view if exists lw7_tickets_golden; + +create +or replace view lw7_tickets_golden as +with + lw7_referrals as ( + select + referred_by, + count(*) as referrals + from + lw7_tickets + where + referred_by is not null + group by + referred_by + ) +select + lw7_tickets."id", + lw7_tickets."name", + lw7_tickets."username", + lw7_tickets."ticketNumber", + lw7_tickets."createdAt", + lw7_tickets."sharedOnTwitter", + lw7_tickets."sharedOnLinkedIn", + lw7_tickets."bg_image_id", + case + when lw7_referrals.referrals is null then 0 + ELSE lw7_referrals.referrals + end as referrals, + case + when lw7_tickets."sharedOnTwitter" is not null + and lw7_tickets."sharedOnLinkedIn" is not null then true + else false + end as golden +from + lw7_tickets + left outer join lw7_referrals on lw7_tickets.username = lw7_referrals.referred_by; + +select + * +from + lw7_tickets_golden +``` + +We can now retrieve that username by using the following code: + +```jsx +// Get ticket data +const { data, error } = await supabaseAdminClient + .from('lw7_tickets_golden') + .select('name, ticketNumber, golden, bg_image_id') + .eq('username', username) + .maybeSingle() +if (error) console.log(error.message) +if (!data) throw new Error('user not found') +const { name, ticketNumber, bg_image_id } = data +const golden = data?.golden ?? false +``` + +You can now probably guess why our edge function was tracking requests from the Twitter and LinkedIn bots! That’s exactly the condition used to turn your ticket golden. How cool is that, with the power of Postgres, we can do all of this within the Database, absolutely mind-blowing. Also, we can easily track a referral count. Relational DBs for the win! + +With our public view in place, we can now easily retrieve the relevant ticket details needed to generate the image, via `supabase-js`: + +The ticket image itself is just a layering of some background images, your GitHub profile picture, and some text elements, et voila you’ve got yourself a unique ticket image! + +
+
+ ![Main background image](/images/blog/launch-week-7/designing-with-ai-midjourney/ticket-backdrop.png) +
+ Main background image +
+
+ +
+ ![Ticket outline](/images/blog/launch-week-7/designing-with-ai-midjourney/ticket-outline.png) +
Ticket outline
+
+ +
+ ![Random AI generated background for the ticket + outline](/images/blog/launch-week-7/designing-with-ai-midjourney/ticket-ai-background.png) +
Random AI generated background for the ticket outline
+
+ +
+ ![Layer it all together and put some nice text on top and you got yourself a beautiful + ticket!](/images/blog/launch-week-7/designing-with-ai-midjourney/ticket-details.png) +
Layer it all together and put some nice text on top and you got yourself a beautiful ticket!
+
+
+ +Once generated, we can conveniently upload the image to Supabase Storage using `supabase-js`. This ensures fast response times as well as efficient resource usage. + +```jsx +const type = golden ? 'golden' : 'regular' + +// Upload image to storage. +const { error: storageError } = await supabaseAdminClient.storage + .from('images') + .upload(`lw7/tickets/${type}/${BUCKET_FOLDER_VERSION}/${username}.png`, generatedImage.body, { + contentType: 'image/png', + cacheControl: '31536000', + upsert: false, + }) +``` + +And of course, all of this is open source, you can find the full function code [here](https://github.com/supabase/supabase/tree/master/apps/www/supabase/functions/lw7-ticket-og). Please feel free to utilize it for your own Launches! + +### Turning tickets golden in realtime + +Using the power of the entire Supabase stack, we’ve designed a pretty neat mechanic to allow users to turn their tickets golden. + +In previous Launch Weeks, we employed the [fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_sequence) to sprinkle golden tickets around using the ticket number sequence. This time around we wanted to make it more interactive and allow the user to earn their golden ticket, increasing their chance to win swag. + +Remember the Twitter and LinkedIn bot detection from above? We use those to generate the `golden` column in our public view: + +```sql +case + when lw7_tickets."sharedOnTwitter" is not null + and lw7_tickets."sharedOnLinkedIn" is not null then true + else false +end as golden +``` + +As folks are sharing their tickets on socials to earn their gold status, we also want to give them realtime feedback on their progress. Luckily we also have a feature for that, [Supabase Realtime](https://supabase.com/realtime). + +Something that would have been a headache in the past is just a couple of lines of client-side JavaScript: + +```jsx +const channel = supabase + .channel('changes') + .on( + 'postgres_changes', + { + event: 'UPDATE', + schema: 'public', + table: 'lw7_tickets', + filter: `username=eq.${username}`, + }, + (payload) => { + const golden = !!payload.new.sharedOnTwitter && !!payload.new.sharedOnLinkedIn + setUserData({ + ...payload.new, + golden, + }) + if (golden) { + channel.unsubscribe() + } + } + ) + .subscribe() +``` + +Interested to know how this fits within your Next.js application? Find the code [here](https://github.com/supabase/supabase/blob/master/apps/www/components/LaunchWeek/Ticket/TicketForm.tsx#L70-L102). + +## Displaying the images + +We have some images, so how can we now display them somewhere? [@Francesco Sansalvadore](https://twitter.com/frnk_snslvdr) saw one of our team members trying to “swipe” on the tickets slider component on the [launch week page](https://supabase.com/launch-week/tickets) and he thought, why not feature all the fantastic people who generated tickets on a single page? + +We built a [ticket wall](https://supabase.com/launch-week/tickets) that you can scroll endlessly. We approached it with an infinite scroll technique, lazy-loading a few tickets at a time. + +![launch week 7 ticket wall](/images/blog/launch-week-7/designing-with-ai-midjourney/launch-week-7-ticket-wall.png) + +If you’re interested in a more detailed step-by-step guide to reproduce this effect, take a look at the [Infinite scroll with Next.js, Framer Motion, and Supabase](/blog/infinite-scroll-with-nextjs-framer-motion) blog post. + +## Get your ticket + +You too can also be Charlie Bucket and have a Golden Ticket. There is no chocolate factory, however, but we do have some amazing swag to win. + +Up for grabs are: + +- Supabase mechanical keyboard. In fact, we have 3 of them to give away!\_ Guaranteed to annoy your co-workers/cat/partner/ yourself. +- Socks: _Perfect for your `