36
loading...
This website collects cookies to deliver better user experience
View the video tutorial of this guide here. As a disclaimer, Supabase is also a sponsor of my YouTube channel
getServerSideProps
if a cookie has been set and is available in the request context.import { supabase } from '../../client'
export default function handler(req, res) {
supabase.auth.api.setAuthCookie(req, res)
}
export async function getServerSideProps({ req }) {
const { user } = await supabase.auth.api.getUserByCookie(req)
if (!user) {
return {
props: {}
}
}
/* if user is present, do something with the user data here */
return { props: { user } }
}
getUserByCookie
function, opening up an entirely new set of use cases and functionality.The final code for this project is located here
npx create-next-app supabase-next-auth
cd supabase-next-auth
@supabase/supabase-js
package:npm install @supabase/supabase-js
NEXT_PUBLIC_SUPABASE_URL=https://app-id.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-public-api-key
/* client.js */
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
)
export { supabase }
/* pages/index.js */
import styles from '../styles/Home.module.css'
export default function Home() {
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Hello World!
</h1>
</main>
</div>
)
}
/* pages/sign-in.js */
import { useState } from 'react'
import styles from '../styles/Home.module.css'
import { supabase } from '../client'
export default function SignIn() {
const [email, setEmail] = useState('')
const [submitted, setSubmitted] = useState(false)
async function signIn() {
const { error, data } = await supabase.auth.signIn({
email
})
if (error) {
console.log({ error })
} else {
setSubmitted(true)
}
}
if (submitted) {
return (
<div className={styles.container}>
<h1>Please check your email to sign in</h1>
</div>
)
}
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Sign In
</h1>
<input
onChange={e => setEmail(e.target.value)}
style={{ margin: 10 }}
/>
<button onClick={() => signIn()}>Sign In</button>
</main>
</div>
)
}
const { error, data } = await supabase.auth.signIn({
email
})
/* pages/profile.js */
import { useState, useEffect } from 'react';
import { supabase } from '../client'
import { useRouter } from 'next/router'
export default function Profile() {
const [profile, setProfile] = useState(null)
const router = useRouter()
useEffect(() => {
fetchProfile()
}, [])
async function fetchProfile() {
const profileData = await supabase.auth.user()
if (!profileData) {
router.push('/sign-in')
} else {
setProfile(profileData)
}
}
async function signOut() {
await supabase.auth.signOut()
router.push('/sign-in')
}
if (!profile) return null
return (
<div style={{ maxWidth: '420px', margin: '96px auto' }}>
<h2>Hello, {profile.email}</h2>
<p>User ID: {profile.id}</p>
<button onClick={signOut}>Sign Out</button>
</div>
)
}
supabase.auth.user()
.setProfile
function set up using the useState
hook.useRouter
hook.setAuthCookie
API given to us by the Supabase client./* pages/api/auth.js */
import { supabase } from '../../client'
export default function handler(req, res) {
supabase.auth.api.setAuthCookie(req, res)
}
/* pages/_app.js */
import '../styles/globals.css'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { supabase } from '../client'
import { useRouter } from 'next/router'
function MyApp({ Component, pageProps }) {
const router = useRouter()
const [authenticatedState, setAuthenticatedState] = useState('not-authenticated')
useEffect(() => {
/* fires when a user signs in or out */
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
handleAuthChange(event, session)
if (event === 'SIGNED_IN') {
setAuthenticatedState('authenticated')
router.push('/profile')
}
if (event === 'SIGNED_OUT') {
setAuthenticatedState('not-authenticated')
}
})
checkUser()
return () => {
authListener.unsubscribe()
}
}, [])
async function checkUser() {
/* when the component loads, checks user to show or hide Sign In link */
const user = await supabase.auth.user()
if (user) {
setAuthenticatedState('authenticated')
}
}
async function handleAuthChange(event, session) {
/* sets and removes the Supabase cookie */
await fetch('/api/auth', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
credentials: 'same-origin',
body: JSON.stringify({ event, session }),
})
}
return (
<div>
<nav style={navStyle}>
<Link href="/">
<a style={linkStyle}>Home</a>
</Link>
<Link href="/profile">
<a style={linkStyle}>Profile</a>
</Link>
{
authenticatedState === 'not-authenticated' && (
<Link href="/sign-in">
<a style={linkStyle}>Sign In</a>
</Link>
)
}
<Link href="/protected">
<a style={linkStyle}>Protected</a>
</Link>
</nav>
<Component {...pageProps} />
</div>
)
}
const navStyle = {
margin: 20
}
const linkStyle = {
marginRight: 10
}
export default MyApp
getUserByCookie
function.import { supabase } from '../client'
export default function Protected({ user }) {
console.log({ user })
return (
<div style={{ maxWidth: '420px', margin: '96px auto' }}>
<h2>Hello from protected route</h2>
</div>
)
}
export async function getServerSideProps({ req }) {
/* check to see if a user is set */
const { user } = await supabase.auth.api.getUserByCookie(req)
/* if no user is set, redirect to the sign-in page */
if (!user) {
return { props: {}, redirect: { destination: '/sign-in' } }
}
/* if a user is set, pass it to the page via props */
return { props: { user } }
}
npm run dev
update
method.const { user, error } = await supabase.auth.update({
data: {
city: "New York"
}
})
The final code for this project is located here