Planck HTTP Fetch
Planck HTTP Fetch (current version 1.7.4) is a lightweight, promise-based library for making HTTP and HTTPS requests within Node.js environments. It offers a fluent, chainable API that simplifies the configuration of requests, allowing developers to easily set parameters such as timeouts, custom headers, and basic authentication details. A notable feature is its automatic handling of HTTP 307 temporary redirects, which was introduced in version 1.7.2, enhancing its robustness for web interactions. The library implicitly determines the HTTP method (GET or POST) based on the presence of a request body, streamlining its usage for common data exchange patterns. It ships with comprehensive TypeScript type definitions, providing strong type checking and IDE support. While a specific release cadence isn't detailed, the package appears to be actively maintained, focusing on a straightforward and developer-friendly approach to network requests, differentiating itself through its minimalist API and direct control over core fetch functionalities.
Common errors
-
TypeError: Fetch is not a constructor
cause Attempting to use CommonJS `require` syntax or incorrect destructuring with an ES Module package. This library exports named `Fetch`.fixEnsure your project is configured for ES Modules (e.g., `"type": "module"` in `package.json`) and use `import { Fetch } from 'planck-http-fetch';`. If you must use CommonJS, consider using dynamic import `import('planck-http-fetch').then(m => new m.Fetch())` (requires Node.js >=13). -
Error: connect ETIMEDOUT
cause The HTTP request could not establish a connection within the specified timeout duration, or the remote server is unreachable/unresponsive.fixIncrease the timeout duration using `.timeout(milliseconds)` in your chain (e.g., `.timeout(15000)` for 15 seconds). Verify the target URL is correct, the server is running, and there are no network issues (e.g., firewall, proxy, DNS resolution) blocking the connection from your environment.
Warnings
- gotcha When sending data, if no `contentType` is explicitly provided to the `.fetch()` method, it defaults to `application/json;charset=utf-8`. This might lead to unexpected server responses if your API expects a different default.
- gotcha The `.unauthorized()` method disables SSL certificate validation for HTTPS requests. While this can be useful for testing against self-signed certificates or specific proxy setups, using it in production with untrusted endpoints exposes your application to Man-in-the-Middle attacks and is a significant security risk.
- gotcha The HTTP method (GET or POST) is implicitly determined by the presence of the `data` argument in the `.fetch(data, contentType)` call. If `data` is provided, the request will be POST; otherwise, it will be GET. This implicit behavior can sometimes lead to confusion or unintended request types.
Install
-
npm install planck-http-fetch -
yarn add planck-http-fetch -
pnpm add planck-http-fetch
Imports
- Fetch
const { Fetch } = require('planck-http-fetch');import { Fetch } from 'planck-http-fetch';
Quickstart
import { Fetch } from "planck-http-fetch";
async function makeRequest() {
// Using process.env for sensitive data in a real application
const apiKey = process.env.API_KEY ?? 'your-default-api-key'; // Replace with a real API key or secure retrieval method
const username = process.env.BASIC_AUTH_USER ?? 'testuser';
const password = process.env.BASIC_AUTH_PASS ?? 'testpass';
const targetUrl = "https://jsonplaceholder.typicode.com/posts"; // Using a public API for demonstration
try {
console.log("Making a POST request...");
// Example POST request with JSON data
const postData = {
title: 'foo',
body: 'bar',
userId: 1,
};
const postResponse = await new Fetch(targetUrl)
.timeout(8000) // Set an 8-second timeout for the request
.head("Authorization", `Bearer ${apiKey}`) // Example of setting an Authorization header
.head("X-Custom-App", "PlanckExample")
.fetch(JSON.stringify(postData), "application/json");
console.log("POST Response Status:", postResponse.status);
console.log("POST Response Body (first 100 chars):");
console.log(postResponse.data.toString().substring(0, 100));
console.log("\nMaking a GET request...");
// Example GET request (no data provided to .fetch(), so it defaults to GET)
const getResponse = await new Fetch(`${targetUrl}/1`)
.basicAuth(username, password) // Apply basic authentication
.fetch();
console.log("GET Response Status:", getResponse.status);
console.log("GET Response Body (first 100 chars):");
console.log(getResponse.data.toString().substring(0, 100));
// Example of skipping SSL cert check (CAUTION: generally not recommended for production)
// const insecureResponse = await new Fetch("https://self-signed.example.com")
// .unauthorized() // Skips certificate validation
// .fetch();
// console.log("Insecure Fetch Response:", insecureResponse.data.toString());
} catch (error) {
console.error("An error occurred during fetch:", error instanceof Error ? error.message : String(error));
}
}
makeRequest();