Skip to content

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

Merge branch 'master' into feat/codehike-v2

Greg Richardson86f78bed258a
diff --cc apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
index 21bc1179e9f,d54980827e2..ecfa0af0cbe
--- a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
@@@ -101,56 -87,84 +87,82 @@@ npm install @supabase/auth-helpers-next
>
<TabPanel id="js" label="JavaScript">
- Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
+ Create a `middleware.js` file and include the following content to:
- ```jsx pages/_app.js
- import '../styles/globals.css'
- import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
- import { SessionContextProvider } from '@supabase/auth-helpers-react'
- import { useState } from 'react'
+ - Verify if there is an authenticated Supabase user
+ - Validate if the user is authenticated and currently on the sign-in page, redirecting them to the `account` page
+ - Verify if the user is not authenticated and currently on the account page, redirecting them to the `sign-in` page.
- function MyApp({ Component, pageProps }) {
- const [supabase] = useState(() => createBrowserSupabaseClient())
-```tsx title=middleware.js
-// middleware.js
++```tsx middleware.js
+ import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
+ import { NextResponse } from 'next/server'
- return (
- <SessionContextProvider supabaseClient={supabase} initialSession={pageProps.initialSession}>
- <Component {...pageProps} />
- </SessionContextProvider>
- )
+ export async function middleware(req) {
+ const res = NextResponse.next()
+ const supabase = createMiddlewareClient({ req, res })
+
+ const {
+ data: { user },
+ } = await supabase.auth.getUser()
+
+ // if user is signed in and the current path is / redirect the user to /account
+ if (user && req.nextUrl.pathname === '/') {
+ return NextResponse.redirect(new URL('/account', req.url))
+ }
+
+ // if user is not signed in and the current path is not / redirect the user to /
+ if (!user && req.nextUrl.pathname !== '/') {
+ return NextResponse.redirect(new URL('/', req.url))
+ }
+
+ return res
+ }
+
+ export const config = {
+ matcher: ['/', '/account'],
}
- export default MyApp
```
</TabPanel>
<TabPanel id="ts" label="TypeScript">
- Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
+ Create a `middleware.ts` file and include the following content to:
- ```jsx mark=2,8 pages/_app.tsx
- import '../styles/globals.css'
- import { useState } from 'react'
- import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
- import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
- import { AppProps } from 'next/app'
+ - Verify if there is an authenticated Supabase user
+ - Validate if the user is authenticated and currently on the sign-in page, redirecting them to the `account` page
+ - Verify if the user is not authenticated and currently on the account page, redirecting them to the `sign-in` page.
- function MyApp({
- Component,
- pageProps,
- }: AppProps<{
- initialSession: Session,
- }>) {
- const [supabase] = useState(() => createBrowserSupabaseClient())
-```tsx title=middleware.ts
-// middleware.ts
++```tsx middleware.ts
+ import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
+ import { NextResponse } from 'next/server'
- return (
- <SessionContextProvider supabaseClient={supabase} initialSession={pageProps.initialSession}>
- <Component {...pageProps} />
- </SessionContextProvider>
- )
+ import type { NextRequest } from 'next/server'
+
+ export async function middleware(req: NextRequest) {
+ const res = NextResponse.next()
+ const supabase = createMiddlewareClient({ req, res })
+
+ const {
+ data: { user },
+ } = await supabase.auth.getUser()
+
+ // if user is signed in and the current path is / redirect the user to /account
+ if (user && req.nextUrl.pathname === '/') {
+ return NextResponse.redirect(new URL('/account', req.url))
+ }
+
+ // if user is not signed in and the current path is not / redirect the user to /
+ if (!user && req.nextUrl.pathname !== '/') {
+ return NextResponse.redirect(new URL('/', req.url))
+ }
+
+ return res
}
- export default MyApp
- ```
- See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.
+ export const config = {
+ matcher: ['/', '/account'],
+ }
+ ```
</TabPanel>
</Tabs>
@@@ -162,34 -178,226 +176,219 @@@ We can use the [Supabase Auth UI](/docs
Install the Supabase Auth UI for React
```bash
- npm install @supabase/auth-ui-react
+ npm install @supabase/auth-ui-react @supabase/auth-ui-shared
```
- Add the `Auth` component to your home page
+ Create an `AuthForm` client side component with the `Auth` component rendered within it:
+
+ <Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="js"
+ >
+ <TabPanel id="js" label="JavaScript">
- ```jsx pages/index.js
-```jsx title=app/auth-form.jsx
-// app/auth-form.jsx
++```jsx app/auth-form.jsx
+ 'use client'
import { Auth } from '@supabase/auth-ui-react'
import { ThemeSupa } from '@supabase/auth-ui-shared'
- import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
+ import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
- const Home = () => {
- const session = useSession()
- const supabase = useSupabaseClient()
+ export default function AuthForm() {
+ const supabase = createClientComponentClient()
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>
- )}
+ <Auth
+ supabaseClient={supabase}
+ view="magic_link"
+ appearance={{ theme: ThemeSupa }}
+ theme="dark"
+ showLinks={false}
+ providers={[]}
+ redirectTo="http://localhost:3000/auth/callback"
+ />
+ )
+ }
+ ```
+
+ </TabPanel>
+ <TabPanel id="ts" label="TypeScript">
+
-```jsx title=app/auth-form.tsx
-// app/auth-form.tsx
++```jsx app/auth-form.tsx
+ 'use client'
+ import { Auth } from '@supabase/auth-ui-react'
+ import { ThemeSupa } from '@supabase/auth-ui-shared'
+ import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+ import { Database } from './database.types'
+
+ export default function AuthForm() {
+ const supabase = createClientComponentClient<Database>()
+
+ return (
+ <Auth
+ supabaseClient={supabase}
+ view="magic_link"
+ appearance={{ theme: ThemeSupa }}
+ theme="dark"
+ showLinks={false}
+ providers={[]}
+ redirectTo="http://localhost:3000/auth/callback"
+ />
+ )
+ }
+ ```
+
+ </TabPanel>
+ </Tabs>
+
+ Add the `AuthForm` component to your home page
+
-```jsx title=app/page.js
-// app/page.[j|t]sx
++```jsx app/page.js
+ import AuthForm from './auth-form'
+
+ export default function Home() {
+ return (
+ <div className="row">
+ <div className="col-6">
+ <h1 className="header">Supabase Auth + Storage</h1>
+ <p className="">
+ Experience our Auth and Storage through a simple profile management example. Create a user
+ profile and upload an avatar image. Fast, simple, secure.
+ </p>
+ </div>
+ <div className="col-6 auth-widget">
+ <AuthForm />
+ </div>
</div>
)
}
+ ```
+
+ ### Proof Key for Code Exchange (PKCE)
+
+ As we are employing Proof Key for Code Exchange (PKCE) in our authentication flow, it is necessary to create a route handler responsible for exchanging the code for a session.
+
+ In the following code snippet, we perform the following steps:
+
+ - Retrieve the code sent back from the Supabase Auth server using the `code` query parameter.
+ - Exchange this code for a session, which we store in our chosen storage mechanism (in this case, cookies).
+ - Finally, we redirect the user to the `account` page.
+
+ <Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="js"
+ >
+ <TabPanel id="js" label="JavaScript">
+
-```js title=app/auth/callback/route.js
-// app/auth/callback/route.js
++```js app/auth/callback/route.js
+ import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import { NextResponse } from 'next/server'
+
+ export async function GET(req) {
+ const supabase = createRouteHandlerClient({ cookies })
+ const { searchParams } = new URL(req.url)
+ const code = searchParams.get('code')
+
+ if (code) {
+ await supabase.auth.exchangeCodeForSession(code)
+ }
+
+ return NextResponse.redirect(new URL('/account', req.url))
+ }
+ ```
+
+ </TabPanel>
+ <TabPanel id="ts" label="TypeScript">
- export default Home
-```ts title=app/auth/callback/route.ts
-// app/auth/callback/route.ts
++```ts app/auth/callback/route.ts
+ import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import { NextRequest, NextResponse } from 'next/server'
+
+ export async function GET(req: NextRequest) {
+ const supabase = createRouteHandlerClient({ cookies })
+ const { searchParams } = new URL(req.url)
+ const code = searchParams.get('code')
+
+ if (code) {
+ await supabase.auth.exchangeCodeForSession(code)
+ }
+
+ return NextResponse.redirect(new URL('/account', req.url))
+ }
```
+ </TabPanel>
+ </Tabs>
+
+ ### Sign out
+
+ Let's create an route handler to handle the signout from the server side.
+
+ <Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="js"
+ >
+ <TabPanel id="js" label="JavaScript">
+
-```js title=app/auth/signout/route.js
-// app/auth/signout/route.js
++```js app/auth/signout/route.js
+ import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import { NextResponse } from 'next/server'
+
+ export async function POST(req) {
+ const supabase = createRouteHandlerClient({ cookies })
+
+ // Check if we have a session
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
+
+ if (session) {
+ await supabase.auth.signOut()
+ }
+
+ return NextResponse.redirect(new URL('/', req.url), {
+ status: 302,
+ })
+ }
+ ```
+
+ </TabPanel>
+ <TabPanel id="ts" label="TypeScript">
+
-```ts title=app/auth/signout/route.ts
-// app/auth/signout/route.ts
++```ts app/auth/signout/route.ts
+ import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import { type NextRequest, NextResponse } from 'next/server'
+
+ export async function POST(req: NextRequest) {
+ const supabase = createRouteHandlerClient({ cookies })
+
+ // Check if we have a session
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
+
+ if (session) {
+ await supabase.auth.signOut()
+ }
+
+ return NextResponse.redirect(new URL('/', req.url), {
+ status: 302,
+ })
+ }
+ ```
+
+ </TabPanel>
+ </Tabs>
+
### Account page
After a user is signed in we can allow them to edit their profile details and manage their account.
@@@ -202,16 -412,16 +403,15 @@@ Let's create a new component for that c
>
<TabPanel id="js" label="JavaScript">
- Let's create a new component for that called `Account.js` within a `components` folder.
-```jsx title=app/account/account-form.jsx
-// app/account/account-form.jsx
++```jsx app/account/account-form.jsx
+ 'use client'
+ import { useCallback, useEffect, useState } from 'react'
+ import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
- ```tsx 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()
+ export default function AccountForm({ session }) {
+ const supabase = createClientComponentClient()
const [loading, setLoading] = useState(true)
+ const [fullname, setFullname] = useState(null)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
const [avatar_url, setAvatarUrl] = useState(null)
@@@ -318,32 -542,25 +532,24 @@@
</TabPanel>
<TabPanel id="ts" label="TypeScript">
- 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 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']
-```tsx title=app/account/account-form.tsx
-// app/account/account-form.tsx
++```tsx app/account/account-form.tsx
+ 'use client'
+ import { useCallback, useEffect, useState } from 'react'
+ import { Database } from '../database.types'
+ import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'
- export default function Account({ session }: { session: Session }) {
- const supabase = useSupabaseClient<Database>()
- const user = useUser()
+ export default function AccountForm({ session }: { session: Session | null }) {
+ const supabase = createClientComponentClient<Database>()
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])
+ const [fullname, setFullname] = useState<string | null>(null)
+ const [username, setUsername] = useState<string | null>(null)
+ const [website, setWebsite] = useState<string | null>(null)
+ const [avatar_url, setAvatarUrl] = useState<string | null>(null)
+ const user = session?.user
- async function getProfile() {
+ const getProfile = useCallback(async () => {
try {
setLoading(true)
- if (!user) throw new Error('No user')
let { data, error, status } = await supabase
.from('profiles')
@@@ -448,35 -678,60 +667,58 @@@
</TabPanel>
</Tabs>
- ### Launch!
+ Create a account page for the `AccountForm` component we just created
- Now that we have all the components in place, let's update `pages/index.js`:
+ <Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="js"
+ >
+ <TabPanel id="js" label="JavaScript">
- ```jsx mark=3,14 pages/index.js
- import { Auth } from '@supabase/auth-ui-react'
- import { ThemeSupa } from '@supabase/auth-ui-shared'
- import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
- import Account from '../components/Account'
-```jsx title=app/account/page.jsx
-// app/account/page.jsx
++```jsx app/account/page.jsx
+ import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import AccountForm from './account-form'
- const Home = () => {
- const session = useSession()
- const supabase = useSupabaseClient()
+ export default async function Account() {
+ const supabase = createServerComponentClient({ cookies })
- return (
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {!session ? (
- <Auth supabaseClient={supabase} appearance={{ theme: ThemeSupa }} theme="dark" />
- ) : (
- <Account session={session} />
- )}
- </div>
- )
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
+
+ return <AccountForm session={session} />
}
+ ```
+
+ </TabPanel>
+ <TabPanel id="ts" label="TypeScript">
+
-```tsx title=app/account/page.tsx
-// app/account/page.tsx
++```tsx app/account/page.tsx
+ import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
+ import { cookies } from 'next/headers'
+ import { Database } from '../database.types'
+ import AccountForm from './account-form'
- export default Home
+ export default async function Account() {
+ const supabase = createServerComponentClient<Database>({ cookies })
+
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
+
+ return <AccountForm session={session} />
+ }
```
- Once that's done, run this in a terminal window:
+ </TabPanel>
+ </Tabs>
+
+ ### Launch!
+
+ Now that we have all the pages, route handlers and components in place, let's run this in a terminal window:
```bash
npm run dev
@@@ -501,12 -756,14 +743,14 @@@ Let's create an avatar widget for the u
>
<TabPanel id="js" label="JavaScript">
- ```jsx components/Avatar.js
-```jsx title=app/account/avatar.jsx
++```jsx app/account/avatar.jsx
+ 'use client'
import React, { useEffect, useState } from 'react'
- import { useSupabaseClient } from '@supabase/auth-helpers-react'
+ import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+ import Image from 'next/image'
export default function Avatar({ uid, url, size, onUpload }) {
- const supabase = useSupabaseClient()
+ const supabase = createClientComponentClient()
const [avatarUrl, setAvatarUrl] = useState(null)
const [uploading, setUploading] = useState(false)
@@@ -593,10 -849,12 +836,12 @@@
</TabPanel>
<TabPanel id="ts" label="TypeScript">
- ```tsx components/Avatar.tsx
-```tsx title=app/account/avatar.tsx
++```tsx app/account/avatar.tsx
+ 'use client'
import React, { useEffect, useState } from 'react'
- import { useSupabaseClient } from '@supabase/auth-helpers-react'
- import { Database } from '../utils/database.types'
+ import { Database } from '../database.types'
+ import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+ import Image from 'next/image'
type Profiles = Database['public']['Tables']['profiles']['Row']
export default function Avatar({
@@@ -699,11 -956,12 +943,11 @@@
### Add the new widget
- And then we can add the widget to the Account page:
+ And then we can add the widget to the `AccountForm` component:
- ```jsx components/Account.js
-```jsx title=app/account/account-form.js
-// app/account/account-form.[j|t]sx
++```jsx app/account/account-form.js
// Import the new component
- import Avatar from './Avatar'
+ import Avatar from './avatar'
// ...
diff --cc apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
index 37c81437e9f,e36b61ce214..ca9ce871676
--- a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
@@@ -116,11 -115,9 +115,9 @@@ declare global
Create a new `src/routes/+layout.server.ts` file to handle the session on the server-side.
-```ts title=src/routes/+layout.server.ts
+```ts src/routes/+layout.server.ts
// src/routes/+layout.server.ts
- import type { LayoutServerLoad } from './$types'
-
- export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {
+ export const load = async ({ locals: { getSession } }) => {
return {
session: await getSession(),
}
@@@ -158,16 -154,17 +154,17 @@@ export const load = async ({ fetch, dat
Update your `src/routes/+layout.svelte`:
-```svelte title=src/routes/+layout.svelte
+```svelte src/routes/+layout.svelte
<!-- src/routes/+layout.svelte -->
<script lang="ts">
- import '../styles.css';
- import { invalidate } from '$app/navigation';
- import { onMount } from 'svelte';
+ import '../styles.css'
+ import { invalidate } from '$app/navigation'
+ import { onMount } from 'svelte'
- export let data;
+ export let data
- $: ({ supabase, session } = data);
+ let { supabase, session } = data
+ $: ({ supabase, session } = data)
onMount(() => {
const { data } = supabase.auth.onAuthStateChange((event, _session) => {
@@@ -203,13 -200,13 +200,13 @@@ npm install @supabase/auth-ui-svelte @s
Add the `Auth` component to your home page
-```svelte title=src/routes/+page.svelte
+```svelte src/routes/+page.svelte
<!-- src/routes/+page.svelte -->
<script lang="ts">
- import { Auth } from '@supabase/auth-ui-svelte';
- import { ThemeSupa } from '@supabase/auth-ui-shared';
+ import { Auth } from '@supabase/auth-ui-svelte'
+ import { ThemeSupa } from '@supabase/auth-ui-shared'
- export let data;
+ export let data
</script>
<svelte:head>
@@@ -289,27 -304,28 +304,28 @@@ export const GET = async ({ url, locals
After a user is signed in, they need to be able to edit their profile details and manage their account.
Create a new `src/routes/account/+page.svelte` file with the content below.
-```svelte title=src/routes/account/+page.svelte
+```svelte src/routes/account/+page.svelte
<!-- src/routes/account/+page.svelte -->
<script lang="ts">
- import { enhance, type SubmitFunction } from '$app/forms';
+ import { enhance, type SubmitFunction } from '$app/forms'
- export let data;
- export let form;
+ export let data
+ export let form
- let { session, supabase, profile } = data;
+ let { session, supabase, profile } = data
+ $: ({ session, supabase, profile } = data)
- let profileForm: any;
- let loading = false;
- let fullName: string = profile?.full_name ?? '';
- let username: string = profile?.username ?? '';
- let website: string = profile?.website ?? '';
- let avatarUrl: string = profile?.avatar_url ?? '';
+ let profileForm: HTMLFormElement
+ let loading = false
+ let fullName: string = profile?.full_name ?? ''
+ let username: string = profile?.username ?? ''
+ let website: string = profile?.website ?? ''
+ let avatarUrl: string = profile?.avatar_url ?? ''
const handleSubmit: SubmitFunction = () => {
- loading = true;
+ loading = true
return async () => {
- loading = false;
+ loading = false
}
}
@@@ -456,21 -471,21 +471,21 @@@ Every Supabase project is configured wi
Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component called `Avatar.svelte` in the `src/routes/account` directory:
-```svelte title=src/routes/account/Avatar.svelte
+```svelte src/routes/account/Avatar.svelte
<!-- src/routes/account/Avatar.svelte -->
<script lang="ts">
- import type { SupabaseClient } from '@supabase/supabase-js';
- import { createEventDispatcher } from 'svelte';
+ import type { SupabaseClient } from '@supabase/supabase-js'
+ import { createEventDispatcher } from 'svelte'
- export let size = 10;
- export let url: string;
- export let supabase: SupabaseClient;
+ export let size = 10
+ export let url: string
+ export let supabase: SupabaseClient
- let avatarUrl: string | null = null;
- let uploading = false;
- let files: FileList;
+ let avatarUrl: string | null = null
+ let uploading = false
+ let files: FileList
- const dispatch = createEventDispatcher();
+ const dispatch = createEventDispatcher()
const downloadImage = async (path: string) => {
try {