useAuth
Access the auth state inside your React components.
Overview
The useAuth
hook is a convenient way to access the current auth state. This hook provides the minimal information needed for data-loading and helper methods to manage the current active session.
This hook is compatible with SSR and is recommended for all authentication tasks.
const {userId,sessionId,getToken,isLoaded,isSignedIn,signOut,orgId,orgRole,orgSlug,} = useAuth();
This new hook should be used instead of:
useSession(
) , to accessgetToken(
) or thesessionId
useUser()
, to accessgetToken()
for integrationsuseClerk()
, to accesssignOut()
Usage
In the following basic example, useAuth
is used to access the auth state and generate a new JWT for a custom Supabase integration in a NextJS application. Note that your component must be a descendant of <ClerkProvider/>.
Typescript
For better type support, we highly recommend updating to at least Typescript 4.6. Applications using Typescript will benefit significantly from Typescript's new Control Flow Analysis for Dependent Parameters when using our hooks.
1import { useAuth } from '@clerk/clerk-react';2import { createClient } from "@supabase/supabase-js";34const supabaseClient = async (supabaseAccessToken) => {5const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_KEY, {6global: { headers: { Authorization: `Bearer ${supabaseAccessToken}` } },7});8// set Supabase JWT on the client object,9// so it is sent up with all Supabase requests10return supabase;11};1213function App() {14const { getToken } = useAuth();1516const fetchData = async () => {17// TODO #1: Replace with your JWT template name18const supabaseAccessToken = await getToken({ template: 'supabase' });1920const supabase = await supabaseClient(supabaseAccessToken);2122// TODO #2: Replace with your database table name2324const { data, error } = await supabase.from('your_table').select();2526// TODO #3: Handle the response27};2829return (30<div className="app">31<button onClick={fetchData}>Fetch data</button>32</div>33);34}
Alternative ways to access the auth object
There are times when you may need to access the auth object during SSR, API handlers and Edge middleware. The auth object is also available in Next.js, Remix, and Gatsby API routes, even during server-side rendering.
The following snippets are quick examples for NextJS applications. For more details, look at the starter guide for your framework of choice.
API Routes: req.auth
1import { withAuth } from "@clerk/nextjs/api";23export default withAuth(async ( req, res ) => {4const { userId } = req.auth;5// Load any data your application needs for the API route6return { props: {} };7});
Server-side rendering: req.auth
/pages/mypage.jsx1import { withServerSideAuth } from "@clerk/nextjs/ssr";23export default MyPage(){4return ...;5}67export const getServerSideProps = withServerSideAuth(8async ({ req }) => {9const { userId } = req.auth;10// Load any data your application needs and pass to props11return { props: {} };12}13);
Edge Middleware: req.auth
1import { withEdgeMiddlewareAuth } from "@clerk/nextjs/edge-middleware";23export default withEdgeMiddlewareAuth(4async ( req ) => {5const { userId } = req.auth;6// Run your middleware78// Complete response9return NextResponse.next();10}11);