The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Changes from PR #10796
dannykng179d5a27f6e4
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.mdxindex 35861d98c86..614f31625c1 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@@ -10,6 +10,8 @@ export const meta = {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).+> 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).## Install the Next.js helper library@@ -52,6 +54,8 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY## Creating a Supabase Client+### Server-side+<Tabsscrollablesize="small"@@ -60,23 +64,13 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY><TabPanel id="js" label="JavaScript">-Create a new file at `/utils/supabase-browser.js` and populate with the following:--```js title="/utils/supabase-browser.js"-import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'--export default createBrowserSupabaseClient()-```--This will be used any time we need to create a Supabase client _client-side_ - in `useEffect`, for example.-Create a new file at `/utils/supabase-server.js` and populate with the following:```js title="/utils/supabase-server.js"import { headers, cookies } from 'next/headers'import { createServerComponentSupabaseClient } from '@supabase/auth-helpers-nextjs'-export default () =>+export const createClient = () =>createServerComponentSupabaseClient({headers,cookies,@@ -85,33 +79,19 @@ export default () =>> 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.-</TabPanel><TabPanel id="ts" label="TypeScript">-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 default createBrowserSupabaseClient<Database>()-```--> 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.--This will be used any time we need to create a Supabase client _client-side_ - in `useEffect`, for example.-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 { Database } from '../lib/database.types'-export default () =>+import type { Database } from '../db_types'++export const createClient = () =>createServerComponentSupabaseClient<Database>({headers,cookies,@@ -122,14 +102,12 @@ export default () =>> 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.-</TabPanel></Tabs>-## Middleware+This will be used any time we need to create a Supabase client _server-side_ - in a Server Component, for example.-Middleware runs before every route declared in the `matcher` array. Since we don't have access to set cookies or headers from Server Components, we need to create a Middleware Supabase client and refresh the user's session by calling `getSession()`.+Next, we need a middleware file to refresh the user's session on navigation.<Tabsscrollable@@ -139,8 +117,6 @@ Middleware runs before every route declared in the `matcher` array. Since we don><TabPanel id="js" label="JavaScript">-Create a new file at `/app/middleware.js` and populate with the following:-```jsx title="middleware.js"import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs'import { NextResponse } from 'next/server'@@ -156,27 +132,22 @@ export async function middleware(req) {return res}--export const config = {- matcher: ['/optional-session', '/required-session', '/realtime'],-}```</TabPanel><TabPanel id="ts" label="TypeScript">-Create a new file at `/app/middleware.ts` 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 { NextRequest, NextResponse } from 'next/server'+import type { Database } from 'db_types'export async function middleware(req: NextRequest) {const res = NextResponse.next()- const supabase = createMiddlewareSupabaseClient({ req, res })+ const supabase = createMiddlewareSupabaseClient<Database>({ req, res })const {data: { session },@@ -184,20 +155,34 @@ export async function middleware(req: NextRequest) {return res}--export const config = {- matcher: ['/optional-session', '/required-session', '/realtime'],-}```+> TypeScript types can be [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/typescript-support) and passed to `createMiddlewareSupabaseClient` to add type support to the Supabase client.+</TabPanel></Tabs>-> Any Server Component route that uses a Supabase client must be added to this middleware's `matcher` array. Without this, the Server Component may try to make a request to Supabase with an expired `access_token`.+We can now use our server-side Supabase client to fetch data in Server Components.++```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 <pre>{JSON.stringify({ data }, null, 2)}</pre>+}+```-## Supabase Listener+### Client-side-We need to set up a listener to fetch fresh data whenever our user logs in or out.+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.<Tabsscrollable@@ -207,83 +192,124 @@ We need to set up a listener to fetch fresh data whenever our user logs in or ou><TabPanel id="js" label="JavaScript">-Create a `/components/supabase-listener.jsx` file and add the following:+Create a new file at `/utils/supabase-browser.js` and populate with the following:-```jsx title="/components/supabase-listener.jsx"+```js title="/utils/supabase-browser.js"+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+export const createClient = () => createBrowserSupabaseClient()+```++</TabPanel>++<TabPanel id="ts" label="TypeScript">++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 '../db_types'++export const createClient = () => createBrowserSupabaseClient<Database>()+```++> 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.++</TabPanel>+</Tabs>++Next, we need to create a single instance of Supabase to use client-side. Let's create a new Provider for Supabase.++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="js"+>+<TabPanel id="js" label="JavaScript">++```jsx title=components/supabase-provider.jsx'use client'-import { useRouter } from 'next/navigation'-import { useEffect } from 'react'-import supabase from '../utils/supabase-browser'+import { createContext, useContext, useState } from 'react'+import { createClient } from '../utils/supabase-browser'-export default function SupabaseListener({ accessToken }) {- const router = useRouter()+const Context = createContext()- useEffect(() => {- supabase.auth.onAuthStateChange((event, session) => {- if (session?.access_token !== accessToken) {- router.refresh()- }- })- }, [accessToken])+export default function SupabaseProvider({ children }) {+ const [supabase] = useState(() => createClient())- return null+ return (+ <Context.Provider value={{ supabase }}>+ <>{children}</>+ </Context.Provider>+ )}++export const useSupabase = () => useContext(Context)```-> `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`.+</TabPanel>-The function we pass to `onAuthStateChange` is automatically called by Supabase whenever a user's session changes. This component takes an `accessToken` prop, which will be the server's state for our user (we'll set this up next). If the `accessToken` from the server and the new `access_token` do not match then the client and server are out of sync, therefore, we want to reload the active route.+<TabPanel id="ts" label="TypeScript">-Lastly, fetch the server-side session in the `RootLayout` and pass it to our new `<SupabaseListener />` component.+```tsx title=components/supabase-provider.tsx+'use client'-```jsx title="/app/layout.jsx"-import SupabaseListener from '../components/supabase-listener'-import createClient from '../utils/supabase-server'+import { createContext, useContext, useState } from 'react'+import { createClient } from '../utils/supabase-browser'-export default async function RootLayout({ children }) {- const supabase = createClient()+import type { SupabaseClient } from '@supabase/auth-helpers-nextjs'+import type { Database } from '../db_types'- const {- data: { session },- } = await supabase.auth.getSession()+type SupabaseContext = {+ supabase: SupabaseClient<Database>+}++const Context = createContext<SupabaseContext>()++export default function SupabaseProvider({ children }: { children: React.ReactNode }) {+ const [supabase] = useState(() => createClient())return (- // html and head section omitted- <body>- <SupabaseListener accessToken={session?.access_token} />- {children}- </body>+ <Context.Provider value={{ supabase }}>+ <>{children}</>+ </Context.Provider>)}++export const useSupabase = () => useContext(Context)```-We don't want Next.js to cache this `session` value, so we need to export a `revalidate` value of `0` in the layout file.+> 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.-```jsx-export const revalidate = 0-```+</TabPanel>+</Tabs>-We also want to tell Next.js to explicitly exclude this component's code from the client bundle by installing the `server-only` package:+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.```bashnpm install server-only```-And importing it at the top of our component.+This will ensure that any component that imports this package will be a Server Component, and excluded from the browser bundle.-```jsx-import 'server-only'-```+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 `<SupabaseListener />` component (we will create this next).-The entire Layout component should look something like this:+<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="js"+>+<TabPanel id="js" label="JavaScript">-```jsx title="/app/layout.jsx"+```jsx title=app/layout.jsximport 'server-only'import SupabaseListener from '../components/supabase-listener'+import SupabaseProvider from '../components/supabase-provider'import './globals.css'-import createClient from '../utils/supabase-server'+import { createClient } from '../utils/supabase-server'// do not cache this layoutexport const revalidate = 0@@ -298,13 +324,15 @@ export default async function RootLayout({ children }) {return (<html lang="en">{/*- <head /> will contain the components returned by the nearest parent- head.jsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head- */}+ <head /> 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+ */}<head /><body>- <SupabaseListener accessToken={session?.access_token} />- {children}+ <SupabaseProvider>+ <SupabaseListener serverAccessToken={session?.access_token} />+ {children}+ </SupabaseProvider></body></html>)@@ -315,85 +343,13 @@ export default async function RootLayout({ children }) {<TabPanel id="ts" label="TypeScript">-Create a `/components/supabase-listener.tsx` file and add the following:--```tsx title="/components/supabase-listener.tsx"-'use client'--import { useRouter } from 'next/navigation'-import { useEffect } from 'react'-import supabase from '../utils/supabase-browser'--export default function SupabaseListener({ accessToken }: { accessToken?: string }) {- const router = useRouter()-- useEffect(() => {- supabase.auth.onAuthStateChange((event, session) => {- if (session?.access_token !== accessToken) {- router.refresh()- }- })- }, [accessToken])-- 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 `accessToken` prop, which will be the server's state for our user (we'll set this up next). If the `accessToken` from the server and the new `access_token` do not match then the client and server are out of sync, therefore, we want to reload the active route.--Lastly, fetch the server-side session in the `RootLayout` and pass it to our new `<SupabaseListener />` component.--```tsx title="/app/layout.tsx"-import SupabaseListener from '../components/supabase-listener'-import createClient from '../utils/supabase-server'--export default async function RootLayout({ children }: { children: React.ReactNode }) {- const supabase = createClient()-- const {- data: { session },- } = await supabase.auth.getSession()-- return (- // html and head section omitted- <body>- <SupabaseListener accessToken={session?.access_token} />- {children}- </body>- )-}-```--> Again, TypeScript types can be [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/typescript-support) and passed to `createServerComponentSupabaseClient` to add type support to the Supabase client.--We don't want Next.js to cache this `session` value, so we need to export a `revalidate` value of `0`.--```tsx-export const revalidate = 0-```--We also want to tell Next.js to explicitly exclude this component's code from the client bundle by installing the `server-only` package:--```bash-npm install server-only-```--And importing it at the top of our component.--```tsx-import 'server-only'-```--The entire Layout component should look something like this:--```tsx title="/app/layout.tsx"+```tsx title=app/layout.tsximport 'server-only'import SupabaseListener from '../components/supabase-listener'+import SupabaseProvider from '../components/supabase-provider'import './globals.css'-import createClient from '../utils/supabase-server'+import { createClient } from '../utils/supabase-server'// do not cache this layoutexport const revalidate = 0@@ -408,13 +364,15 @@ export default async function RootLayout({ children }: { children: React.ReactNoreturn (<html lang="en">{/*- <head /> 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- */}+ <head /> 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+ */}<head /><body>- <SupabaseListener accessToken={session?.access_token} />- {children}+ <SupabaseProvider>+ <SupabaseListener serverAccessToken={session?.access_token} />+ {children}+ </SupabaseProvider></body></html>)@@ -424,11 +382,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo</TabPanel></Tabs>-Supabase can now be used in any Client or Server component.--## Server Components--Next.js recommends fetching data in Server Components whenever possible.+And now create our Supabase listener component that uses the singleton Supabase instance to listen for auth changes.<Tabsscrollable@@ -438,19 +392,32 @@ Next.js recommends fetching data in Server Components whenever possible.><TabPanel id="js" label="JavaScript">-```jsx-import 'server-only'+```jsx title="/components/supabase-listener.jsx"+'use client'++import { useRouter } from 'next/navigation'+import { useEffect } from 'react'+import { useSupabase } from './supabase-provider'-import createClient from '../../utils/supabase-server'+export default function SupabaseListener({ serverAccessToken }) {+ const { supabase } = useSupabase()+ const router = useRouter()-// do not cache this page-export const revalidate = 0+ useEffect(() => {+ const {+ data: { subscription },+ } = supabase.auth.onAuthStateChange((event, session) => {+ if (session?.access_token !== serverAccessToken) {+ router.refresh()+ }+ })-export default async function ServerComponent() {- const supabase = createClient()- const { data } = await supabase.from('posts').select('*')+ return () => {+ subscription.unsubscribe()+ }+ }, [serverAccessToken, router, supabase])- return <pre>{JSON.stringify({ data }, null, 2)}</pre>+ return null}```@@ -458,32 +425,45 @@ export default async function ServerComponent() {<TabPanel id="ts" label="TypeScript">-```tsx-import 'server-only'+```tsx title="/components/supabase-listener.tsx"+'use client'-import createClient from '../../utils/supabase-server'+import { useRouter } from 'next/navigation'+import { useEffect } from 'react'+import { useSupabase } from './supabase-provider'-// do not cache this page-export const revalidate = 0+export default function SupabaseListener({ serverAccessToken }: { serverAccessToken?: string }) {+ const { supabase } = useSupabase()+ const router = useRouter()-export default async function ServerComponent() {- const supabase = createClient()- const { data } = await supabase.from('posts').select('*')+ useEffect(() => {+ const {+ data: { subscription },+ } = supabase.auth.onAuthStateChange((event, session) => {+ if (session?.access_token !== serverAccessToken) {+ router.refresh()+ }+ })- return <pre>{JSON.stringify({ data }, null, 2)}</pre>+ return () => {+ subscription.unsubscribe()+ }+ }, [serverAccessToken, router, supabase])++ return null}```</TabPanel></Tabs>-## Client Components+> `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`.-While Next.js recommend doing all data fetching in Server Components, we still need Supabase client-side for things like authentication and subscribing to realtime updates.+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.-### Authentication+Now we can use our `useSupabase` hook throughout our client-side components.-We can call any of [Supabase's authentication methods](https://supabase.com/docs/reference/javascript/v1/auth-signin) - such as `supabase.auth.signInWithOAuth` - from a client component.+### Authentication<Tabsscrollable@@ -496,30 +476,33 @@ We can call any of [Supabase's authentication methods](https://supabase.com/docs```jsx title="/components/login.jsx"'use client'-import supabase from '../utils/supabase-browser'+import { useSupabase } from './supabase-provider'+// Supabase auth needs to be triggered client-sideexport default function Login() {- const handleLogin = async () => {- const { error } = await supabase.auth.signInWithOAuth({- provider: 'github',+ const { supabase, session } = useSupabase()++ const handleEmailLogin = async () => {+ await supabase.auth.signInWithPassword({+ email: '[email protected]',+ password: 'password',})+ }- if (error) {- console.log({ error })- }+ const handleGitHubLogin = async () => {+ await supabase.auth.signInWithOAuth({+ provider: 'github',+ })}const handleLogout = async () => {- const { error } = await supabase.auth.signOut()-- if (error) {- console.log({ error })- }+ await supabase.auth.signOut()}return (<>- <button onClick={handleLogin}>Login</button>+ <button onClick={handleEmailLogin}>Email Login</button>+ <button onClick={handleGitHubLogin}>GitHub Login</button><button onClick={handleLogout}>Logout</button></>)@@ -533,30 +516,33 @@ export default function Login() {```tsx title="/components/login.tsx"'use client'-import supabase from '../utils/supabase-browser'+import { useSupabase } from './supabase-provider'+// Supabase auth needs to be triggered client-sideexport default function Login() {- const handleLogin = async () => {- const { error } = await supabase.auth.signInWithOAuth({- provider: 'github',+ const { supabase, session } = useSupabase()++ const handleEmailLogin = async () => {+ await supabase.auth.signInWithPassword({+ email: '[email protected]',+ password: 'password',})+ }- if (error) {- console.log({ error })- }+ const handleGitHubLogin = async () => {+ await supabase.auth.signInWithOAuth({+ provider: 'github',+ })}const handleLogout = async () => {- const { error } = await supabase.auth.signOut()-- if (error) {- console.log({ error })- }+ await supabase.auth.signOut()}return (<>- <button onClick={handleLogin}>Login</button>+ <button onClick={handleEmailLogin}>Email Login</button>+ <button onClick={handleGitHubLogin}>GitHub Login</button><button onClick={handleLogout}>Logout</button></>)@@ -586,10 +572,11 @@ Create a new file at `/app/realtime/posts.jsx` and populate with the following:'use client'import { useEffect, useState } from 'react'-import supabase from '../../utils/supabase-browser'+import { useSupabase } from '../../components/supabase-provider'export default function Posts({ serverPosts }) {const [posts, setPosts] = useState(serverPosts)+ const { supabase } = useSupabase()useEffect(() => {setPosts(serverPosts)@@ -606,14 +593,12 @@ export default function Posts({ serverPosts }) {return () => {supabase.removeChannel(channel)}- }, [serverPosts])+ }, [supabase, setPosts, posts])return <pre>{JSON.stringify(posts, null, 2)}</pre>}```-> The first `useEffect` is required to overwrite posts if the `serverPosts` prop changes.-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:@@ -621,7 +606,7 @@ 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 { createClient } from '../../utils/supabase-server'import Posts from './posts'// do not cache this page@@ -645,13 +630,15 @@ Create a new file at `/app/realtime/posts.tsx` and populate with the following:'use client'import { useEffect, useState } from 'react'-import { Database } from '../lib/database.types'-import supabase from '../../utils/supabase-browser'+import { useSupabase } from '../../components/supabase-provider'++import type { Database } from '../../db_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)@@ -668,13 +655,13 @@ export default function Posts({ serverPosts }: { serverPosts: Post[] }) {return () => {supabase.removeChannel(channel)}- }, [serverPosts])+ }, [supabase, setPosts, posts])return <pre>{JSON.stringify(posts, null, 2)}</pre>}```-> The first `useEffect` is required to overwrite posts if the `serverPosts` prop changes.+> 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.@@ -683,7 +670,7 @@ 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 { createClient } from '../../utils/supabase-server'import Posts from './posts'// do not cache this page