Skip to content

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

feat(examples): Add nextjs-with-supabase-auth example.

Thorsten Schaefff0c5f879c4f8
diff --git a/examples/nextjs-with-supabase-auth/.env.local.example b/examples/nextjs-with-supabase-auth/.env.local.example
new file mode 100644
index 00000000000..3b3abc14b0c
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/.env.local.example
@@ -0,0 +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
diff --git a/examples/nextjs-with-supabase-auth/.gitignore b/examples/nextjs-with-supabase-auth/.gitignore
new file mode 100644
index 00000000000..1437c53f70b
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/.gitignore
@@ -0,0 +1,34 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# local env files
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+# vercel
+.vercel
diff --git a/examples/nextjs-with-supabase-auth/README.md b/examples/nextjs-with-supabase-auth/README.md
new file mode 100644
index 00000000000..dacf6008e30
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/README.md
@@ -0,0 +1,55 @@
+# Example: Supabase authentication client- and server-side (API routes)
+
+This example shows how to use Supabase auth both on the client (`useUser` hook) and server in [API routes](https://nextjs.org/docs/api-routes/introduction).
+
+## Demo
+
+- See it in action on [CodeSandbox](https://codesandbox.io/s/github/thorwebdev/nextjs-with-supabase-auth).
+
+## 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/with-supabase-auth with-supabase-auth-app
+# or
+yarn create next-app --example https://github.com/supabase/supabase/tree/master/examples/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/import/git?s=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.
diff --git a/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js b/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js
new file mode 100644
index 00000000000..b65603cd56f
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/components/SupabaseAuth.js
@@ -0,0 +1,93 @@
+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/package.json b/examples/nextjs-with-supabase-auth/package.json
new file mode 100644
index 00000000000..c2a13b9c52e
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "with-supabase-auth",
+ "version": "1.0.0",
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start"
+ },
+ "dependencies": {
+ "@supabase/supabase-js": "^1.0.1",
+ "next": "latest",
+ "react": "^16.13.1",
+ "react-dom": "^16.13.1",
+ "swr": "0.2.3"
+ },
+ "license": "MIT"
+}
diff --git a/examples/nextjs-with-supabase-auth/pages/api/getUser.js b/examples/nextjs-with-supabase-auth/pages/api/getUser.js
new file mode 100644
index 00000000000..196937de3d8
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/pages/api/getUser.js
@@ -0,0 +1,13 @@
+import { supabase } from '../../utils/initSupabase';
+
+// Example of how to verify and get user data server-side.
+const getUser = async (req, res) => {
+ const token = req.headers.token;
+
+ const { data: user, error } = await supabase.auth.api.getUser(token);
+
+ if (error) return res.status(401).json({ error: error.message });
+ return res.status(200).json(user);
+};
+
+export default getUser;
diff --git a/examples/nextjs-with-supabase-auth/pages/index.js b/examples/nextjs-with-supabase-auth/pages/index.js
new file mode 100644
index 00000000000..9f88d8afdb0
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/pages/index.js
@@ -0,0 +1,60 @@
+import useSWR from 'swr';
+import { useUser } from '../utils/useUser';
+import { supabase } from '../utils/initSupabase';
+import SupabaseAuth from '../components/SupabaseAuth';
+
+const fetcher = (url, token) =>
+ fetch(url, {
+ method: 'GET',
+ headers: new Headers({ 'Content-Type': 'application/json', token }),
+ credentials: 'same-origin',
+ }).then((res) => res.json());
+
+const Index = () => {
+ const { user, session } = useUser();
+ const { data, error } = useSWR(
+ session ? ['/api/getUser', session.access_token] : null,
+ fetcher
+ );
+ if (!user) {
+ return (
+ <>
+ <p>Hi there!</p>
+ <p>You are not signed in.</p>
+ <div>
+ <SupabaseAuth />
+ </div>
+ </>
+ );
+ }
+
+ 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>
+ );
+};
+
+export default Index;
diff --git a/examples/nextjs-with-supabase-auth/utils/initSupabase.js b/examples/nextjs-with-supabase-auth/utils/initSupabase.js
new file mode 100644
index 00000000000..db7f65cb345
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/utils/initSupabase.js
@@ -0,0 +1,6 @@
+import { createClient } from '@supabase/supabase-js';
+
+export const supabase = createClient(
+ process.env.NEXT_PUBLIC_SUPABASE_URL,
+ process.env.NEXT_PUBLIC_SUPABASE_KEY
+);
diff --git a/examples/nextjs-with-supabase-auth/utils/useUser.js b/examples/nextjs-with-supabase-auth/utils/useUser.js
new file mode 100644
index 00000000000..569c30082f4
--- /dev/null
+++ b/examples/nextjs-with-supabase-auth/utils/useUser.js
@@ -0,0 +1,27 @@
+import { useEffect, useState } from 'react';
+import { supabase } from './initSupabase';
+
+const useUser = () => {
+ const [session, setSession] = useState(null);
+ const [user, setUser] = useState(null);
+
+ useEffect(() => {
+ setSession(supabase.auth.session());
+ setUser(supabase.auth.user());
+ const { data: authListener } = supabase.auth.onAuthStateChange(
+ (event, session) => {
+ console.log(`Supbase auth event: ${event}`);
+ setSession(session);
+ setUser(session?.user ?? null);
+ }
+ );
+ return () => {
+ authListener.unsubscribe();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return { user, session };
+};
+
+export { useUser };