@dephub/http
v1.0.1
Published
Enhanced HTTP client with timeout, delay, and Next.js support for Node.js and browsers
Downloads
10
Maintainers
Readme
@dephub/http 🌐
Enhanced HTTP client with timeout, delay, and Next.js support for Node.js and browsers. Perfect for API requests and web scraping.
Features ✨
- ⚡ Enhanced Fetch - Timeout, delay, and retry support
- 🔒 Type Safe - Full TypeScript support with autocomplete
- 🎯 Next.js Ready - Built-in support for Next.js caching and revalidation
- 📡 HTTP Methods - Convenience methods for GET, POST, PUT, DELETE, PATCH
- 🖥️ CLI Interface - Make HTTP requests directly from terminal
- 🌐 Universal - Works in Node.js, browsers, and edge environments
- ⚙️ Configurable - Custom headers, timeouts, and request options
Installation 📦
npm install @dephub/http
# or
pnpm add @dephub/http
# or
yarn add @dephub/httpQuick Start 🚀
Programmatic Usage
import { get, post, http } from '@dephub/http';
// Simple GET request
const response = await get('https://api.example.com/data');
const data = await response.json();
// POST with JSON body and timeout
const result = await post('https://api.example.com/users', {
timeout: 5000,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', email: '[email protected]' }),
});
// Generic HTTP request with custom options
const response = await http('https://api.example.com/upload', {
method: 'PUT',
headers: { Authorization: 'Bearer token' },
next: { revalidate: 300 }, // Next.js caching
});CLI Usage
# GET request
npx @dephub/http get https://api.example.com/data
# POST with JSON body
npx @dephub/http post https://api.example.com/users \
--body '{"name": "John", "email": "[email protected]"}'
# GET with headers and save to file
npx @dephub/http get https://api.example.com/data \
--headers '{"Authorization": "Bearer token"}' \
--output response.jsonAPI Reference 📚
Core Functions
http(url, options)
Main HTTP client function with enhanced options.
Parameters:
url(string | URL) - Request URLoptions(HttpOptions) - Request configurationmethod- HTTP method (default: 'GET')timeout- Request timeout in ms (default: 0 = no timeout)delay- Delay before request in ms (default: 0)headers- Request headers objectnext- Next.js caching optionsbody- Request body
Returns: Promise<Response>
Convenience Methods
get(url, options)- HTTP GET requestpost(url, options)- HTTP POST requestput(url, options)- HTTP PUT requestdel(url, options)- HTTP DELETE requestpatch(url, options)- HTTP PATCH request
CLI Commands
http get <url>
Perform HTTP GET request.
Options:
--headers- Request headers as JSON string--timeout- Request timeout in milliseconds--output- Save response to file
http post <url>
Perform HTTP POST request.
Options:
--headers- Request headers as JSON string--body- Request body data--timeout- Request timeout in milliseconds
http request <method> <url>
Perform HTTP request with custom method.
Options:
--headers- Request headers as JSON string--body- Request body data--timeout- Request timeout in milliseconds
Usage Examples 🎯
Basic API Requests
import { get, post } from '@dephub/http';
// Fetch JSON data
const todos = await get('https://jsonplaceholder.typicode.com/todos');
const data = await todos.json();
// Create resource
const newUser = await post('https://api.example.com/users', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Alice',
email: '[email protected]',
}),
});Advanced Configuration
import { http } from '@dephub/http';
// Request with timeout and delay
const response = await http('https://slow-api.example.com/data', {
timeout: 10000, // 10 second timeout
delay: 1000, // 1 second delay before request
headers: {
'User-Agent': 'MyApp/1.0',
Authorization: 'Bearer secret-token',
},
});
// Next.js specific (for API routes)
const cachedData = await http('/api/expensive-operation', {
next: {
revalidate: 3600, // Revalidate every hour
tags: ['expensive-data'],
},
});Error Handling
import { get } from '@dephub/http';
import { error } from '@dephub/log';
try {
const response = await get('https://api.example.com/data', {
timeout: 5000,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
console.log('Data:', data);
} catch (err) {
error('Request failed:', err.message);
}CLI Examples
# Simple GET request
npx @dephub/http get https://jsonplaceholder.typicode.com/todos/1
# POST with JSON body
npx @dephub/http post https://jsonplaceholder.typicode.com/posts \
--body '{"title": "Hello", "body": "World", "userId": 1}'
# GET with authentication
npx @dephub/http get https://api.github.com/user \
--headers '{"Authorization": "token YOUR_GITHUB_TOKEN"}'
# Save API response to file
npx @dephub/http get https://api.example.com/data --output data.json
# Custom request with timeout
npx @dephub/http request PUT https://api.example.com/resources/123 \
--body '{"status": "updated"}' \
--timeout 10000Common Patterns 🎨
API Client Wrapper
import { get, post, put, del } from '@dephub/http';
class ApiClient {
private baseURL: string;
private token: string;
constructor(baseURL: string, token: string) {
this.baseURL = baseURL;
this.token = token;
}
private getHeaders() {
return {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
};
}
async getUser(id: string) {
return get(`${this.baseURL}/users/${id}`, {
headers: this.getHeaders(),
});
}
async createUser(userData: any) {
return post(`${this.baseURL}/users`, {
headers: this.getHeaders(),
body: JSON.stringify(userData),
});
}
}
// Usage
const api = new ApiClient('https://api.example.com', 'secret-token');
const user = await api.getUser('123');Request with Retry Logic
import { http } from '@dephub/http';
async function fetchWithRetry(url: string, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await http(url, {
timeout: 5000,
delay: attempt * 1000, // Exponential backoff
});
} catch (err) {
if (attempt === maxRetries) throw err;
console.log(`Attempt ${attempt} failed, retrying...`);
}
}
}
const response = await fetchWithRetry('https://api.example.com/data');Batch Requests with Throttling
import { get } from '@dephub/http';
async function fetchMultipleUrls(urls: string[]) {
const results = [];
for (const url of urls) {
const response = await get(url, {
delay: 200, // 200ms between requests
});
results.push(await response.json());
}
return results;
}
const urls = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3',
];
const data = await fetchMultipleUrls(urls);CLI Reference 🖥️
Global Installation
# Install globally
npm install -g @dephub/http
# Then use anywhere
http get https://api.example.com/data
http post https://api.example.com/users --body '{"name": "John"}'Command Overview
# Show help
http --help
# Show command-specific help
http get --help
http post --help
http request --help
# Version info
http --versionPiping and Redirection
# Pipe to jq for JSON processing
http get https://api.example.com/data | jq '.results'
# Save response to file
http get https://api.example.com/data > output.json
# Use in scripts
RESPONSE=$(http get https://api.example.com/data)License 📄
MIT License – see LICENSE for details.
Author: Estarlin R (estarlincito.com)
