Axly is a powerful and flexible HTTP client library built on top of Axios. It provides a streamlined interface for making API requests with additional features like:
- Dynamic request configurations
- Request cancellation using
AbortController
- Retry logic
- Progress tracking for uploads and downloads
- Easy integration with React, Next.js, and Node.js applications
- Full TypeScript support with detailed typings and JSDoc comments
Install Axly using npm or bun:
npm install axly
or
bun add axly
- Dynamic Request Options: Customize each request with flexible configurations.
- Request Cancellation with AbortController: Cancel requests to prevent race conditions or unnecessary network calls.
- Retry Logic: Automatically retry failed requests with configurable attempts.
- Progress Tracking: Monitor upload and download progress for files and data streams.
- Interceptors: Globally handle request and response transformations and errors.
- TypeScript Support: Fully typed with detailed JSDoc comments for an enhanced developer experience.
- React.js, Node.js, and Next.js Ready: Designed for seamless integration with modern frameworks.
Start by configuring Axly with your base URL and other settings:
import { setAxiosConfig } from 'axly';
setAxiosConfig({
baseURL: 'https://api.example.com',
token: 'user-jwt-auth-token',
defaultHeaders: {
'Custom-Header': 'value'
},
interceptors: {
request: (config) => {
// Modify request config if needed
return config;
},
response: (response) => {
// Handle response data if needed
return response;
},
requestError: (error) => {
// Handle request error
return Promise.reject(error);
},
responseError: (error) => {
// Handle response error
return Promise.reject(error);
}
}
});
Then make a request:
import { makeRequest } from 'axly';
const fetchData = async () => {
try {
const response = await makeRequest({
method: 'GET',
url: '/api/data'
});
console.log(response.data);
} catch (error) {
console.error('Request failed:', error);
}
};
Use the useAxios
hook to manage state and requests in React components:
import React, { useEffect } from 'react';
import { useAxios } from 'axly';
const App = () => {
const { makeRequest, isLoading, uploadProgress, downloadProgress } =
useAxios();
useEffect(() => {
const fetchData = async () => {
try {
const response = await makeRequest({
method: 'GET',
url: '/todos/1'
});
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, [makeRequest]);
return (
<div>
{isLoading ?
<p>Loading...</p>
: <p>Data loaded!</p>}
<p>Upload Progress: {uploadProgress}%</p>
<p>Download Progress: {downloadProgress}%</p>
</div>
);
};
export default App;
Axly can be used in Node.js for server-side requests:
import { makeRequest, setAxiosConfig } from 'axly';
setAxiosConfig({
baseURL: 'https://api.example.com'
});
const fetchData = async () => {
try {
const response = await makeRequest({
method: 'GET',
url: '/data'
});
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
Configures global settings for Axly.
Parameters:
-
config
(Partial<AxiosConfigOptions>): Configuration options to set or update.
Example:
setAxiosConfig({
baseURL: 'https://api.example.com',
token: 'your-auth-token',
REQUEST_HEADER_AUTH_KEY: 'Authorization',
TOKEN_TYPE: 'Bearer ',
defaultHeaders: {
'Custom-Header': 'value'
},
interceptors: {
request: (config) => {
console.log('Request sent:', config);
return config;
},
response: (response) => {
console.log('Response received:', response);
return response;
},
requestError: (error) => {
console.error('Request error:', error);
return Promise.reject(error);
},
responseError: (error) => {
console.error('Response error:', error);
return Promise.reject(error);
}
}
});
Make HTTP requests with dynamic configurations.
Type Parameters:
-
T
– The expected response data type.
Parameters:
-
options
(RequestOptions
) – Configuration options for the request.
Returns:
Promise<AxiosResponse<ApiResponse<T>>>
Example:
const response = await makeRequest({
method: 'GET',
url: '/users',
params: { page: 1 }
});
A React hook that provides an interface to make HTTP requests and track their state.
Returns:
-
makeRequest
: Function to make requests. -
isLoading
: Boolean indicating loading state. -
uploadProgress
: Upload progress percentage. -
downloadProgress
: Download progress percentage.
Example:
const { makeRequest, isLoading, uploadProgress, downloadProgress } = useAxios();
const response = await makeRequest({
method: 'GET',
url: '/users',
params: { page: 1 }
});
console.log(response.data);
const response = await makeRequest({
method: 'POST',
url: '/users',
data: {
name: 'John Doe',
email: 'john@example.com'
},
contentType: 'application/json'
});
console.log(response.data);
const { makeRequest, uploadProgress } = useAxios();
const handleFileUpload = async (file) => {
const formData = new FormData();
formData.append('file', file);
await makeRequest({
method: 'POST',
url: '/upload',
data: formData,
contentType: 'multipart/form-data',
onUploadProgress: (progress) => {
console.log(`Upload Progress: ${progress}%`);
}
});
};
You can cancel a request using the cancelable
option and an AbortController
.
const controller = new AbortController();
const fetchData = async () => {
try {
const response = await makeRequest({
method: 'GET',
url: '/slow-endpoint',
cancelable: true,
signal: controller.signal, // Pass the signal to the request
onCancel: () => {
console.log('Request was canceled');
}
});
console.log(response.data);
} catch (error) {
if (error.name === 'CanceledError') {
console.log('Request canceled:', error.message);
} else {
console.error('Error fetching data:', error);
}
}
};
// To cancel the request
controller.abort();
setAxiosConfig({
interceptors: {
request: (config) => {
// Modify request config if needed
console.log('Request sent:', config);
return config;
},
response: (response) => {
// Handle response data if needed
console.log('Response received:', response);
return response;
},
requestError: (error) => {
// Handle request error
console.error('Request error:', error);
return Promise.reject(error);
},
responseError: (error) => {
// Handle response error
console.error('Response error:', error);
return Promise.reject(error);
}
}
});
Contributions are welcome! Please follow these steps:
- Fork the repository.
- Create a new branch (
git checkout -b feature/your-feature
). - Commit your changes (
git commit -am 'Add new feature'
). - Push to the branch (
git push origin feature/your-feature
). - Open a Pull Request.
This project is licensed under the MIT License. See the LICENSE file for details.
Made with ❤️ by Harshal Katakiya. Feel free to reach out if you have any questions or need support!