Lesson 6 of 8
Authentication Flows
Authentication in React involves token storage, refresh flows, protected routes, and persisting auth state across page reloads. The most important decision: where to store the access token - memory (most secure), httpOnly cookie (secure + automatic), or localStorage (simple but XSS-vulnerable).
Token Storage - The Security Tradeoff
// OPTION 1: Memory storage (most secure for XSS)
// Tokens stored in a module-level variable - not accessible to XSS scripts
// Downside: lost on page refresh (need refresh token in httpOnly cookie)
let accessToken: string | null = null;
export const tokenStore = {
get: () => accessToken,
set: (token: string) => { accessToken = token; },
clear: () => { accessToken = null; },
};
// OPTION 2: httpOnly Cookie (recommended for production)
// Server sets: Set-Cookie: access_token=...; HttpOnly; Secure; SameSite=Strict
// JavaScript CANNOT access httpOnly cookies - XSS proof
// Automatically sent with every request to same-origin
// Works with Axios: axios.defaults.withCredentials = true;
// OPTION 3: localStorage (simple, but XSS vulnerable)
// Only acceptable for low-risk applications
localStorage.setItem('access_token', token);
// ---- Complete auth flow with React Context ----
interface AuthContextValue {
user: User | null;
isLoading: boolean;
login: (credentials: LoginCredentials) => Promise<void>;
logout: () => Promise<void>;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function AuthProvider({ children }: { children: React.ReactNode }) {
// TanStack Query handles caching and refetching of current user
const queryClient = useQueryClient();
const { data: user, isLoading } = useQuery({
queryKey: ['auth', 'me'],
queryFn: () => api.get<User>('/auth/me').then(r => r.data),
retry: false, // don't retry on 401 (user is not logged in)
staleTime: Infinity, // don't background-refetch auth state
});
const loginMutation = useMutation({
mutationFn: (credentials: LoginCredentials) =>
api.post<{ user: User; token: string }>('/auth/login', credentials).then(r => r.data),
onSuccess: ({ user, token }) => {
tokenStore.set(token); // store in memory
queryClient.setQueryData(['auth', 'me'], user); // update cache immediately
},
});
const logoutMutation = useMutation({
mutationFn: () => api.post('/auth/logout'),
onSettled: () => {
tokenStore.clear();
queryClient.clear(); // clear all cached data on logout
},
});
const value = useMemo(() => ({
user: user ?? null,
isLoading,
login: async (credentials: LoginCredentials) => { await loginMutation.mutateAsync(credentials); },
logout: async () => { await logoutMutation.mutateAsync(); },
isAuthenticated: !!user,
}), [user, isLoading, loginMutation, logoutMutation]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be inside AuthProvider');
return ctx;
}Tip
Tip
Practice Authentication Flows in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Authentication Flows
Practice Task
Note
Practice Task - (1) Write a working example of Authentication Flows from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Authentication Flows is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?