-
Notifications
You must be signed in to change notification settings - Fork 8
Open
Labels
Description
Description
Create or update api.js to export a configured Axios instance that:
- Automatically attaches Authorization: Bearer when token exists.
- Handles 401 responses centrally (e.g., auto-logout or redirect to login).
- Exposes helper methods: setToken(token), clearToken().
Suggested files
- frontend/src/services/api.js (new or update existing)
- frontend/src/services/authService.js (uses api.js to call /auth/*)
Example api.js
import axios from 'axios';
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL || 'http://localhost:5000/api',
withCredentials: false,
});
export const setAuthToken = (token) => {
if (token) api.defaults.headers.common['Authorization'] = Bearer ${token};
else delete api.defaults.headers.common['Authorization'];
};
api.interceptors.response.use(
res => res,
err => {
if (err.response?.status === 401) {
// optional: emit event to logout or call a callback
window.dispatchEvent(new CustomEvent('app:unauthorized'));
}
return Promise.reject(err);
}
);
export default api;
Acceptance criteria
- All protected API calls automatically include token header.
- On 401, a global event or handler triggers logout and redirect to /login.
- AuthContext calls setAuthToken on login and clears on logout.
Testing checklist
- After login, protected endpoints are called with Authorization header.
- When server returns 401, application logs out or navigates to /login.
- Token removal prevents further authorized calls.