diff options
Diffstat (limited to 'frontend/src/lib/api/index.js')
-rw-r--r-- | frontend/src/lib/api/index.js | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/frontend/src/lib/api/index.js b/frontend/src/lib/api/index.js new file mode 100644 index 0000000..dca56e3 --- /dev/null +++ b/frontend/src/lib/api/index.js @@ -0,0 +1,40 @@ +import axios from 'axios'; + +const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api'; + +const api = axios.create({ + baseURL: API_URL, + headers: { + 'Content-Type': 'application/json', + }, +}); + +// Request interceptor to add authorization header +api.interceptors.request.use( + (config) => { + const token = localStorage.getItem('token'); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; + }, + (error) => Promise.reject(error) +); + +// Response interceptor to handle errors +api.interceptors.response.use( + (response) => response, + (error) => { + // Handle 401 unauthorized errors + if (error.response && error.response.status === 401) { + localStorage.removeItem('token'); + localStorage.removeItem('user'); + if (typeof window !== 'undefined') { + window.location.href = '/login'; + } + } + return Promise.reject(error); + } +); + +export default api;
\ No newline at end of file |