This project implements a robust user authentication system for a React application. The system includes a context-based authentication state, protected routes, and API utilities with token-based authentication. Below is an overview of the code and its functionalities.
- Overview
- Features
- Technologies Used
- Folder Structure
- Setup and Installation
- Code Breakdown
- Usage
- Future Enhancements
- Contributing
This project demonstrates how to build an authentication system using React's Context API and hooks. It provides seamless token-based authentication with secure API calls, ensuring user data is protected.
- Context API for global state management.
- Token-based authentication.
- Persistent user state using
localStorage
. - Protected routes to restrict access.
- Auto-logout on session expiration.
- Toast notifications for user feedback.
- Axios interceptors for secure API requests.
- React: Frontend framework.
- React Router DOM: For route handling and navigation.
- Axios: For making HTTP requests.
- React Hot Toast: For notifications.
- LocalStorage: For persisting user data.
project-root/
├── src/
├── apis/
│ └── apiService.js
├── components/
│ └── [Your Components]
├── context/
│ └── AuthContext.js
├── hooks/
│ └── useAuth.js
├── routes/
│ └── ProtectedRoute.js
├── App.js
├── index.js
├── styles/
└── [Your CSS Files]
-
Clone the repository:
git clone (https://github.com/azzayshakya/Frontend_Auth_Advanced.git)
-
Install dependencies:
npm install
-
Configure the API base URL in
src/apis/apiService.js
:baseURL: "https://YourAPi/api",
-
Start the development server:
npm start
-
Open your browser and navigate to:
http://localhost:3000
The AuthContext
manages user state and provides login/logout functionality. It ensures persistent authentication by syncing with localStorage
.
const login = (userDetails, accessToken) => {
setUser(userDetails);
localStorage.setItem("data", JSON.stringify(userDetails));
localStorage.setItem("token", accessToken);
};
const logout = () => {
setUser(null);
localStorage.removeItem("data");
localStorage.removeItem("token");
};
The useAuth
hook simplifies access to authentication state and actions within components.
const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};
The ProtectedRoute
component restricts access to certain routes based on the user's authentication state.
const ProtectedRoute = ({ children }) => {
const { user } = useAuth();
return user ? children : <Navigate to="/login" />;
};
The apiService.js
file sets up Axios with interceptors to include authentication tokens and handle session expiration.
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
toast.error("Session expired. Please log in again.");
localStorage.removeItem("token");
setTimeout(() => {
window.location.href = "/login";
}, 3000);
}
return Promise.reject(error);
}
);
- Login: Call the
login
method with user details and access token. - Logout: Call the
logout
method to clear the session. - Protected Routes: Wrap components with
ProtectedRoute
orProtectedLoginRoute
to secure them.
- Add role-based access control for user roles (admin, user, etc.).
- Implement refresh tokens for seamless session renewal.
- Improve UI/UX for login and logout flow.
- Integrate with a backend authentication system.
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Submit a pull request with a detailed description of changes.
Happy Coding!