You're absolutely right — Node.js v18+ includes a stable global fetch API (based on the undici implementation), and for many use cases, it's a great alternative to external libraries like axios. Using native fetch can reduce dependencies, improve performance, and align closer to browser-compatible APIs.
Here's how you can refactor the earlier solution to use Node.js native fetch while maintaining the same functionality and logging:
✅ Updated disable-accounts.ts with Native fetch
import { readFileSync } from 'fs';
import { join } from 'path';
import * as dotenv from 'dotenv';
// Load environment variables
dotenv.config();
// Constants
const API_BASE_URL = process.env.API_BASE_URL!;
const API_TOKEN = process.env.API_TOKEN!;
const LOG_FILE_PATH = join(__dirname, '../disable-accounts.log');
// Log helper
function log(message: string): void {
const timestamp = new Date().toISOString();
console.log(`[INFO] ${timestamp} - ${message}`);
}
function errorLog(message: string): void {
const timestamp = new Date().toISOString();
console.error(`[ERROR] ${timestamp} - ${message}`);
}
// Simulate logging to file if needed
// const fs = require('fs');
// function writeLogToFile(logMessage: string) {
// fs.appendFileSync(LOG_FILE_PATH, logMessage + '\n');
// }
async function disableAccount(accountId: string): Promise<void> {
const url = `${API_BASE_URL}/accounts/${accountId}/disable`;
const options = {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ status: 'inactive' }),
};
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const result = await response.json();
log(`Account ${accountId} disabled successfully. Response: ${JSON.stringify(result)}`);
} catch (error: any) {
errorLog(`Failed to disable account ${accountId}: ${error.message}`);
}
}
async function main() {
try {
// Read account IDs from file
const data = readFileSync(join(__dirname, '../accounts.txt'), 'utf-8');
const accountIds = data.split('\n').map(id => id.trim()).filter(Boolean);
log(`Found ${accountIds.length} accounts to process`);
// Sequential processing with delay to avoid rate limiting
for (const accountId of accountIds) {
await disableAccount(accountId);
await new Promise(resolve => setTimeout(resolve, 1000)); // 1s delay
}
log('Processing completed');
} catch (error: any) {
errorLog(`Critical error: ${error.message}`);
process.exit(1);
}
}
main();
📌 Key Differences Between fetch and axios
| Feature | fetch (Native) | axios |
|---|
| Built-in | ✅ Yes | ❌ Requires install |
| Error Handling | Must manually check response.ok | Automatically throws on HTTP errors |
| Response Parsing | Must manually call .json() or .text() | Auto-parses JSON |
| Interceptors | ❌ Not supported | ✅ Supported |
| AbortController | ✅ Supported | ✅ Supported |
| Middleware | ❌ No built-in support | ✅ Interceptors allow middleware |
| Performance | ⚡ Faster startup (uses undici) | Slightly slower startup |
| Body Serialization | Must JSON.stringify() manually | Auto-serializes request body |
✅ Why Use Native fetch?
- No external dependency (no need to install
axios)
- Faster cold start (especially in serverless environments)
- Consistent browser/Node.js API
- Better memory efficiency in large-scale applications
- Undici-based for better performance and reliability
⚠️ Caveats
- You must manually check
response.ok and parse the response body (json(), text(), etc.).
- No built-in interceptors or middleware, so common logic like logging or retry policies must be implemented manually.
- No automatic request body serialization — you must use
JSON.stringify().
🛠 Optional Enhancements
If you want more advanced features like retry logic or logging interceptors, consider wrapping fetch in a utility:
async function fetchWithRetry(url: string, options: RequestInit, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok && response.status >= 500) {
throw new Error(`Server error: ${response.status}`);
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
🧪 Running the Script
As before, execute with:
npx tsx src/disable-accounts.ts
✅ Summary
Using Node.js native fetch is a clean, modern, and dependency-free way to make HTTP requests. It's especially suitable for simple use cases like disabling accounts via an API. For more complex scenarios (e.g., interceptors, retry logic), axios or a custom wrapper around fetch might be better.
Let me know if you'd like to see a version with enhanced logging to a file, batch processing, or parallel execution!