Skip to content

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

feat: updated nextjs quickstart.

thorwebdevb5223131e00b
diff --git a/apps/reference/docs/guides/auth/auth-helpers/nextjs.mdx b/apps/reference/docs/guides/auth/auth-helpers/nextjs.mdx
index f17a9fe926e..6bf0f2b83f2 100644
--- a/apps/reference/docs/guides/auth/auth-helpers/nextjs.mdx
+++ b/apps/reference/docs/guides/auth/auth-helpers/nextjs.mdx
@@ -31,7 +31,8 @@ This library supports the following tooling versions:
- Node.js: `^10.13.0 || >=12.0.0`
- Next.js: `>=10`
-Optionally, install **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
+Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
+
```sh
npm install @supabase/auth-helpers-react
```
@@ -48,7 +49,7 @@ This library supports the following tooling versions:
- Node.js: `^10.13.0 || >=12.0.0`
- Next.js: `>=10`
-Optionally, install **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
+Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
```sh
yarn add @supabase/auth-helpers-react
@@ -61,82 +62,135 @@ yarn add @supabase/auth-helpers-react
Retrieve your project URL and anon key in your project's [API settings](https://app.supabase.com/project/_/settings/api) in the Dashboard to set up the following environment variables. For local development you can set them in a `.env.local` file. See an [example](https://github.com/supabase/auth-helpers/blob/main/examples/nextjs/.env.local.example).
-```bash
-NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
-NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
+```bash title=".env.local"
+NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
+NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
## Basic Setup
+<Tabs
+ defaultValue="js"
+ values={[
+ {label: 'JavaScript', value: 'js'},
+ {label: 'TypeScript', value: 'ts'},
+ ]}>
+<TabItem value="js">
+
Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
```jsx title="pages/_app.js"
-import React from 'react'
-import { useRouter } from 'next/router'
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { SessionContextProvider } from '@supabase/auth-helpers-react'
-function MyApp({ Component, pageProps }: AppProps) {
+function MyApp({ Component, pageProps }) {
const router = useRouter()
+ // Create a new supabase browser client on every first render.
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
<SessionContextProvider
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
- >
- <button
- onClick={async () => {
- await supabaseClient.auth.signOut()
- router.push('/')
- }}
- >
- Logout
- </button>
+ <Component {...pageProps} />
+ </SessionContextProvider>
+ )
+}
+```
+
+</TabItem>
+<TabItem value="ts">
+
+Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
+```jsx title="pages/_app.tsx"
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+// highlight-next-line
+import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
+
+function MyApp({
+ Component,
+ pageProps,
+}: AppProps<{
+ // highlight-next-line
+ initialSession: Session,
+}>) {
+ // Create a new supabase browser client on every first render.
+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())
+
+ return (
+ <SessionContextProvider
+ supabaseClient={supabaseClient}
+ initialSession={pageProps.initialSession}
+ >
<Component {...pageProps} />
</SessionContextProvider>
)
}
```
+</TabItem>
+</Tabs>
+
You can now determine if a user is authenticated by checking that the `user` object returned by the `useUser()` hook is defined.
## Usage with TypeScript
You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:
-```js
+### Browser client
+
+```ts
// Creating a new supabase client object:
-import { Database } from '../db_types';
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { Database } from '../database.types'
-const [supabaseClient] = useState(() =>
- createBrowserSupabaseClient<Database>()
- );
+const supabaseClient = createBrowserSupabaseClient<Database>()
```
-```js
+```ts
// Retrieving a supabase client object from the SessionContext:
-import { useSupabaseClient } from '@supabase/auth-helpers-react';
-import { Database } from '../db_types';
+import { useSupabaseClient } from '@supabase/auth-helpers-react'
+import { Database } from '../database.types'
+
+const supabaseClient = useSupabaseClient<Database>()
+```
+
+### Server client
-const supabaseClient = useSupabaseClient<Database>();
+```ts
+// Creating a new supabase server client object (e.g. in API route):
+import type { NextApiRequest, NextApiResponse } from 'next'
+import type { Database } from 'types_db'
+
+export default async (req: NextApiRequest, res: NextApiResponse) => {
+ const supabaseServerClient = createServerSupabaseClient<Database>({
+ req,
+ res,
+ })
+ const {
+ data: { user },
+ } = await supabaseServerClient.auth.getUser()
+
+ res.status(200).json({ name: user?.name ?? '' })
+}
```
## Client-side data fetching with RLS
-For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSessionContext` hook and only run your query once the user is defined client-side in the `useUser()` hook:
+For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSupabaseClient` hook and only run your query once the user is defined client-side in the `useUser()` hook:
```js
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
-import { useUser, useSessionContext } from '@supabase/auth-helpers-react'
+import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
import { useEffect, useState } from 'react'
const LoginPage = () => {
- const { isLoading, session, error, supabaseClient } = useSessionContext()
+ const supabaseClient = useSupabaseClient()
const user = useUser()
const [data, setData] = useState()
+ // highlight-start
useEffect(() => {
async function loadData() {
const { data } = await supabaseClient.from('test').select('*')
@@ -145,19 +199,17 @@ const LoginPage = () => {
// Only run query once user is logged in.
if (user) loadData()
}, [user])
+ // highlight-end
if (!user)
return (
- <>
- {error && <p>{error.message}</p>}
- <Auth
- redirectTo="http://localhost:3000/"
- appearance={{ theme: ThemeSupa }}
- supabaseClient={supabaseClient}
- providers={['google', 'github']}
- socialLayout="horizontal"
- />
- </>
+ <Auth
+ redirectTo="http://localhost:3000/"
+ appearance={{ theme: ThemeSupa }}
+ supabaseClient={supabaseClient}
+ providers={['google', 'github']}
+ socialLayout="horizontal"
+ />
)
return (
@@ -191,7 +243,7 @@ export const getServerSideProps = withPageAuth({ redirectTo: '/login' })
If there is no authenticated user, they will be redirect to your home page, unless you specify the `redirectTo` option.
You can pass in your own `getServerSideProps` method, the props returned from this will be merged with the
-user props. You can also access the user session data by calling `getUser` inside of this method, eg:
+user props. You can also access the user session data by calling `supabase.auth.getUser()` inside of this method, eg:
```js title="pages/protected-page.js"
import { withPageAuth } from '@supabase/auth-helpers-nextjs'
@@ -250,39 +302,57 @@ export const getServerSideProps = withPageAuth({
When using third-party auth providers, sessions are initiated with an additional `provider_token` field which is persisted as an HTTPOnly cookie upon logging in to enabled usage on the server side. The `provider_token` can be used to make API requests to the OAuth provider's API endpoints on behalf of the logged-in user. In the following example, we fetch the user's full profile from the third-party API during SSR using their id and auth token:
```js
-import { User, withPageAuth, getUser } from '@supabase/auth-helpers-nextjs'
-
-interface Profile {
- /* ... */
-}
+import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'
export default function ProtectedPage({
user,
- data,
+ allRepos,
}: {
user: User,
- profile: Profile,
+ allRepos: any,
}) {
- return <div>Protected content</div>
+ return (
+ <>
+ <div>Protected content for {user.email}</div>
+ <p>Data fetched with provider token:</p>
+ <pre>{JSON.stringify(allRepos, null, 2)}</pre>
+ <p>user:</p>
+ <pre>{JSON.stringify(user, null, 2)}</pre>
+ </>
+ )
}
export const getServerSideProps = withPageAuth({
redirectTo: '/',
- async getServerSideProps(ctx) {
- // Retrieve provider_token from cookies
- const provider_token = ctx.req.cookies['sb-provider-token']
- // Get logged in user's third-party id from metadata
- const { user } = await getUser(ctx)
- const userId = user?.user_metadata.provider_id
- const profile: Profile = await (
- await fetch(`https://api.example.com/users/${userId}`, {
- method: 'GET',
- headers: {
- Authorization: `Bearer ${provider_token}`,
- },
- })
+ async getServerSideProps(ctx, supabase) {
+ const {
+ data: { session },
+ error,
+ } = await supabase.auth.getSession()
+ if (error) {
+ throw error
+ }
+ if (!session) {
+ return { props: {} }
+ }
+
+ // Retrieve provider_token & logged in user's third-party id from metadata
+ const { provider_token, user } = session
+ const userId = user.user_metadata.user_name
+
+ const allRepos = await (
+ await fetch(
+ `https://api.github.com/search/repositories?q=user:${userId}`,
+ {
+ method: 'GET',
+ headers: {
+ Authorization: `token ${provider_token}`,
+ },
+ }
+ )
).json()
- return { props: { profile } }
+
+ return { props: { allRepos, user } }
},
})
```
@@ -355,6 +425,7 @@ export const config = {
</button>
```
- The `supabaseClient` and `supabaseServerClient` have been removed in favor of the `createBrowserSupabaseClient` and `createServerSupabaseClient` methods. This allows you to provide the CLI-generated types to the client:
+
```js
// client-side
import type { Database } from 'types_db';
@@ -373,12 +444,14 @@ export const config = {
res.status(200).json({ name: user?.name ?? '' })
}
```
+
- The `UserProvider` has been replaced by the `SessionContextProvider`. Make sure to wrap your `pages/_app.js` componenent with the `SessionContextProvider`. Then, throughout your application you can use the `useSessionContext` hook to get the `session` and the `useSupabaseClient` hook to get an authenticated `supabaseClient`.
- The `useUser` hook now returns the `user` object or `null`.
- Usage with TypeScript: You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:
+
```js
// Creating a new supabase client object:
- import { Database } from '../db_types';
+ import { Database } from '../database.types';
const [supabaseClient] = useState(() =>
createBrowserSupabaseClient<Database>()
@@ -388,7 +461,7 @@ export const config = {
```js
// Retrieving a supabase client object from the SessionContext:
import { useSupabaseClient } from '@supabase/auth-helpers-react';
- import { Database } from '../db_types';
+ import { Database } from '../database.types';
const supabaseClient = useSupabaseClient<Database>();
```
diff --git a/apps/reference/docs/guides/with-nextjs.mdx b/apps/reference/docs/guides/with-nextjs.mdx
index ebcc253325c..b6a25d921f1 100644
--- a/apps/reference/docs/guides/with-nextjs.mdx
+++ b/apps/reference/docs/guides/with-nextjs.mdx
@@ -85,51 +85,59 @@ or you can just copy/paste the SQL from below and run it yourself.
<TabItem value="sql">
```sql
--- Create a table for public "profiles"
+-- Create a table for public profiles
create table profiles (
- id uuid references auth.users not null,
+ id uuid references auth.users not null primary key,
updated_at timestamp with time zone,
username text unique,
+ full_name text,
avatar_url text,
website text,
- primary key (id),
- unique(username),
constraint username_length check (char_length(username) >= 3)
);
-
-alter table profiles enable row level security;
-
-create policy "Public profiles are viewable by everyone."
- on profiles for select
- using ( true );
-
-create policy "Users can insert their own profile."
- on profiles for insert
- with check ( auth.uid() = id );
-
-create policy "Users can update own profile."
- on profiles for update
- using ( auth.uid() = id );
-
--- Set up Realtime!
-begin;
- drop publication if exists supabase_realtime;
- create publication supabase_realtime;
-commit;
-alter publication supabase_realtime add table profiles;
+-- Set up Row Level Security (RLS)
+-- See https://supabase.com/docs/guides/auth/row-level-security for more details.
+alter table profiles
+ enable row level security;
+
+create policy "Public profiles are viewable by everyone." on profiles
+ for select using (true);
+
+create policy "Users can insert their own profile." on profiles
+ for insert with check (auth.uid() = id);
+
+create policy "Users can update own profile." on profiles
+ for update using (auth.uid() = id);
+
+-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth.
+-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details.
+create function public.handle_new_user()
+returns trigger as $$
+begin
+ insert into public.profiles (id, full_name, avatar_url)
+ values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');
+ return new;
+end;
+$$ language plpgsql security definer;
+create trigger on_auth_user_created
+ after insert on auth.users
+ for each row execute procedure public.handle_new_user();
-- Set up Storage!
insert into storage.buckets (id, name)
-values ('avatars', 'avatars');
+ values ('avatars', 'avatars');
-create policy "Avatar images are publicly accessible."
- on storage.objects for select
- using ( bucket_id = 'avatars' );
+-- Set up access controls for storage.
+-- See https://supabase.com/docs/guides/storage#policy-examples for more details.
+create policy "Avatar images are publicly accessible." on storage.objects
+ for select using (bucket_id = 'avatars');
-create policy "Anyone can upload an avatar."
- on storage.objects for insert
- with check ( bucket_id = 'avatars' );
+create policy "Anyone can upload an avatar." on storage.objects
+ for insert with check (bucket_id = 'avatars');
+
+create policy "Anyone can update their own avatar." on storage.objects
+ for update using ( auth.uid() = owner ) with check (bucket_id = 'avatars');
```
@@ -163,12 +171,31 @@ Let's start building the Next.js app from scratch.
We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize
an app called `supabase-nextjs`:
+<Tabs
+ defaultValue="js"
+ values={[
+ {label: 'JavaScript', value: 'js'},
+ {label: 'TypeScript', value: 'ts'},
+ ]}>
+<TabItem value="js">
+
```bash
-npx create-next-app supabase-nextjs --use-npm
+npx create-next-app@latest --use-npm supabase-nextjs
cd supabase-nextjs
```
-Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)
+</TabItem>
+<TabItem value="ts">
+
+```bash
+npx create-next-app@latest --ts --use-npm supabase-nextjs
+cd supabase-nextjs
+```
+
+</TabItem>
+</Tabs>
+
+Then install the Supabase client library: [supabase-js](https://github.com/supabase/supabase-js)
```bash
npm install @supabase/supabase-js
@@ -182,93 +209,146 @@ NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
-Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client.
-These variables will be exposed on the browser, and that's completely fine since we have
-[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.
+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
-```js title="utils/supabaseClient.js"
-import { createClient } from '@supabase/supabase-js'
+Next.js is a highly versatile framework offering static site generation, server-side rendering (SSR), middleware edge-functions, and much more.
-const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
-const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
+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.
-export const supabase = createClient(supabaseUrl, supabaseAnonKey)
+Install the auth helpers for React and Next.js
+
+```bash
+npm install @supabase/auth-helpers-react @supabase/auth-helpers-nextjs
```
-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/examples/main/supabase-js-v2/user-management/nextjs-ts-user-management/styles/globals.css).
+<Tabs
+ defaultValue="js"
+ values={[
+ {label: 'JavaScript', value: 'js'},
+ {label: 'TypeScript', value: 'ts'},
+ ]}>
+<TabItem value="js">
-### Set up a Login component
+Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
-Let's set up a React component to manage logins and sign ups.
-We'll use Magic Links, so users can sign in with their email without using passwords.
+```jsx title="pages/_app.js"
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+import { SessionContextProvider } from '@supabase/auth-helpers-react'
-```jsx title="components/Auth.js"
-import { useState } from 'react'
-import { supabase } from '../utils/supabaseClient'
+function MyApp({ Component, pageProps }) {
+ const router = useRouter()
+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())
-export default function Auth() {
- const [loading, setLoading] = useState(false)
- const [email, setEmail] = useState('')
+ return (
+ <SessionContextProvider
+ supabaseClient={supabaseClient}
+ initialSession={pageProps.initialSession}
+ <Component {...pageProps} />
+ </SessionContextProvider>
+ )
+}
+```
- const handleLogin = async (email) => {
- try {
- setLoading(true)
- const { error } = await supabase.auth.signInWithOtp({ email })
- if (error) throw error
- alert('Check your email for the login link!')
- } catch (error) {
- alert(error.error_description || error.message)
- } finally {
- setLoading(false)
- }
- }
+</TabItem>
+<TabItem value="ts">
+
+Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
+
+```jsx title="pages/_app.tsx"
+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
+// highlight-next-line
+import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
+
+function MyApp({
+ Component,
+ pageProps,
+}: AppProps<{
+ // highlight-next-line
+ initialSession: Session,
+}>) {
+ const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
- <div className="row flex-center flex">
- <div className="col-6 form-widget">
- <h1 className="header">Supabase + Next.js</h1>
- <p className="description">
- Sign in via magic link with your email below
- </p>
- <div>
- <input
- className="inputField"
- type="email"
- placeholder="Your email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- />
- </div>
- <div>
- <button
- onClick={(e) => {
- e.preventDefault()
- handleLogin(email)
- }}
- className="button block"
- disabled={loading}
- >
- <span>{loading ? 'Loading' : 'Send magic link'}</span>
- </button>
- </div>
- </div>
+ <SessionContextProvider
+ supabaseClient={supabaseClient}
+ initialSession={pageProps.initialSession}
+ >
+ <Component {...pageProps} />
+ </SessionContextProvider>
+ )
+}
+```
+
+See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.
+
+</TabItem>
+</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 type { NextPage } from 'next'
+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
+import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
+
+const Home: NextPage = () => {
+ 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.
-Let's create a new component for that called `Account.js`.
+<Tabs
+ defaultValue="js"
+ values={[
+ {label: 'JavaScript', value: 'js'},
+ {label: 'TypeScript', value: 'ts'},
+ ]}>
+<TabItem value="js">
-```jsx title="components/Account.js"
+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 { supabase } from '../utils/supabaseClient'
+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)
@@ -278,27 +358,9 @@ export default function Account({ session }) {
getProfile()
}, [session])
- async function getCurrentUser() {
- const {
- data: { session },
- error,
- } = await supabase.auth.getSession()
-
- if (error) {
- throw error
- }
-
- if (!session?.user) {
- throw new Error('User not logged in')
- }
-
- return session.user
- }
-
async function getProfile() {
try {
setLoading(true)
- const user = await getCurrentUser()
let { data, error, status } = await supabase
.from('profiles')
@@ -316,7 +378,8 @@ export default function Account({ session }) {
setAvatarUrl(data.avatar_url)
}
} catch (error) {
- alert(error.message)
+ alert('Error loading user data!')
+ console.log(error)
} finally {
setLoading(false)
}
@@ -325,23 +388,21 @@ export default function Account({ session }) {
async function updateProfile({ username, website, avatar_url }) {
try {
setLoading(true)
- const user = await getCurrentUser()
const updates = {
id: user.id,
username,
website,
avatar_url,
- updated_at: new Date(),
+ updated_at: new Date().toISOString(),
}
let { error } = await supabase.from('profiles').upsert(updates)
-
- if (error) {
- throw error
- }
+ if (error) throw error
+ alert('Profile updated!')
} catch (error) {
- alert(error.message)
+ alert('Error updating the data!')
+ console.log(error)
} finally {
setLoading(false)
}
@@ -354,7 +415,7 @@ export default function Account({ session }) {
<input id="email" type="text" value={session.user.email} disabled />
</div>
<div>
- <label htmlFor="username">Name</label>
+ <label htmlFor="username">Username</label>
<input
id="username"
type="text"
@@ -395,63 +456,176 @@ export default function Account({ session }) {
}
```
-### Launch!
+</TabItem>
+<TabItem value="ts">
-Now that we have all the components in place, let's update `pages/index.js`:
+Let's create a new component for that called `Account.tsx` within a `components` folder.
-```jsx title="pages/index.js"
+```tsx title="components/Account.tsx"
import { useState, useEffect } from 'react'
-import { supabase } from '../utils/supabaseClient'
-import Auth from '../components/Auth'
-import Account from '../components/Account'
-
-export default function Home() {
- const [isLoading, setIsLoading] = useState(true)
- const [session, setSession] = useState(null)
+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(() => {
- let mounted = true
+ getProfile()
+ }, [session])
- async function getInitialSession() {
- const {
- data: { session },
- } = await supabase.auth.getSession()
+ 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()
- // only update the react state if the component is still mounted
- if (mounted) {
- if (session) {
- setSession(session)
- }
+ if (error && status !== 406) {
+ throw error
+ }
- setIsLoading(false)
+ 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)
}
+ }
- getInitialSession()
+ 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 { subscription } = supabase.auth.onAuthStateChange(
- (_event, session) => {
- setSession(session)
+ const updates = {
+ id: user.id,
+ username,
+ website,
+ avatar_url,
+ updated_at: new Date().toISOString(),
}
- )
-
- return () => {
- mounted = false
- subscription?.unsubscribe()
+ 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>
+ )
+}
+```
+
+</TabItem>
+</Tabs>
+
+### Launch!
+
+Now that we have all the components in place, let's update `pages/index.js`:
+
+```jsx title="pages/index.js"
+import type { NextPage } from 'next'
+import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
+import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
+// highlight-next-line
+import Account from '../components/Account'
+
+const Home: NextPage = () => {
+ const session = useSession()
+ const supabase = useSupabaseClient()
return (
<div className="container" style={{ padding: '50px 0 100px 0' }}>
{!session ? (
- <Auth />
+ <Auth
+ supabaseClient={supabase}
+ appearance={{ theme: ThemeSupa }}
+ theme="dark"
+ />
) : (
- <Account key={session.user.id} session={session} />
+ // highlight-next-line
+ <Account session={session} />
)}
</div>
)
}
+
+export default Home
```
Once that's done, run this in a terminal window:
@@ -462,8 +636,6 @@ npm run dev
And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
-![Supabase User demo](/img/supabase-react-demo.png)
-
## Bonus: Profile photos
Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like
@@ -471,14 +643,22 @@ photos and videos.
### Create an upload widget
-Let's create an avatar for the user so that they can upload a profile photo.
-We can start by creating a new component:
+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
+ defaultValue="js"
+ values={[
+ {label: 'JavaScript', value: 'js'},
+ {label: 'TypeScript', value: 'ts'},
+ ]}>
+<TabItem value="js">
```jsx title="components/Avatar.js"
-import { useEffect, useState } from 'react'
-import { supabase } from '../utils/supabaseClient'
+import React, { useEffect, useState } from 'react'
+import { useSupabaseClient } from '@supabase/auth-helpers-react'
-export default function Avatar({ url, size, onUpload }) {
+export default function Avatar({ uid, url, size, onUpload }) {
+ const supabase = useSupabaseClient()
const [avatarUrl, setAvatarUrl] = useState(null)
const [uploading, setUploading] = useState(false)
@@ -497,11 +677,11 @@ export default function Avatar({ url, size, onUpload }) {
const url = URL.createObjectURL(data)
setAvatarUrl(url)
} catch (error) {
- console.log('Error downloading image: ', error.message)
+ console.log('Error downloading image: ', error)
}
}
- async function uploadAvatar(event) {
+ const uploadAvatar = async (event) => {
try {
setUploading(true)
@@ -511,7 +691,7 @@ export default function Avatar({ url, size, onUpload }) {
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
- const fileName = `${Math.random()}.${fileExt}`
+ const fileName = `${uid}.${fileExt}`
const filePath = `${fileName}`
let { error: uploadError } = await supabase.storage
@@ -524,7 +704,8 @@ export default function Avatar({ url, size, onUpload }) {
onUpload(filePath)
} catch (error) {
- alert(error.message)
+ alert('Error uploading avatar!')
+ console.log(error)
} finally {
setUploading(false)
}
@@ -566,6 +747,120 @@ export default function Avatar({ url, size, onUpload }) {
}
```
+</TabItem>
+<TabItem value="ts">
+
+```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)
+
+ 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>
+ )
+}
+```
+
+</TabItem>
+</Tabs>
+
### Add the new widget
And then we can add the widget to the Account page:
@@ -580,6 +875,7 @@ return (
<div className="form-widget">
{/* Add to the body */}
<Avatar
+ uid={user.id}
url={avatar_url}
size={150}
onUpload={(url) => {