Facebook Pixel
Step-by-Step Guide

How to Implement Authentication Flow in React

A step-by-step guide on how to implement login, logout, protected routes, and persistent authentication state in a React application.

Set Up an Auth Context

Create a React Context specifically for authentication. The context will hold the current user object, a login function, and a logout function. Wrap your entire application with the Auth Context Provider so every component in the tree can access authentication state without prop drilling.

Manage the User State

Inside the Auth Provider component, create a user state variable using useState initialized to null. A null user means no one is logged in. When the user successfully authenticates, update this state with the user object. All components that consume the context will automatically re-render with the new authentication status.

Implement the Login Function

Write an async login function that accepts credentials, calls your authentication API, and on success stores the returned token in localStorage or a secure cookie for persistence. Then set the user state with the returned user data. This function is exposed through the context so any component can trigger a login.

Implement the Logout Function

Write a logout function that clears the token from localStorage, sets the user state back to null, and optionally calls a logout endpoint on your server to invalidate the token server-side. Expose this through the context. Any component like a navbar can call it when the user clicks the logout button.

Restore Authentication on Page Refresh

When the app loads, check localStorage for an existing token inside a useEffect with an empty dependency array. If a valid token exists, use it to fetch the current user's profile from your API and populate the user state. This restores the authenticated session automatically so users do not have to log in again after a page refresh.

Create a Protected Route Component

Build a ProtectedRoute component that reads the user from the Auth Context. If the user is null, redirect the user to the login page using React Router's Navigate component. If the user exists, render the Outlet component which displays the protected child routes. Wrap all routes that require authentication with this component.

Handle Loading State During Auth Check

Add an isAuthChecking boolean state that starts as true and is set to false after the initial token validation in useEffect completes. While isAuthChecking is true, render a full-screen loading indicator instead of your routes. This prevents a flash of the login page before the auth state is restored from localStorage.

Protect API Requests with the Token

Create an Axios instance or a fetch wrapper that automatically attaches the authentication token as a Bearer token in the Authorization header of every outgoing request. Also add an interceptor that handles 401 Unauthorized responses by calling the logout function and redirecting to the login page, ensuring expired sessions are handled gracefully.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.