Skip to content

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

Update user management nextjs guide

Andrew Smith09cf361c82a2
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 5757c41d7ca..c5c5108460f 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
@@ -183,158 +183,19 @@ export const config = {
</TabPanel>
</Tabs>
-### Supabase provider
-
-Create a Supabase context provider that simplifies access to the Supabase client within client-side code.
-
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="js"
->
-<TabPanel id="js" label="JavaScript">
-
-Create a `SupabaseProvider` component in `app/supabase-provider.jsx` and populate it with the following content:
-
-```jsx title=app/supabase-provider.jsx
-// app/supabase-provider.jsx
-'use client'
-
-import { createContext, useContext, useEffect, useState } from 'react'
-import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-import { useRouter } from 'next/navigation'
-
-const Context = createContext(undefined)
-
-export default function SupabaseProvider({ children, session }) {
- const [supabase] = useState(() => createClientComponentClient())
- const router = useRouter()
-
- useEffect(() => {
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((_, _session) => {
- if (_session?.access_token !== session?.access_token) {
- router.refresh()
- }
- })
-
- return () => {
- subscription.unsubscribe()
- }
- }, [router, supabase, session])
-
- return (
- <Context.Provider value={{ supabase, session }}>
- <>{children}</>
- </Context.Provider>
- )
-}
-
-export const useSupabase = () => {
- let context = useContext(Context)
-
- if (context === undefined) {
- throw new Error('useSupabase must be used inside SupabaseProvider')
- }
-
- return context.supabase
-}
-
-export const useSession = () => {
- let context = useContext(Context)
-
- if (context === undefined) {
- throw new Error('useSession must be used inside SupabaseProvider')
- }
-
- return context.session
-}
-```
-
-</TabPanel>
-<TabPanel id="ts" label="TypeScript">
-
-Create a `SupabaseProvider` component in `app/supabase-provider.tsx` and populate it with the following content:
-
-```tsx title=app/supabase-provider.tsx
-// app/supabase-provider.tsx
-'use client'
-
-import { createContext, useContext, useEffect, useState } from 'react'
-import { Session, SupabaseClient, createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-import { useRouter } from 'next/navigation'
-import { Database } from './database.types'
-
-type MaybeSession = Session | null
-
-type SupabaseContext = {
- supabase: SupabaseClient
- session: MaybeSession
-}
-
-const Context = createContext<SupabaseContext | undefined>(undefined)
-
-export default function SupabaseProvider({
- children,
- session,
-}: {
- children: React.ReactNode
- session: MaybeSession
-}) {
- const [supabase] = useState(() => createClientComponentClient<Database>())
- const router = useRouter()
-
- useEffect(() => {
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((_, _session) => {
- if (_session?.access_token !== session?.access_token) {
- router.refresh()
- }
- })
-
- return () => {
- subscription.unsubscribe()
- }
- }, [router, supabase, session])
-
- return (
- <Context.Provider value={{ supabase, session }}>
- <>{children}</>
- </Context.Provider>
- )
-}
-
-export const useSupabase = <
- Database = any,
- SchemaName extends string & keyof Database = 'public' extends keyof Database
- ? 'public'
- : string & keyof Database
->() => {
- let context = useContext(Context)
-
- if (context === undefined) {
- throw new Error('useSupabase must be used inside SupabaseProvider')
- }
+### Set up a Login component
- return context.supabase as SupabaseClient<Database, SchemaName>
-}
+#### Supabase Auth UI
-export const useSession = () => {
- let context = useContext(Context)
+We can use the [Supabase Auth UI](/docs/guides/auth/auth-helpers/auth-ui) a pre-built React component for authenticating users via OAuth, email, and magic links.
- if (context === undefined) {
- throw new Error('useSession must be used inside SupabaseProvider')
- }
+Install the Supabase Auth UI for React
- return context.session
-}
+```bash
+npm install @supabase/auth-ui-react @supabase/auth-ui-shared
```
-</TabPanel>
-</Tabs>
+Create an `AuthForm` client side component with the `Auth` component rendered within it:
<Tabs
scrollable
@@ -344,39 +205,26 @@ export const useSession = () => {
>
<TabPanel id="js" label="JavaScript">
-Wrap your `app/layout.js` component with the `SupabaseProvider` component:
-
-```jsx title=app/layout.jsx
-// app/layout.jsx
-import './globals.css'
-import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
-import SupabaseProvider from './supabase-provider'
-import { cookies } from 'next/headers'
-
-export const metadata = {
- title: 'User Management',
- description: 'Generated by create next app',
-}
-
-export default async function RootLayout({ children }) {
- const supabase = createServerComponentClient({
- cookies,
- })
+```jsx title=app/auth-form.jsx
+// app/auth-form.jsx
+'use client'
+import { Auth } from '@supabase/auth-ui-react'
+import { ThemeSupa } from '@supabase/auth-ui-shared'
+import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
- const {
- data: { session },
- } = await supabase.auth.getSession()
+export default function AuthForm() {
+ const supabase = createClientComponentClient()
return (
- <html lang="en">
- <body>
- <SupabaseProvider session={session}>
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {children}
- </div>
- </SupabaseProvider>
- </body>
- </html>
+ <Auth
+ supabaseClient={supabase}
+ view="magic_link"
+ appearance={{ theme: ThemeSupa }}
+ theme="dark"
+ showLinks={false}
+ providers={[]}
+ redirectTo="http://localhost:3000/auth/callback"
+ />
)
}
```
@@ -384,71 +232,16 @@ export default async function RootLayout({ children }) {
</TabPanel>
<TabPanel id="ts" label="TypeScript">
-Wrap your `app/layout.tsx` component with the `SupabaseProvider` component:
-
-```jsx title=app/layout.tsx
-// app/layout.tsx
-import './globals.css'
-import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
-import SupabaseProvider from './supabase-provider'
-import { cookies } from 'next/headers'
-
-export const metadata = {
- title: 'User Management',
- description: 'Generated by create next app',
-}
-
-export default async function RootLayout({ children }: { children: React.ReactNode }) {
- const supabase = createServerComponentClient({
- cookies,
- })
-
- const {
- data: { session },
- } = await supabase.auth.getSession()
-
- return (
- <html lang="en">
- <body>
- <SupabaseProvider session={session}>
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {children}
- </div>
- </SupabaseProvider>
- </body>
- </html>
- )
-}
-```
-
-See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.
-
-</TabPanel>
-</Tabs>
-
-### Set up a Login component
-
-#### Supabase Auth UI
-
-We can use the [Supabase Auth UI](/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 @supabase/auth-ui-shared
-```
-
-Create an `AuthForm` client side component with the `Auth` component rendered within it:
-
-```jsx title=app/authform.jsx
-// app/authform.[j|t]sx
+```jsx title=app/auth-form.tsx
+// app/auth-form.tsx
'use client'
import { Auth } from '@supabase/auth-ui-react'
import { ThemeSupa } from '@supabase/auth-ui-shared'
-import { useSupabase } from './supabase-provider'
+import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+import { Database } from './database.types'
export default function AuthForm() {
- const supabase = useSupabase()
+ const supabase = createClientComponentClient<Database>()
return (
<Auth
@@ -464,13 +257,16 @@ export default function AuthForm() {
}
```
+</TabPanel>
+</Tabs>
+
Add the `AuthForm` component to your home page
```jsx title=app/page.js
// app/page.[j|t]sx
-import AuthForm from './authform'
+import AuthForm from './auth-form'
-export default async function Home() {
+export default function Home() {
return (
<div className="row">
<div className="col-6">
@@ -488,6 +284,8 @@ export default async function Home() {
}
```
+### 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:
@@ -628,15 +426,14 @@ Let's create a new component for that called `AccountForm` within the `app/accou
>
<TabPanel id="js" label="JavaScript">
-```jsx title=app/account/accountform.jsx
-// app/account/accountform.jsx
+```jsx title=app/account/account-form.jsx
+// app/account/account-form.jsx
'use client'
-import { useSession, useSupabase } from '../supabase-provider'
import { useCallback, useEffect, useState } from 'react'
+import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-export default function AccountForm() {
- const supabase = useSupabase()
- const session = useSession()
+export default function AccountForm({ session }) {
+ const supabase = createClientComponentClient()
const [loading, setLoading] = useState(true)
const [fullname, setFullname] = useState(null)
const [username, setUsername] = useState(null)
@@ -759,16 +556,15 @@ export default function AccountForm() {
</TabPanel>
<TabPanel id="ts" label="TypeScript">
-```tsx title=app/account/accountform.tsx
-// app/account/accountform.tsx
+```tsx title=app/account/account-form.tsx
+// app/account/account-form.tsx
'use client'
-import { useSession, useSupabase } from '../supabase-provider'
import { useCallback, useEffect, useState } from 'react'
import { Database } from '../database.types'
+import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-export default function AccountForm() {
- const supabase = useSupabase<Database>()
- const session = useSession()
+export default function AccountForm({ session }: { session: Session | null }) {
+ const supabase = createClientComponentClient<Database>()
const [loading, setLoading] = useState(true)
const [fullname, setFullname] = useState<string | null>(null)
const [username, setUsername] = useState<string | null>(null)
@@ -908,10 +704,18 @@ Create a account page for the `AccountForm` component we just created
```jsx title=app/account/page.jsx
// app/account/page.jsx
-import AccountForm from './accountform'
+import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
+import { cookies } from 'next/headers'
+import AccountForm from './account-form'
-export default function Account() {
- return <AccountForm />
+export default async function Account() {
+ const supabase = createServerComponentClient({ cookies })
+
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
+
+ return <AccountForm session={session} />
}
```
@@ -920,10 +724,19 @@ export default function Account() {
```tsx title=app/account/page.tsx
// app/account/page.tsx
-import AccountForm from './accountform'
+import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
+import { cookies } from 'next/headers'
+import { Database } from '../database.types'
+import AccountForm from './account-form'
+
+export default async function Account() {
+ const supabase = createServerComponentClient<Database>({ cookies })
+
+ const {
+ data: { session },
+ } = await supabase.auth.getSession()
-export default function Account() {
- return <AccountForm />
+ return <AccountForm session={session} />
}
```
@@ -960,23 +773,17 @@ Let's create an avatar widget for the user so that they can upload a profile pho
```jsx title=app/account/avatar.jsx
'use client'
import React, { useEffect, useState } from 'react'
-import { Database } from '../database.types'
-import { useSupabase } from '../supabase-provider'
+import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+import Image from 'next/image'
export default function Avatar({ uid, url, size, onUpload }) {
- const supabase = useSupabase()
+ const supabase = createClientComponentClient()
const [avatarUrl, setAvatarUrl] = useState(null)
const [uploading, setUploading] = useState(false)
- const [blobUrlCache, setBlobUrlCache] = useState({})
useEffect(() => {
async function downloadImage(path) {
try {
- if (blobUrlCache[path]) {
- setAvatarUrl(blobUrlCache[path])
- return
- }
-
const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
throw error
@@ -984,14 +791,13 @@ export default function Avatar({ uid, url, size, onUpload }) {
const url = URL.createObjectURL(data)
setAvatarUrl(url)
- setBlobUrlCache((prevCache) => ({ ...prevCache, [path]: url }))
} catch (error) {
console.log('Error downloading image: ', error)
}
}
if (url) downloadImage(url)
- }, [url, supabase.storage, blobUrlCache])
+ }, [url, supabase])
const uploadAvatar = async (event) => {
try {
@@ -1003,12 +809,9 @@ export default function Avatar({ uid, url, size, onUpload }) {
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
- const fileName = `${uid}.${fileExt}`
- const filePath = `${fileName}`
+ const filePath = `${uid}-${Math.random()}.${fileExt}`
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file, { upsert: true })
+ let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
if (uploadError) {
throw uploadError
@@ -1017,7 +820,6 @@ export default function Avatar({ uid, url, size, onUpload }) {
onUpload(filePath)
} catch (error) {
alert('Error uploading avatar!')
- console.log(error)
} finally {
setUploading(false)
}
@@ -1026,7 +828,9 @@ export default function Avatar({ uid, url, size, onUpload }) {
return (
<div>
{avatarUrl ? (
- <img
+ <Image
+ width={size}
+ height={size}
src={avatarUrl}
alt="Avatar"
className="avatar image"
@@ -1063,7 +867,8 @@ export default function Avatar({ uid, url, size, onUpload }) {
'use client'
import React, { useEffect, useState } from 'react'
import { Database } from '../database.types'
-import { useSupabase } from '../supabase-provider'
+import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+import Image from 'next/image'
type Profiles = Database['public']['Tables']['profiles']['Row']
export default function Avatar({
@@ -1077,19 +882,13 @@ export default function Avatar({
size: number
onUpload: (url: string) => void
}) {
- const supabase = useSupabase()
- const [avatarUrl, setAvatarUrl] = useState<Profiles['avatar_url']>(null)
+ const supabase = createClientComponentClient<Database>()
+ const [avatarUrl, setAvatarUrl] = useState<Profiles['avatar_url']>(url)
const [uploading, setUploading] = useState(false)
- const [blobUrlCache, setBlobUrlCache] = useState<Record<string, string>>({})
useEffect(() => {
async function downloadImage(path: string) {
try {
- if (blobUrlCache[path]) {
- setAvatarUrl(blobUrlCache[path])
- return
- }
-
const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
throw error
@@ -1097,14 +896,13 @@ export default function Avatar({
const url = URL.createObjectURL(data)
setAvatarUrl(url)
- setBlobUrlCache((prevCache) => ({ ...prevCache, [path]: url }))
} catch (error) {
console.log('Error downloading image: ', error)
}
}
if (url) downloadImage(url)
- }, [url, supabase.storage, blobUrlCache])
+ }, [url, supabase])
const uploadAvatar: React.ChangeEventHandler<HTMLInputElement> = async (event) => {
try {
@@ -1116,12 +914,9 @@ export default function Avatar({
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
- const fileName = `${uid}.${fileExt}`
- const filePath = `${fileName}`
+ const filePath = `${uid}-${Math.random()}.${fileExt}`
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file, { upsert: true })
+ let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
if (uploadError) {
throw uploadError
@@ -1130,7 +925,6 @@ export default function Avatar({
onUpload(filePath)
} catch (error) {
alert('Error uploading avatar!')
- console.log(error)
} finally {
setUploading(false)
}
@@ -1139,7 +933,9 @@ export default function Avatar({
return (
<div>
{avatarUrl ? (
- <img
+ <Image
+ width={size}
+ height={size}
src={avatarUrl}
alt="Avatar"
className="avatar image"
@@ -1176,8 +972,8 @@ export default function Avatar({
And then we can add the widget to the `AccountForm` component:
-```jsx title=app/account/accountform.js
-// app/account/accountform.[j|t]sx
+```jsx title=app/account/account-form.js
+// app/account/account-form.[j|t]sx
// Import the new component
import Avatar from './avatar'
@@ -1192,7 +988,7 @@ return (
size={150}
onUpload={(url) => {
setAvatarUrl(url)
- updateProfile({ username, website, avatar_url: url })
+ updateProfile({ fullname, username, website, avatar_url: url })
}}
/>
{/* ... */}