Skip to content

Instantly share code, notes, and snippets.

@Bendzae
Last active July 10, 2025 12:31
Show Gist options
  • Select an option

  • Save Bendzae/a997d8113051d2567092e0bdd51dfe4c to your computer and use it in GitHub Desktop.

Select an option

Save Bendzae/a997d8113051d2567092e0bdd51dfe4c to your computer and use it in GitHub Desktop.
// AuthContext.tsx
import React, { createContext, useContext, ReactNode } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
interface AuthContextType {
getToken: () => Promise<string | null>;
isAuthenticated: boolean;
isLoading: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const { getAccessTokenSilently, isAuthenticated, isLoading } = useAuth0();
const getToken = async (): Promise<string | null> => {
if (!isAuthenticated) return null;
try {
return await getAccessTokenSilently();
} catch {
return null;
}
};
return (
<AuthContext.Provider value={{ getToken, isAuthenticated, isLoading }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment