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.
1// pages/supabase.tsx2import { useAuth } from '@clerk/nextjs';3import { supabase } from './supabaseClient';45function SupabasePage() {6const { getToken, isLoaded, isSignedIn } = useAuth();78if (!isLoaded || !isSignedIn) {9// You can handle the loading or signed state separately10return null;11}1213const fetchDataFromSupabase = async () => {14const token = await getToken({ template: 'supabase' });15supabase.auth.setAuth(token);16const { data } = await supabase.from('your-table').select();17return data;18}1920return <div>...</div>;21}2223export default App;
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);