# 🚀 Nexli: High-Performance API Client
**Nexli** is a robust API client designed to provide essential features like offline sync, automatic retries, and rate limiting. This guide shows you how to integrate it with the Axios adapter and implement a clean solution for handling authentication tokens.

## 🛠️ Usage and Configuration

Your `apiClient.js` file demonstrates the correct setup for using Nexli with Vite and Axios.

### 1. `src/apis/apiClient.js` Setup

This file creates the main `ApiClient` instance, injecting necessary adapters (like Axios) and defining global policies.

```js
// src/apis/apiClient.js

import { ApiClient } from "nexli";
import axios from "axios"; // Import Axios for the adapter

// Get Base URL from environment variables
const API_URL = import.meta.env.VITE_API_URL;

const apiClient = new ApiClient({
    // Set Base URL for all requests
    baseUrl: `${API_URL}/api`,

    // Specify the adapter to use by name
    adapter: "axios", 
    
    // Provide the actual Axios library for the adapter to use
    adapters: { 
        axios: axios,
    },

    // Offline Synchronization settings
    offline: {
        enabled: true,
        storageKey: "my_app_pending_sync_requests",
        limit: 20, // Max 20 pending requests
    },

    // Retry policy for enhanced reliability
    retry: {
        maxAttempts: 3,
        delayMs: 1000,
        // Retry only on server errors
        statusCodes: [500, 503],
    },
});

export default apiClient;
```

## 🔑 Authentication and Token Handling (Best Practice)

To ensure the authentication token is attached to every protected request (like `getMyPlan`) without manually passing it, we will use the `ApiClient`'s Default Headers feature.

### 2. Add `setAuthToken` Function to `apiClient.js`

Add the following function to your `apiClient.js` file and export it. This allows you to set the token globally after a successful login.

```js
// src/apis/apiClient.js (Append this function)

/**
 * Sets or removes the Authorization token as a default header 
 * for all subsequent API requests.
 */
export const setAuthToken = (token) => {
    if (token) {
        // This header will be automatically included in every request
        apiClient.setDefaultHeaders({
            Authorization: `Bearer ${token}`,
        });
    } else {
        // Clear the header on logout
        apiClient.removeDefaultHeader('Authorization');
    }
};

export default apiClient;
```

### 3. Implementing API Functions
Here is how you use the new setup in your service file (`apiService.js`).

### Authentication
The `loginUser` function is where you receive the token and immediately set it globally using `setAuthToken`.

```js
// src/apis/apiService.js

import apiClient, { setAuthToken } from "./apiClient"; 

export const loginUser = async (formData) => {
    try {
        const res = await apiClient.post(`/auth/login`, { ...formData });
        
        // 🌟 CRITICAL STEP: Set the token globally upon successful login
        const token = res.data.token;
        setAuthToken(token); 

        return res.data;
    } catch (error) {
        throw new Error(error.response?.data?.message || "Login failed");
    }
};
```
### Protected Functions (Automatic Token Injection)

With the token set globally, protected functions like `getMyPlan` no longer need to handle headers manually.

```js
// src/apis/apiService.js

// ... (other functions)

export const getMyPlan = async () => { // Removed 'token' argument
    try {
        // The Authorization header is injected automatically via default headers.
        const res = await apiClient.get(`/auth/my-plan`); 

        return res.data;
    } catch (error) {
        throw new Error(error.response?.data?.message || "Failed to fetch plan");
    }
};
```

## 💡 Nexli Features Summary

* 🌐 Offline Sync: Requests (except Login/Register) are stored while offline and synchronized when the connection returns, ensuring data is not lost.

* 🔄 Automatic Retries: Improves application stability by automatically retrying requests that fail due to temporary server issues (like 500 or 503 errors).

* ⚡ Clean Code: The use of default headers keeps your API service functions clean and focused on business logic.