Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Delete old mdx files

dannykng45550be4e078
diff --git a/apps/docs/pages/getting-started.mdx b/apps/docs/pages/getting-started.mdx
deleted file mode 100644
index ccb7790f15e..00000000000
--- a/apps/docs/pages/getting-started.mdx
+++ /dev/null
@@ -1,161 +0,0 @@
-import Layout from '~/layouts/DefaultGuideLayout'
-
-export const meta = {
- title: 'Overview',
- description: 'An overview of Supabase\'s architecture and product principles.',
-}
-
-Supabase is open source. We choose open source tools which are scalable and make them simple to use.
-
-Supabase is not a 1-to-1 mapping of Firebase. While we are building many of the features that Firebase offers, we are not going about it the same way:
-our technological choices are quite different; everything we use is open source; and wherever possible, we use and support existing tools rather than developing from scratch.
-
-Most notably, we use Postgres rather than a NoSQL store. This choice was deliberate. We believe that no other database offers the functionality required to compete with Firebase,
-while maintaining the scalability required to go beyond it.
-
-## Architecture
-
-Each Supabase project consists of several tools:
-
-![Supabase Architecture](/docs/img/supabase-architecture.png)
-
-### PostgreSQL (Database)
-
-PostgreSQL is the core of Supabase. We do not abstract the PostgreSQL database — you can access it and use it with full privileges. We simply provide tools which makes PostgreSQL as easy to use as Firebase.
-
-- Official Docs: [postgresql.org/docs](https://www.postgresql.org/docs/current/index.html)
-- Source code: [github.com/postgres/postgres](https://github.com/postgres/postgres) (mirror)
-- License: [PostgreSQL Licence](https://www.postgresql.org/about/licence/)
-- Language: C
-
-### Studio (Dashboard)
-
-An open source Dashboard for managing your database and services.
-
-- Official Docs: [Supabase docs](/docs)
-- Source code: [github.com/supabase/supabase](https://github.com/supabase/supabase/tree/master/studio)
-- License: [Apache 2](https://github.com/supabase/supabase/blob/master/LICENSE)
-- Language: TypeScript
-
-### GoTrue (Auth)
-
-A JWT-based API for managing users and issuing access tokens. This integrates with PostgreSQL's Row Level Security and the API servers.
-
-- Official Docs: [Supabase Auth reference docs](/docs/reference/auth)
-- Source code: [github.com/supabase/gotrue](https://github.com/supabase/gotrue)
-- License: [MIT](https://github.com/supabase/gotrue/blob/master/LICENSE)
-- Language: Go
-
-### PostgREST (API)
-
-A standalone web server that turns your PostgreSQL database directly into a RESTful API.
-We use this with our [pg_graphql](https://github.com/supabase/pg_graphql) extension to provide a GraphQL API.
-
-- Official Docs: [postgrest.org](https://postgrest.org/)
-- Source code: [github.com/PostgREST/postgrest](https://github.com/PostgREST/postgrest)
-- License: [MIT](https://github.com/PostgREST/postgrest/blob/main/LICENSE)
-- Language: Haskel
-
-### Realtime (API & multiplayer)
-
-A scalable websocket engine for managing user Presence, broadcasting messages, and streaming database changes.
-
-- Official Docs: [Supabase Realtime docs](/docs/guides/realtime)
-- Source code: [github.com/supabase/realtime](https://github.com/supabase/realtime)
-- License: [Apache 2](https://github.com/supabase/realtime/blob/main/LICENSE)
-- Language: Elixir
-
-### Storage API (large file storage)
-
-An S3-compatible object storage service that stores metadata in Postgres.
-
-- Official Docs: [Supabase Storage reference docs](/docs/reference/storage)
-- Source code: [github.com/supabase/storage-api](https://github.com/supabase/storage-api)
-- License: [Apache 2.0](https://github.com/supabase/storage-api/blob/master/LICENSE)
-- Language: NodeJS / TypeScript
-
-### Deno (Edge Functions)
-
-A modern runtime for JavaScript and TypeScript.
-
-- Official Docs: [deno.land](https://deno.land/)
-- Source code: [github.com/denoland/deno](https://github.com/denoland/deno)
-- License: [MIT](https://github.com/denoland/deno/blob/main/LICENSE.md)
-- Language: TypeScript / Rust
-
-### postgres-meta (Database management)
-
-A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries.
-
-- Official Docs: [supabase.github.io/postgres-meta](https://supabase.github.io/postgres-meta/)
-- Source code: [github.com/supabase/postgres-meta](https://github.com/supabase/postgres-meta)
-- License: [Apache 2.0](https://github.com/supabase/postgres-meta/blob/master/LICENSE)
-- Language: NodeJS / TypeScript
-
-### PgBouncer
-
-A lightweight connection pooler for PostgreSQL. This is useful for connecting to Postgres when using Serverless functions.
-
-- Official Docs: [pgbouncer.org](http://www.pgbouncer.org/)
-- Source code: [pgbouncer/pgbouncer](https://github.com/pgbouncer/pgbouncer)
-- License: [ISC](https://github.com/pgbouncer/pgbouncer/blob/master/COPYRIGHT)
-- Language: C
-
-### Kong (API Gateway)
-
-A cloud-native API gateway, built on top of Nginx.
-
-- Official Docs: [docs.konghq.com](https://docs.konghq.com/)
-- Source code: [github.com/kong/kong](https://github.com/kong/kong)
-- License: [Apache 2.0](https://github.com/Kong/kong/blob/master/LICENSE)
-- Language: Lua
-
-## Product Principles
-
-It is our goal to provide an architecture that any large-scale company would design for themselves,
-and then provide tooling around that architecture that is easy-to-use for indie-developers and small teams.
-
-We use a series of principles to ensure that scalability and usability are never mutually exclusive:
-
-### Everything works in isolation
-
-Each system must work as a standalone tool with as few moving parts as possible.
-The litmus test for this is: "Can a user run this product with nothing but a Postgres database?"
-
-### Everything is integrated
-
-Supabase is composable. Even though every product works in isolation, each product on the platform needs to 10x the other products.
-For integration, each tool should expose an API and Webhooks.
-
-### Everything is extensible
-
-We're deliberate about adding a new tool, and prefer instead to extend an existing one.
-This is the opposite of many cloud providers whose product offering expands into niche use-cases. We provide _primitives_ for developers, which allow them to achieve any goal.
-Less, but better.
-
-### Everything is portable
-
-To avoid lock-in, we make it easy to migrate in and out. Our cloud offering is compatible with our self-hosted product.
-We use existing standards to increase portability (like pg_dump an CSV files). If a new standard emerges which competes with a "Supabase" approach, we will deprecate the approach in favor of the standard.
-This forces us compete on experience. We aim to be the best Postgres hosting service.
-
-### Play the long game
-
-We sacrifice short-term wins for long-term gains. For example, it is tempting to run a fork of Postgres with additional functionality which only our customers need.
-Instead, we prefer to support efforts to upstream missing functionality so that the entire community benefits. This has the additional benefit of ensuring portability and longevity.
-
-### Build for developers
-
-"Developers" are a specific profile of user: they are _builders_.
-When assessing impact as a function of effort, developers have a large efficiency due to the type of products and systems they can build.
-As the profile of a developer changes over time, Supabase will continue to evolve the product to fit this evolving profile.
-
-### Support existing tools
-
-Supabase supports existing tools and communities wherever possible. Supabase is more like a "community of communities" - each tool typically has its own community
-which we work with.
-Open source is something we approach [collaboratively](https://supabase.com/blog/supabase-series-b#giving-back): we employ maintainers, sponsor projects, invest in businesses, and develop our own open source tools.
-
-export const Page = ({ children }) => <Layout meta={meta} children={children} />
-
-export default Page
diff --git a/apps/docs/pages/guides/tutorials.mdx b/apps/docs/pages/guides/tutorials.mdx
deleted file mode 100644
index 39f553feea8..00000000000
--- a/apps/docs/pages/guides/tutorials.mdx
+++ /dev/null
@@ -1,159 +0,0 @@
-import Layout from '~/layouts/DefaultLayout'
-import Link from 'next/link'
-import { GlassPanel } from 'ui'
-
-export const meta = {
- title: 'Tutorials',
-}
-
-### Webapps
-
-<div className="grid grid-cols-12 gap-6 not-prose">
- {webapps.map((item) => {
- return (
- <Link href={`/${item.href}`} key={item.title} passHref>
- <a className={'col-span-4'}>
- <GlassPanel title={item.title} span="col-span-6" background={false} icon={item.icon}>
- {item.description}
- </GlassPanel>
- </a>
- </Link>
- )
- })}
-</div>
-
-### Mobile
-
-<div className="grid grid-cols-12 gap-6 not-prose">
- {mobile.map((item) => {
- return (
- <Link href={`/${item.href}`} key={item.title} passHref>
- <a className={'col-span-4'}>
- <GlassPanel title={item.title} span="col-span-6" background={false} icon={item.icon}>
- {item.description}
- </GlassPanel>
- </a>
- </Link>
- )
- })}
-</div>
-
-### Low code
-
-<div className="grid grid-cols-12 gap-6 not-prose">
- {lowCode.map((item) => {
- return (
- <Link href={`/${item.href}`} key={item.title} passHref>
- <a className={'col-span-4'}>
- <GlassPanel title={item.title} span="col-span-6" background={false} icon={item.icon}>
- {item.description}
- </GlassPanel>
- </a>
- </Link>
- )
- })}
-</div>
-
-export const webapps = [
- {
- title: 'NextJS',
- href: '/guides/tutorials/with-nextjs',
- description:
- 'Learn how to build a user management app with NextJS and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/nextjs-icon',
- },
- {
- title: 'React',
- href: '/guides/tutorials/with-react',
- description:
- 'Learn how to build a user management app with React and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/react-icon',
- },
- {
- title: 'Vue 3',
- href: '/guides/tutorials/with-vue-3',
- description:
- 'Learn how to build a user management app with Vue 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/vuejs-icon',
- },
- {
- title: 'Nuxt 3',
- href: '/guides/tutorials/with-nuxt-3',
- description:
- 'Learn how to build a user management app with Nuxt 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/nuxt-icon',
- },
- {
- title: 'Anglular',
- href: '/guides/tutorials/with-angular',
- description:
- 'Learn how to build a user management app with Nuxt 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/angular-icon',
- },
- {
- title: 'RedwoodJS',
- href: '/guides/tutorials/with-redwoodjs',
- description:
- 'Learn how to build a user management app with Nuxt 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/redwood-icon',
- },
- {
- title: 'Svelte',
- href: '/guides/tutorials/with-svelte',
- description:
- 'Learn how to build a user management app with Nuxt 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/svelte-icon',
- },
- {
- title: 'SvelteKit',
- href: '/guides/tutorials/with-sveltekit',
- description:
- 'Learn how to build a user management app with Nuxt 3 and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/svelte-icon',
- },
-]
-
-export const mobile = [
- {
- title: 'Flutter',
- href: '/guides/tutorials/with-flutter',
- description:
- 'Learn how to build a user management app with Flutter and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/flutter-icon',
- },
- {
- title: 'Expo',
- href: '/guides/tutorials/with-expo',
- description:
- 'Learn how to build a user management app with React and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/expo-icon',
- },
-]
-
-export const lowCode = [
- {
- title: 'Ionic React',
- href: '/guides/tutorials/with-ionic-react',
- description:
- 'Learn how to build a user management app with React and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/ionic-icon',
- },
- {
- title: 'Ionic Vue',
- href: '/guides/tutorials/with-ionic-vue',
- description:
- 'Learn how to build a user management app with Flutter and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/ionic-icon',
- },
- {
- title: 'Ionic Angular',
- href: '/guides/tutorials/with-ionic-angular',
- description:
- 'Learn how to build a user management app with NextJS and Supabase Database, Auth, and Storage functionality.',
- icon: '/docs/img/icons/ionic-icon',
- },
-]
-
-export const Page = ({ children }) => <Layout meta={meta} children={children} />
-
-export default Page
diff --git a/apps/docs/pages/new/auth.mdx b/apps/docs/pages/new/auth.mdx
deleted file mode 100644
index 5228f5129da..00000000000
--- a/apps/docs/pages/new/auth.mdx
+++ /dev/null
@@ -1,77 +0,0 @@
-import Layout from '~/layouts/DefaultLayout'
-import Link from 'next/link'
-// import { useTheme } from 'common/Providers'
-import { GlassPanel } from 'ui'
-
-{/* // export const { isDarkMode } = useTheme() */}
-
-export const meta = {
- title: 'Auth',
-}
-
-## Add and manage email and password, passwordless, OAuth, and mobile logins to your project through a suite of identity providers and APIs.
-
-### Popular Guides
-
-<div className="grid grid-cols-12 gap-6 not-prose">
- {topArticles.map((item) => {
- return (
- <Link
- href={`/${item.href}`}
- key={item.title}
- passHref
- >
- <a className={item.span ?? 'col-span-4'}>
- <GlassPanel
- title={item.title}
- header="/docs/img/cards/sample-card-header-4.svg"
- span="col-span-6"
- background={false}
- //* isDarkMode={isDarkMode}
- >
- {item.description}
- </GlassPanel>
- </a>
- </Link>
- )})}
-
-</div>
-
-export const topArticles = [
- {
- title: 'Enable Captcha Protection',
- header: '/docs/img/cards/sample-card-header-4.svg',
- href: '/guides/auth/auth-captcha',
- description: 'Keep your platform safe from bots and malicious scripts by implementing hCaptcha.',
- span: 'col-span-6',
- },
- {
- title: 'Auth Helpers',
- header: '/docs/img/cards/sample-card-header-4.svg',
- href: '/guides/auth/auth-helpers',
- description: 'A collection of framework-specific utilities for implementing Supabase Auth.',
- span: 'col-span-6',
- },
- {
- title: 'Email Login',
- header: '/docs/img/cards/sample-card-header-4.svg',
- href: '/guides/auth/auth-email',
- description: 'Learn how to add an email and password login flow to your platform.',
- },
- {
- title: 'Phone Login',
- header: '/docs/img/cards/sample-card-header-4.svg',
- href: '/guides/auth/phone-login',
- description: 'Learn how to add a login flow so your users can access your platform through one-time passwords via SMS.',
- },
- {
- title: 'Social Login',
- header: '/docs/img/cards/sample-card-header-4.svg',
- href: '/guides/auth/social-login',
- description: 'Learn how to add a login flow so your users can access your platform through social providers like Apple, Facebook, or Google.',
- },
-]
-
-export const Page = ({ children }) => <Layout meta={meta} children={children} />
-
-export default Page
diff --git a/apps/docs/pages/ref-pages.mdx b/apps/docs/pages/ref-pages.mdx
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/apps/docs/pages/tutorials/nextjs.mdx b/apps/docs/pages/tutorials/nextjs.mdx
deleted file mode 100644
index 5e22b391296..00000000000
--- a/apps/docs/pages/tutorials/nextjs.mdx
+++ /dev/null
@@ -1,724 +0,0 @@
-import Layout from '~/layouts/tutorials/TutorialLayout'
-
-export const meta = {
- title: 'Creating a user management dashboard with NextJS and Supabase',
- author: 'Rich Haines',
- video: 'https://www.youtube-nocookie.com/embed/0Fs96oZ4se0',
-}
-
-In this 25-minute guide, we’ll be building a collaborative user managment app using NextJS and Supabase.
-As users add and move rectangles in a canvas, changes will be automatically synced and persisted, allowing for a canvas that updates in real-time across clients.
-Users will also be able to see other users selections, and undo and redo actions.
-
-![Supabase User Management example](/docs/img/user-management-demo.png)
-
-### GitHub
-
-Should you get stuck while working through the guide, refer to [this repo](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management).
-
-## Building the App
-
-Let's start building the Next.js app from scratch.
-
-### Initialize a Next.js app
-
-We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize
-an app called `supabase-nextjs`:
-
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="js"
->
-<Tabs.Panel id="js" label="JavaScript">
-
-```bash
-npx create-next-app@latest --use-npm supabase-nextjs
-cd supabase-nextjs
-```
-
-</Tabs.Panel>
-<Tabs.Panel id="ts" label="TypeScript">
-
-```bash
-npx create-next-app@latest --ts --use-npm supabase-nextjs
-cd supabase-nextjs
-```
-
-</Tabs.Panel>
-</Tabs>
-
-Then install the Supabase client library: [supabase-js](https://github.com/supabase/supabase-js)
-
-```bash
-npm install @supabase/supabase-js
-```
-
-And finally we want to save the environment variables in a `.env.local`.
-All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).
-
-```bash title=.env.local
-NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
-NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
-```
-
-And one optional step is to update the CSS file `styles/globals.css` to make the app look nice.
-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/nextjs-ts-user-management/styles/globals.css).
-
-### Set up a Login component
-
-#### Supabase Auth Helpers
-
-Next.js is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and middleware edge-functions.
-
-It can be challenging to authenticate your users in all these different environments, that's why we've created the [Supabase Auth Helpers](https://supabase.com/docs/guides/auth/auth-helpers/nextjs) to make user management and data fetching within Next.js as easy as possible.
-
-Install the auth helpers for React and Next.js
-
-```bash
-npm install @supabase/auth-helpers-react @supabase/auth-helpers-nextjs
-```
-
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="js"
->
-<Tabs.Panel id="js" label="JavaScript">
-
-Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
-
-```jsx title=pages/_app.js
-import '../styles/globals.css'
-import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { SessionContextProvider } from '@supabase/auth-helpers-react'
-
-function MyApp({ Component, pageProps }) {
- const [supabaseClient] = useState(() => createBrowserSupabaseClient())
-
- return (
- <SessionContextProvider
- supabaseClient={supabaseClient}
- initialSession={pageProps.initialSession}
- >
- <Component {...pageProps} />
- </SessionContextProvider>
- )
-}
-export default MyApp
-```
-
-</Tabs.Panel>
-<Tabs.Panel id="ts" label="TypeScript">
-
-Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
-
-```jsx lines=2,8 title=pages/_app.tsx
-import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
-
-function MyApp({
- Component,
- pageProps,
-}: AppProps<{
- initialSession: Session,
-}>) {
- const [supabaseClient] = useState(() => createBrowserSupabaseClient())
-
- return (
- <SessionContextProvider
- supabaseClient={supabaseClient}
- initialSession={pageProps.initialSession}
- >
- <Component {...pageProps} />
- </SessionContextProvider>
- )
-}
-export default MyApp
-```
-
-See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.
-
-</Tabs.Panel>
-</Tabs>
-
-#### Supabase Auth UI
-
-We can use the [Supabase Auth UI](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui) a pre-built React component for authenticating users via OAuth, email, and magic links.
-
-Install the Supabase Auth UI for React
-
-```bash
-npm install @supabase/auth-ui-react
-```
-
-Add the `Auth` component to your home page
-
-```jsx title=pages/index.js
-import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
-import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
-
-const Home = () => {
- const session = useSession()
- const supabase = useSupabaseClient()
-
- return (
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {!session ? (
- <Auth supabaseClient={supabase} appearance={{ theme: ThemeSupa }} theme="dark" />
- ) : (
- <p>Account page will go here.</p>
- )}
- </div>
- )
-}
-
-export default Home
-```
-
-### Account page
-
-After a user is signed in we can allow them to edit their profile details and manage their account.
-
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="js"
->
-<Tabs.Panel id="js" label="JavaScript">
-
-Let's create a new component for that called `Account.js` within a `components` folder.
-
-```tsx title=components/Account.js
-import { useState, useEffect } from 'react'
-import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
-
-export default function Account({ session }) {
- const supabase = useSupabaseClient()
- const user = useUser()
- const [loading, setLoading] = useState(true)
- const [username, setUsername] = useState(null)
- const [website, setWebsite] = useState(null)
- const [avatar_url, setAvatarUrl] = useState(null)
-
- useEffect(() => {
- getProfile()
- }, [session])
-
- async function getProfile() {
- try {
- setLoading(true)
-
- let { data, error, status } = await supabase
- .from('profiles')
- .select(`username, website, avatar_url`)
- .eq('id', user.id)
- .single()
-
- if (error && status !== 406) {
- throw error
- }
-
- if (data) {
- setUsername(data.username)
- setWebsite(data.website)
- setAvatarUrl(data.avatar_url)
- }
- } catch (error) {
- alert('Error loading user data!')
- console.log(error)
- } finally {
- setLoading(false)
- }
- }
-
- async function updateProfile({ username, website, avatar_url }) {
- try {
- setLoading(true)
-
- const updates = {
- id: user.id,
- username,
- website,
- avatar_url,
- updated_at: new Date().toISOString(),
- }
-
- let { error } = await supabase.from('profiles').upsert(updates)
- if (error) throw error
- alert('Profile updated!')
- } catch (error) {
- alert('Error updating the data!')
- console.log(error)
- } finally {
- setLoading(false)
- }
- }
-
- return (
- <div className="form-widget">
- <div>
- <label htmlFor="email">Email</label>
- <input id="email" type="text" value={session.user.email} disabled />
- </div>
- <div>
- <label htmlFor="username">Username</label>
- <input
- id="username"
- type="text"
- value={username || ''}
- onChange={(e) => setUsername(e.target.value)}
- />
- </div>
- <div>
- <label htmlFor="website">Website</label>
- <input
- id="website"
- type="website"
- value={website || ''}
- onChange={(e) => setWebsite(e.target.value)}
- />
- </div>
-
- <div>
- <button
- className="button primary block"
- onClick={() => updateProfile({ username, website, avatar_url })}
- disabled={loading}
- >
- {loading ? 'Loading ...' : 'Update'}
- </button>
- </div>
-
- <div>
- <button className="button block" onClick={() => supabase.auth.signOut()}>
- Sign Out
- </button>
- </div>
- </div>
- )
-}
-```
-
-</Tabs.Panel>
-<Tabs.Panel id="ts" label="TypeScript">
-
-Let's create a new component for that called `Account.tsx` within a `components` folder.
-
-```tsx title=components/Account.tsx
-import { useState, useEffect } from 'react'
-import { useUser, useSupabaseClient, Session } from '@supabase/auth-helpers-react'
-import { Database } from '../utils/database.types'
-type Profiles = Database['public']['Tables']['profiles']['Row']
-
-export default function Account({ session }: { session: Session }) {
- const supabase = useSupabaseClient<Database>()
- const user = useUser()
- const [loading, setLoading] = useState(true)
- const [username, setUsername] = useState<Profiles['username']>(null)
- const [website, setWebsite] = useState<Profiles['website']>(null)
- const [avatar_url, setAvatarUrl] = useState<Profiles['avatar_url']>(null)
-
- useEffect(() => {
- getProfile()
- }, [session])
-
- async function getProfile() {
- try {
- setLoading(true)
- if (!user) throw new Error('No user')
-
- let { data, error, status } = await supabase
- .from('profiles')
- .select(`username, website, avatar_url`)
- .eq('id', user.id)
- .single()
-
- if (error && status !== 406) {
- throw error
- }
-
- if (data) {
- setUsername(data.username)
- setWebsite(data.website)
- setAvatarUrl(data.avatar_url)
- }
- } catch (error) {
- alert('Error loading user data!')
- console.log(error)
- } finally {
- setLoading(false)
- }
- }
-
- async function updateProfile({
- username,
- website,
- avatar_url,
- }: {
- username: Profiles['username']
- website: Profiles['website']
- avatar_url: Profiles['avatar_url']
- }) {
- try {
- setLoading(true)
- if (!user) throw new Error('No user')
-
- const updates = {
- id: user.id,
- username,
- website,
- avatar_url,
- updated_at: new Date().toISOString(),
- }
-
- let { error } = await supabase.from('profiles').upsert(updates)
- if (error) throw error
- alert('Profile updated!')
- } catch (error) {
- alert('Error updating the data!')
- console.log(error)
- } finally {
- setLoading(false)
- }
- }
-
- return (
- <div className="form-widget">
- <div>
- <label htmlFor="email">Email</label>
- <input id="email" type="text" value={session.user.email} disabled />
- </div>
- <div>
- <label htmlFor="username">Username</label>
- <input
- id="username"
- type="text"
- value={username || ''}
- onChange={(e) => setUsername(e.target.value)}
- />
- </div>
- <div>
- <label htmlFor="website">Website</label>
- <input
- id="website"
- type="website"
- value={website || ''}
- onChange={(e) => setWebsite(e.target.value)}
- />
- </div>
-
- <div>
- <button
- className="button primary block"
- onClick={() => updateProfile({ username, website, avatar_url })}
- disabled={loading}
- >
- {loading ? 'Loading ...' : 'Update'}
- </button>
- </div>
-
- <div>
- <button className="button block" onClick={() => supabase.auth.signOut()}>
- Sign Out
- </button>
- </div>
- </div>
- )
-}
-```
-
-</Tabs.Panel>
-</Tabs>
-
-### Launch!
-
-Now that we have all the components in place, let's update `pages/index.js`:
-
-```jsx lines=3,14 title=pages/index.js
-import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
-import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
-import Account from '../components/Account'
-
-const Home = () => {
- const session = useSession()
- const supabase = useSupabaseClient()
-
- return (
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {!session ? (
- <Auth supabaseClient={supabase} appearance={{ theme: ThemeSupa }} theme="dark" />
- ) : (
- <Account session={session} />
- )}
- </div>
- )
-}
-
-export default Home
-```
-
-Once that's done, run this in a terminal window:
-
-```bash
-npm run dev
-```
-
-And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
-
-## Bonus: Profile photos
-
-Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like
-photos and videos.
-
-### Create an upload widget
-
-Let's create an avatar widget for the user so that they can upload a profile photo. We can start by creating a new component:
-
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="js"
->
-<Tabs.Panel id="js" label="JavaScript">
-
-```jsx title=components/Avatar.js
-import React, { useEffect, useState } from 'react'
-import { useSupabaseClient } from '@supabase/auth-helpers-react'
-
-export default function Avatar({ uid, url, size, onUpload }) {
- const supabase = useSupabaseClient()
- const [avatarUrl, setAvatarUrl] = useState(null)
- const [uploading, setUploading] = useState(false)
-
- useEffect(() => {
- if (url) downloadImage(url)
- }, [url])
-
- async function downloadImage(path) {
- try {
- const { data, error } = await supabase.storage.from('avatars').download(path)
- if (error) {
- throw error
- }
- const url = URL.createObjectURL(data)
- setAvatarUrl(url)
- } catch (error) {
- console.log('Error downloading image: ', error)
- }
- }
-
- const uploadAvatar = async (event) => {
- try {
- setUploading(true)
-
- if (!event.target.files || event.target.files.length === 0) {
- throw new Error('You must select an image to upload.')
- }
-
- const file = event.target.files[0]
- const fileExt = file.name.split('.').pop()
- const fileName = `${uid}.${fileExt}`
- const filePath = `${fileName}`
-
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file, { upsert: true })
-
- if (uploadError) {
- throw uploadError
- }
-
- onUpload(filePath)
- } catch (error) {
- alert('Error uploading avatar!')
- console.log(error)
- } finally {
- setUploading(false)
- }
- }
-
- return (
- <div>
- {avatarUrl ? (
- <img
- src={avatarUrl}
- alt="Avatar"
- className="avatar image"
- style={{ height: size, width: size }}
- />
- ) : (
- <div className="avatar no-image" style={{ height: size, width: size }} />
- )}
- <div style={{ width: size }}>
- <label className="button primary block" htmlFor="single">
- {uploading ? 'Uploading ...' : 'Upload'}
- </label>
- <input
- style={{
- visibility: 'hidden',
- position: 'absolute',
- }}
- type="file"
- id="single"
- accept="image/*"
- onChange={uploadAvatar}
- disabled={uploading}
- />
- </div>
- </div>
- )
-}
-```
-
-</Tabs.Panel>
-<Tabs.Panel id="ts" label="TypeScript">
-
-```tsx title=components/Avatar.tsx
-import React, { useEffect, useState } from 'react'
-import { useSupabaseClient } from '@supabase/auth-helpers-react'
-import { Database } from '../utils/database.types'
-type Profiles = Database['public']['Tables']['profiles']['Row']
-
-export default function Avatar({
- uid,
- url,
- size,
- onUpload,
-}: {
- uid: string
- url: Profiles['avatar_url']
- size: number
- onUpload: (url: string) => void
-}) {
- const supabase = useSupabaseClient<Database>()
- const [avatarUrl, setAvatarUrl] = useState<Profiles['avatar_url']>(null)
- const [uploading, setUploading] = useState(false)
-
- useEffect(() => {
- if (url) downloadImage(url)
- }, [url])
-
- async function downloadImage(path: string) {
- try {
- const { data, error } = await supabase.storage.from('avatars').download(path)
- if (error) {
- throw error
- }
- const url = URL.createObjectURL(data)
- setAvatarUrl(url)
- } catch (error) {
- console.log('Error downloading image: ', error)
- }
- }
-
- const uploadAvatar: React.ChangeEventHandler<HTMLInputElement> = async (event) => {
- try {
- setUploading(true)
-
- if (!event.target.files || event.target.files.length === 0) {
- throw new Error('You must select an image to upload.')
- }
-
- const file = event.target.files[0]
- const fileExt = file.name.split('.').pop()
- const fileName = `${uid}.${fileExt}`
- const filePath = `${fileName}`
-
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file, { upsert: true })
-
- if (uploadError) {
- throw uploadError
- }
-
- onUpload(filePath)
- } catch (error) {
- alert('Error uploading avatar!')
- console.log(error)
- } finally {
- setUploading(false)
- }
- }
-
- return (
- <div>
- {avatarUrl ? (
- <img
- src={avatarUrl}
- alt="Avatar"
- className="avatar image"
- style={{ height: size, width: size }}
- />
- ) : (
- <div className="avatar no-image" style={{ height: size, width: size }} />
- )}
- <div style={{ width: size }}>
- <label className="button primary block" htmlFor="single">
- {uploading ? 'Uploading ...' : 'Upload'}
- </label>
- <input
- style={{
- visibility: 'hidden',
- position: 'absolute',
- }}
- type="file"
- id="single"
- accept="image/*"
- onChange={uploadAvatar}
- disabled={uploading}
- />
- </div>
- </div>
- )
-}
-```
-
-</Tabs.Panel>
-</Tabs>
-
-### Add the new widget
-
-And then we can add the widget to the Account page:
-
-```jsx title=components/Account.js
-// Import the new component
-import Avatar from './Avatar'
-
-// ...
-
-return (
- <div className="form-widget">
- {/* Add to the body */}
- <Avatar
- uid={user.id}
- url={avatar_url}
- size={150}
- onUpload={(url) => {
- setAvatarUrl(url)
- updateProfile({ username, website, avatar_url: url })
- }}
- />
- {/* ... */}
- </div>
-)
-```
-
-## Next steps
-
-At this stage you have a fully functional application!
-
-- See the complete [example on GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management) and deploy it to Vercel.
-- Explore the [pre-built Auth UI for React](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui).
-- Explore the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs).
-- Explore the [Supabase Cache Helpers](https://github.com/psteinroe/supabase-cache-helpers).
-- See the [Next.js Subscription Payments Starter](https://github.com/vercel/nextjs-subscription-payments) template on GitHub.
-- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).
-- Sign in: [app.supabase.com](https://app.supabase.com)
-
-export default ({ children }) => <Layout meta={meta} children={children} />