Synchronous Fetch API for Node.js and Browser

0.6.0 · active · verified Tue Apr 21

sync-fetch is a JavaScript library that provides a synchronous wrapper around the standard Fetch API, enabling blocking network requests in environments where asynchronicity is not desired or feasible. Currently at version 0.6.0, it sees intermittent updates, with the last publish approximately four months ago, indicating an actively maintained but not rapidly evolving project. It internally leverages `node-fetch` for Node.js environments and `XMLHttpRequest` for browser contexts, adapting the underlying mechanism to provide a unified synchronous interface. Its primary differentiation is the synchronous execution, which, while useful for niche scenarios such as initial configuration loading or specific command-line utilities in Node.js, or within Web Workers in browsers to avoid blocking the main thread, generally carries significant performance and responsiveness implications due to its blocking nature. It is crucial to understand that using `sync-fetch` on the main thread of a browser or within the Node.js event loop will halt all other operations until the network request completes, making it generally unsuitable for interactive applications. The library explicitly outlines several limitations, particularly regarding body types like `Stream` or `Blob` and some advanced `fetch` options, which are inherent to synchronous request models.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic synchronous GET request and synchronously parses a JSON response, followed by a text response and an example using an environment variable for authentication.

const fetch = require('sync-fetch');

const metadata = fetch('https://doi.org/10.7717/peerj-cs.214', {
  headers: {
    Accept: 'application/vnd.citationstyles.csl+json'
  }
}).json();

console.log('DOI Metadata:', metadata);

// Example of synchronous text response
const textResponse = fetch('https://httpbin.org/get').text();
console.log('Plain Text Response (first 100 chars):', textResponse.substring(0, 100) + '...');

// Example with environment variable for API key (placeholder)
const apiKey = process.env.SOME_API_KEY ?? 'your_default_key';
// In a real scenario, avoid embedding keys directly. This is for demonstration.
const secureResponse = fetch(`https://api.example.com/data?key=${apiKey}`).json();
console.log('Secure Data (first 50 chars):', JSON.stringify(secureResponse).substring(0, 50) + '...');

view raw JSON →