We generally recommend using the new @supabase/ssr package instead of auth-helpers. @supabase/ssr takes the core concepts of the Auth Helpers package and makes them available to any server language or framework. Check out the migration doc to learn more.
This submodule provides convenience helpers for implementing user authentication in Next.js applications using the pages directory.
Retrieve your project URL and anon key in your project's API settings 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.
The Code Exchange API route is required for the server-side auth flow implemented by the Next.js Auth Helpers. It exchanges an auth code for the user's session, which is set as a cookie for future requests made to Supabase.
Create a new file at pages/api/auth/callback.js and populate with the following:
pages/api/auth/callback.js
import { NextApiHandler } from 'next'
import { createPagesServerClient } from '@supabase/auth-helpers-nextjs'
const handler = async (req, res) => {
const { code } = req.query
if (code) {
const supabase = createPagesServerClient({ req, res })
For 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:
import { Auth } from '@supabase/auth-ui-react'
import { ThemeSupa } from '@supabase/auth-ui-shared'
import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
import { useEffect, useState } from 'react'
const LoginPage = () => {
const supabaseClient = useSupabaseClient()
const user = useUser()
const [data, setData] = useState()
useEffect(() => {
async function loadData() {
const { data } = await supabaseClient.from('test').select('*')
const { data } = await supabase.from('users').select('*')
return {
props: {
initialSession: session,
user: session.user,
data: data ?? [],
},
}
}
Server-side data fetching to OAuth APIs using provider token #oauth-provider-token#
When using third-party auth providers, sessions are initiated with an additional provider_token field which is persisted in the auth cookie and can be accessed within the session object. The provider_token can be used to make API requests to the OAuth provider's API endpoints on behalf of the logged-in user.
import { createPagesServerClient } from '@supabase/auth-helpers-nextjs'
export default function ProtectedPage({ user, allRepos }) {
As an alternative to protecting individual pages you can use a Next.js Middleware to protect the entire directory or those that match the config object. In the following example, all requests to /middleware-protected/* will check whether a user is signed in, if successful the request will be forwarded to the destination route, otherwise the user will be redirected:
middleware.ts
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next()
// Create authenticated Supabase Client.
const supabase = createMiddlewareClient({ req, res })
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession()
// Check auth condition
if (session?.user.email?.endsWith('@gmail.com')) {
// Authentication successful, forward request to protected route.
PKCE is the new server-side auth flow implemented by the Next.js Auth Helpers. It requires a new API route for /api/auth/callback that exchanges an auth code for the user's session.
For authentication methods that have a redirectTo or emailRedirectTo, this must be set to this new code exchange API Route - /api/auth/callback. This is an example with the signUp function:
With v0.7.x of the Next.js Auth Helpers a new naming convention has been implemented for createClient functions. The createBrowserSupabaseClient and createServerSupabaseClient functions have been marked as deprecated, and will be removed in a future version of the Auth Helpers.
createBrowserSupabaseClient has been replaced with createPagesBrowserClient
createServerSupabaseClient has been replaced with createPagesServerClient
To make these helpers more flexible as well as more maintainable and easier to upgrade for new versions of Next.js, we're stripping them down to the most useful part which is managing the cookies and giving you an authenticated supabase-js client in any environment (client, server, middleware/edge).
Therefore we're marking the withApiAuth, withPageAuth, and withMiddlewareAuth higher order functions as deprecated and they will be removed in the next minor release (v0.6.X).
Please follow the steps below to update your API routes, pages, and middleware handlers. Thanks!
With the update to supabase-js v2 the auth API routes are no longer required, therefore you can go ahead and delete your auth directory under the /pages/api/ directory. Please refer to the v2 migration guide for the full set of changes within supabase-js.
The /api/auth/logout API route has been removed, please use the signout method instead:
<button
onClick={async () => {
await supabaseClient.auth.signOut()
router.push('/')
}}
>
Logout
</button>
The supabaseClient and supabaseServerClient have been removed in favor of the createPagesBrowserClient and createPagesServerClient methods. This allows you to provide the CLI-generated types to the client:
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 to the Supabase Client to get enhanced type safety and auto completion: