Skip to content

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

feat: Add Supabase Auth components, update password, and SSR Cookie example. (#512)

Thor 雷神 Schaeffaf99c593bc2a
diff --git a/examples/nextjs-with-supabase-auth/.env.local.example b/examples/nextjs-with-supabase-auth/.env.local.example
index 3b3abc14b0c..477da3d401d 100644
--- a/examples/nextjs-with-supabase-auth/.env.local.example
+++ b/examples/nextjs-with-supabase-auth/.env.local.example
@@ -1,3 +1,3 @@
# Update these with your Supabase details from your project settings > API
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
-NEXT_PUBLIC_SUPABASE_KEY=your-anon-key
\ No newline at end of file
+NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
\ No newline at end of file
diff --git a/examples/nextjs-with-supabase-auth/README.md b/examples/nextjs-with-supabase-auth/README.md
index a525eb46064..c09acaaa35d 100644
--- a/examples/nextjs-with-supabase-auth/README.md
+++ b/examples/nextjs-with-supabase-auth/README.md
@@ -1,55 +1,9 @@
-# Example: Supabase authentication client- and server-side (API routes)
+# Example: Supabase authentication client- and server-side (API routes), and SSR with auth cookie.
-This example shows how to use Supabase auth both on the client (`useUser` hook from the `UserContext` component) and server in [API routes](https://nextjs.org/docs/api-routes/introduction).
+This example shows how to use Supabase auth both on the client and server in both [API routes](https://nextjs.org/docs/api-routes/introduction) and when using [server side rendering (SSR)](https://nextjs.org/docs/basic-features/pages#server-side-rendering).
-## Demo
+## Deploy with Vercel
-- See it in action on [CodeSandbox](https://codesandbox.io/s/github/thorwebdev/nextjs-with-supabase-auth).
+The Vercel deployment will guide you through creating a Supabase account and project. After installation of the Supabase integration, all relevant environment variables will be set up so that the project is usable immediately after deployment 🚀
-## How to use
-
-Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
-
-```bash
-npx create-next-app --example https://github.com/supabase/supabase/tree/master/examples/nextjs-with-supabase-auth with-supabase-auth-app
-# or
-yarn create next-app --example https://github.com/supabase/supabase/tree/master/examples/nextjs-with-supabase-auth with-supabase-auth-app
-```
-
-## Configuration
-
-### 1. Create new project
-
-Sign up to Supabase - [https://app.supabase.io](https://app.supabase.io) and create a new project. Wait for your database to start.
-
-### 2. Get the URL and Key
-
-Create a copy of `.env.local.example`:
-
-```bash
-cp .env.local.example .env.local
-```
-
-Go to the Project Settings (the cog icon), open the API tab, and find your API URL and `anon` key and set them in your newly created `.env.local` file.
-
-#### [Optional] - Set up OAuth providers
-
-You can use third-party login providers like GitHub or Google. Refer to the [docs](https://supabase.io/docs/guides/auth#third-party-logins) to learn how to configure these.
-
-### 3. Install and run
-
-```bash
-npm install
-npm run dev
-# or
-yarn
-yarn dev
-```
-
-### 4. Deploy with Vercel
-
-[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Fnextjs-with-supabase-auth&env=NEXT_PUBLIC_SUPABASE_URL,NEXT_PUBLIC_SUPABASE_KEY&envDescription=Find%20the%20Supabase%20URL%20and%20key%20in%20your%20auto-generated%20docs%20at%20app.supabase.io&project-name=nextjs-with-supabase-auth&repo-name=nextjs-with-supabase-auth)
-
-You will be asked for the `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_KEY` from step 2 above.
-
-After deploying, copy the deployment URL and navigate to your Supabase project settings (Authentication > Settings) and set your site url.
+[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Fnextjs-with-supabase-auth&project-name=nextjs-with-supabase-auth&repository-name=nextjs-with-supabase-auth&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv)
diff --git a/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js b/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js
deleted file mode 100644
index b65603cd56f..00000000000
--- a/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useState } from 'react';
-import { supabase } from '../utils/initSupabase';
-
-export default function SupabaseAuth() {
- const [email, setEmail] = useState('');
- const [password, setPassword] = useState('');
-
- const handleLogin = async (type, email, password) => {
- const { error, user } =
- type === 'LOGIN'
- ? await supabase.auth.signIn({ email, password })
- : await supabase.auth.signUp({ email, password });
- if (!error && !user) alert('Check your email for the login link!');
- if (error) alert(error.message);
- };
-
- async function handleOAuthLogin(provider) {
- let { error } = await supabase.auth.signIn({ provider });
- if (error) alert(error.message);
- }
-
- async function forgotPassword() {
- const email = prompt('Please enter your email:');
- if (email === null || email === '')
- return alert('You must enter your email.');
-
- const { error } = await supabase.auth.api.resetPasswordForEmail(email);
- if (error) return alert(error.message);
- alert('Password recovery email has been sent.');
- }
-
- return (
- <div>
- <div>
- <label>Email</label>
- <input
- type="text"
- placeholder="Your email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- />
- </div>
- <div>
- <label>Password</label>
- <input
- type="password"
- placeholder="Your password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- />
- </div>
-
- <div>
- <button
- onClick={() => {
- handleLogin('SIGNUP', email, password);
- }}
- >
- Sign up
- </button>
- <button
- onClick={() => {
- handleLogin('LOGIN', email, password);
- }}
- >
- {password.length ? 'Sign in' : 'Send magic link'}
- </button>
- </div>
-
- <div>
- <button onClick={forgotPassword}>Forgot your password?</button>
- </div>
-
- <div>
- <hr />
- <span>Or continue with</span>
-
- <div>
- <div>
- <button onClick={() => handleOAuthLogin('github')} type="button">
- GitHub
- </button>
- </div>
- <div>
- <button onClick={() => handleOAuthLogin('google')} type="button">
- Google
- </button>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/examples/nextjs-with-supabase-auth/components/UserContext.js b/examples/nextjs-with-supabase-auth/components/UserContext.js
deleted file mode 100644
index e858351de2e..00000000000
--- a/examples/nextjs-with-supabase-auth/components/UserContext.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import { useEffect, useState, createContext, useContext } from 'react'
-import { supabase } from '../utils/initSupabase'
-
-export const UserContext = createContext()
-
-export const UserContextProvider = (props) => {
- const [session, setSession] = useState(null)
- const [user, setUser] = useState(null)
-
- useEffect(() => {
- const session = supabase.auth.session()
- setSession(session)
- setUser(session?.user ?? null)
- const { data: authListener } = supabase.auth.onAuthStateChange(async (event, session) => {
- setSession(session)
- setUser(session?.user ?? null)
- })
-
- return () => {
- authListener.unsubscribe()
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
-
- const value = {
- session,
- user,
- }
- return <UserContext.Provider value={value} {...props} />
-}
-
-export const useUser = () => {
- const context = useContext(UserContext)
- if (context === undefined) {
- throw new Error(`useUser must be used within a UserContextProvider.`)
- }
- return context
-}
diff --git a/examples/nextjs-with-supabase-auth/package.json b/examples/nextjs-with-supabase-auth/package.json
index c2a13b9c52e..b05bb8417e8 100644
--- a/examples/nextjs-with-supabase-auth/package.json
+++ b/examples/nextjs-with-supabase-auth/package.json
@@ -7,7 +7,8 @@
"start": "next start"
},
"dependencies": {
- "@supabase/supabase-js": "^1.0.1",
+ "@supabase/supabase-js": "^1.2.1",
+ "@supabase/ui": "^0.6.1",
"next": "latest",
"react": "^16.13.1",
"react-dom": "^16.13.1",
diff --git a/examples/nextjs-with-supabase-auth/pages/_app.js b/examples/nextjs-with-supabase-auth/pages/_app.js
index b472b590c9f..62d631ce30d 100644
--- a/examples/nextjs-with-supabase-auth/pages/_app.js
+++ b/examples/nextjs-with-supabase-auth/pages/_app.js
@@ -1,9 +1,13 @@
-import { UserContextProvider } from '../components/UserContext'
+import { Auth } from '@supabase/ui'
+import { supabase } from '../utils/initSupabase'
+import './../style.css'
export default function MyApp({ Component, pageProps }) {
return (
- <UserContextProvider>
- <Component {...pageProps} />
- </UserContextProvider>
+ <main className={'dark'}>
+ <Auth.UserContextProvider supabaseClient={supabase}>
+ <Component {...pageProps} />
+ </Auth.UserContextProvider>
+ </main>
)
}
diff --git a/examples/nextjs-with-supabase-auth/pages/api/auth.js b/examples/nextjs-with-supabase-auth/pages/api/auth.js
new file mode 100644
index 00000000000..2d5c3814003
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/pages/api/auth.js
@@ -0,0 +1,8 @@
+/**
+ * NOTE: this file is only needed if you're doing SSR (getServerSideProps)!
+ */
+import { supabase } from '../../utils/initSupabase'
+
+export default function handler(req, res) {
+ supabase.auth.api.setAuthCookie(req, res)
+}
diff --git a/examples/nextjs-with-supabase-auth/pages/index.js b/examples/nextjs-with-supabase-auth/pages/index.js
index 82a4278927b..5ae1ee01a08 100644
--- a/examples/nextjs-with-supabase-auth/pages/index.js
+++ b/examples/nextjs-with-supabase-auth/pages/index.js
@@ -1,7 +1,8 @@
+import Link from 'next/link'
import useSWR from 'swr'
-import { useUser } from '../components/UserContext'
+import { Auth, Card, Typography, Space, Button, Icon } from '@supabase/ui'
import { supabase } from '../utils/initSupabase'
-import SupabaseAuth from '../components/SupabaseAuth'
+import { useEffect, useState } from 'react'
const fetcher = (url, token) =>
fetch(url, {
@@ -11,45 +12,93 @@ const fetcher = (url, token) =>
}).then((res) => res.json())
const Index = () => {
- const { user, session } = useUser()
+ const { user, session } = Auth.useUser()
const { data, error } = useSWR(session ? ['/api/getUser', session.access_token] : null, fetcher)
- if (!user) {
+ const [authView, setAuthView] = useState('sign_in')
+
+ useEffect(() => {
+ const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
+ if (event === 'PASSWORD_RECOVERY') setAuthView('update_password')
+ if (event === 'USER_UPDATED') setTimeout(() => setAuthView('sign_in'), 1000)
+ // Send session to /api/auth route to set the auth cookie.
+ // NOTE: this is only needed if you're doing SSR (getServerSideProps)!
+ fetch('/api/auth', {
+ method: 'POST',
+ headers: new Headers({ 'Content-Type': 'application/json' }),
+ credentials: 'same-origin',
+ body: JSON.stringify({ event, session }),
+ }).then((res) => res.json())
+ })
+
+ return () => {
+ authListener.unsubscribe()
+ }
+ }, [])
+
+ const View = () => {
+ if (!user)
+ return (
+ <Space direction="vertical" size={8}>
+ <div>
+ <img src="https://app.supabase.io/img/supabase-dark.svg" width="96" />
+ <Typography.Title level={3}>Welcome to Supabase Auth</Typography.Title>
+ </div>
+ <Auth
+ supabaseClient={supabase}
+ providers={['google', 'github']}
+ view={authView}
+ socialLayout="horizontal"
+ socialButtonSize="xlarge"
+ />
+ </Space>
+ )
+
return (
- <>
- <p>Hi there!</p>
- <p>You are not signed in.</p>
- <div>
- <SupabaseAuth />
- </div>
- </>
+ <Space direction="vertical" size={6}>
+ {authView === 'update_password' && <Auth.UpdatePassword supabaseClient={supabase} />}
+ {user && (
+ <>
+ <Typography.Text>You're signed in</Typography.Text>
+ <Typography.Text strong>Email: {user.email}</Typography.Text>
+
+ <Button
+ icon={<Icon type="LogOut" />}
+ type="outline"
+ onClick={() => supabase.auth.signOut()}
+ >
+ Log out
+ </Button>
+ {error && <Typography.Text danger>Failed to fetch user!</Typography.Text>}
+ {data && !error ? (
+ <>
+ <Typography.Text type="success">
+ User data retrieved server-side (in API route):
+ </Typography.Text>
+
+ <Typography.Text>
+ <pre>{JSON.stringify(data, null, 2)}</pre>
+ </Typography.Text>
+ </>
+ ) : (
+ <div>Loading...</div>
+ )}
+
+ <Typography.Text>
+ <Link href="/profile">
+ <a>SSR example with getServerSideProps</a>
+ </Link>
+ </Typography.Text>
+ </>
+ )}
+ </Space>
)
}
return (
- <div>
- <p
- style={{
- display: 'inline-block',
- color: 'blue',
- textDecoration: 'underline',
- cursor: 'pointer',
- }}
- onClick={() => supabase.auth.signOut()}
- >
- Log out
- </p>
- <div>
- <p>You're signed in. Email: {user.email}</p>
- </div>
- {error && <div>Failed to fetch user!</div>}
- {data && !error ? (
- <div>
- <span>User data retrieved server-side (in API route):</span>
- <pre>{JSON.stringify(data, null, 2)}</pre>
- </div>
- ) : (
- <div>Loading...</div>
- )}
+ <div style={{ maxWidth: '420px', margin: '96px auto' }}>
+ <Card>
+ <View />
+ </Card>
</div>
)
}
diff --git a/examples/nextjs-with-supabase-auth/pages/profile.js b/examples/nextjs-with-supabase-auth/pages/profile.js
new file mode 100644
index 00000000000..27c9206c236
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/pages/profile.js
@@ -0,0 +1,41 @@
+import Link from 'next/link'
+import { Card, Typography, Space } from '@supabase/ui'
+import { supabase } from '../utils/initSupabase'
+
+export default function Profile({ user }) {
+ return (
+ <div style={{ maxWidth: '420px', margin: '96px auto' }}>
+ <Card>
+ <Space direction="vertical" size={6}>
+ <Typography.Text>You're signed in</Typography.Text>
+ <Typography.Text strong>Email: {user.email}</Typography.Text>
+ <Typography.Text type="success">
+ User data retrieved server-side (from Cookie in getServerSideProps):
+ </Typography.Text>
+
+ <Typography.Text>
+ <pre>{JSON.stringify(user, null, 2)}</pre>
+ </Typography.Text>
+
+ <Typography.Text>
+ <Link href="/">
+ <a>Static example with useSWR</a>
+ </Link>
+ </Typography.Text>
+ </Space>
+ </Card>
+ </div>
+ )
+}
+
+export async function getServerSideProps({ req }) {
+ const { user } = await supabase.auth.api.getUserByCookie(req)
+
+ if (!user) {
+ // If no user, redirect to index.
+ return { props: {}, redirect: { destination: '/', permanent: false } }
+ }
+
+ // If there is a user, return it.
+ return { props: { user } }
+}
diff --git a/examples/nextjs-with-supabase-auth/style.css b/examples/nextjs-with-supabase-auth/style.css
new file mode 100644
index 00000000000..f1bf15cc288
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/style.css
@@ -0,0 +1,4 @@
+body {
+ background: #3d3d3d;
+ font-family: Helvetica, Arial, Sans-Serif;
+}
diff --git a/examples/nextjs-with-supabase-auth/utils/initSupabase.js b/examples/nextjs-with-supabase-auth/utils/initSupabase.js
index db7f65cb345..75092fc556c 100644
--- a/examples/nextjs-with-supabase-auth/utils/initSupabase.js
+++ b/examples/nextjs-with-supabase-auth/utils/initSupabase.js
@@ -1,6 +1,6 @@
-import { createClient } from '@supabase/supabase-js';
+import { createClient } from '@supabase/supabase-js'
export const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
- process.env.NEXT_PUBLIC_SUPABASE_KEY
-);
+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
+)