Using the API Client
We use a centralized ApiClient (wrapper around fetch) to handle all HTTP requests.
It is located at lib/api/client.ts. All requests are prefixed with /api/v1 (e.g. /users/me → {baseUrl}/api/v1/users/me).
Basics
import { apiClient } from "@/lib/api/client";
// GET (endpoint is relative to /api/v1)
const data = await apiClient.get<User>("/users/me");
// POST
await apiClient.post("/cameras", { name: "Stable 1" });
Features
1. Automatic Authentication
The client automatically retrieves the JWT from the TokenManager and injects it into the Authorization header. You don't need to pass the token manually.
2. Error Handling
If the API returns an error (4xx/5xx), the promise rejects with an instance of ApiError.
try {
await apiClient.post(...)
} catch (error) {
if (error instanceof ApiError) {
console.log(error.status); // 400
console.log(error.code); // VALIDATION_ERROR (from API v1)
console.log(error.errors); // { email: ['Invalid email'] }
}
}
3. Rate Limiting (429)
The client automatically parses the Retry-After header and throws a user-friendly error message:
"Trop de tentatives. Veuillez réessayer dans 45 secondes."
4. 401 Handling
If a request fails with 401 Unauthorized, the client automatically:
- Clears the local token.
- Redirects the user to
/login.