{"id":16234,"library":"sync-fetch","title":"Synchronous Fetch API for Node.js and Browser","description":"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.","status":"active","version":"0.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/larsgw/sync-fetch","tags":["javascript","fetch","sync"],"install":[{"cmd":"npm install sync-fetch","lang":"bash","label":"npm"},{"cmd":"yarn add sync-fetch","lang":"bash","label":"yarn"},{"cmd":"pnpm add sync-fetch","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used internally as the underlying Fetch API implementation for Node.js environments.","package":"node-fetch","optional":false}],"imports":[{"note":"For Node.js, this package primarily offers a CommonJS `require` interface as shown in its documentation. Direct ESM `import` may not work without a bundler or specific Node.js configuration, as `node-fetch` v3 (its dependency) is ESM-only.","wrong":"import fetch from 'sync-fetch'","symbol":"fetch","correct":"const fetch = require('sync-fetch')"},{"note":"In browser environments, `sync-fetch` is typically loaded via a CDN, making the `fetch` function globally accessible. Be aware of CORS and other browser limitations for synchronous XHR.","symbol":"fetch (global)","correct":"<script src=\"https://unpkg.com/sync-fetch\"></script>\n// 'fetch' is now globally available"},{"note":"All `SyncResponse` methods (e.g., `.json()`, `.text()`, `.buffer()`, `.blob()`, `.arrayBuffer()`) return values synchronously, unlike the asynchronous `Promise`-returning methods of the standard Fetch API.","wrong":"const response = await fetch('http://example.com');\nconst data = await response.json();","symbol":"SyncResponse methods","correct":"const response = fetch('http://example.com');\nconst data = response.json(); // or .text(), .buffer(), etc."}],"quickstart":{"code":"const fetch = require('sync-fetch');\n\nconst metadata = fetch('https://doi.org/10.7717/peerj-cs.214', {\n  headers: {\n    Accept: 'application/vnd.citationstyles.csl+json'\n  }\n}).json();\n\nconsole.log('DOI Metadata:', metadata);\n\n// Example of synchronous text response\nconst textResponse = fetch('https://httpbin.org/get').text();\nconsole.log('Plain Text Response (first 100 chars):', textResponse.substring(0, 100) + '...');\n\n// Example with environment variable for API key (placeholder)\nconst apiKey = process.env.SOME_API_KEY ?? 'your_default_key';\n// In a real scenario, avoid embedding keys directly. This is for demonstration.\nconst secureResponse = fetch(`https://api.example.com/data?key=${apiKey}`).json();\nconsole.log('Secure Data (first 50 chars):', JSON.stringify(secureResponse).substring(0, 50) + '...');","lang":"javascript","description":"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."},"warnings":[{"fix":"For browser applications, use standard, asynchronous `fetch` or ensure `sync-fetch` is only used within a Web Worker. For Node.js, prefer asynchronous I/O with `node-fetch` or other promise-based libraries unless a blocking operation is strictly required for a specific, isolated use case (e.g., a CLI tool's initial setup).","message":"This package provides synchronous I/O. Using `sync-fetch` on the main thread of a browser will block the UI, making the page unresponsive. In Node.js, it will block the event loop, halting all other operations and significantly degrading application performance. It is generally suitable only for Web Workers or CLI tools where blocking is acceptable or desired.","severity":"breaking","affected_versions":">=0.1.0"},{"fix":"For Node.js, ensure request bodies are JSON, strings, or `Buffer` objects that can be serialized synchronously. Avoid using `Stream`, `Blob`, or `FormData` directly as body content.","message":"The Node.js implementation of `sync-fetch` has significant limitations on request body types. It does not support `Stream`, `Blob`, or `FormData` instances as input bodies because they cannot be read or serialized synchronously. Additionally, the non-spec `agent` option is not supported.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Be aware of reduced functionality in browsers. Test thoroughly for desired behavior, especially concerning CORS. For advanced `fetch` options, consider asynchronous `fetch`.","message":"When used in browser environments, `sync-fetch` relies on `XMLHttpRequest` and consequently supports only a limited set of `fetch` options (`method`, `body`, `headers`, `credentials`, `timeout`). Standard `fetch` features like `redirect`, `integrity`, or `cache` are often unavailable. CORS limitations apply and may be stricter for synchronous requests.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"If encountering `ERR_REQUIRE_ESM` when using `sync-fetch` in a CJS project, verify your Node.js version and environment. Ensure `sync-fetch`'s internal handling of `node-fetch` v3 is compatible, or consider alternative synchronous HTTP clients if issues persist.","message":"While `sync-fetch` relies on `node-fetch` internally, `node-fetch` v3 is an ESM-only module. If you are working in a CommonJS Node.js project and face issues related to `require()` of ESM modules, it might stem from `sync-fetch`'s internal dependency resolution, even though `sync-fetch` itself exposes a CommonJS `require` interface.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Convert `Stream` or `Blob` data into a synchronously readable format (e.g., `Buffer` or string) before passing it as the `body` option.","cause":"The synchronous nature of `sync-fetch` in Node.js prevents it from reading or serializing asynchronous data types like `Stream` or `Blob` for the request body.","error":"Cannot use Stream or Blob as request body"},{"fix":"For Node.js, ensure you are using `const fetch = require('sync-fetch')`. If the error persists due to internal dependencies, verify your Node.js runtime environment (>=18 is required). If you are in an ESM project, and `sync-fetch` does not provide an ESM export, you might need to use dynamic `import()` or tools that bridge CJS and ESM, though this package's core design revolves around synchronous CJS for Node.js.","cause":"This error occurs when attempting to `require()` an ECMAScript Module (ESM) in a CommonJS context. While `sync-fetch` provides a CommonJS `require` entry, its internal dependency `node-fetch` v3 is ESM-only. This error might indicate an incompatibility or misconfiguration if `sync-fetch`'s internal mechanisms fail to bridge the CJS/ESM gap correctly for its dependencies, or if you are trying to `import` `sync-fetch` directly in an ESM project where it only exposes CJS.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported"},{"fix":"Refactor your code to use the standard, asynchronous `fetch` API for browser main thread operations. If synchronous behavior is absolutely required, move the `sync-fetch` call into a Web Worker to avoid blocking the UI thread.","cause":"This is a browser console warning (or error in strict environments) indicating that you are using `sync-fetch` on the browser's main UI thread, which causes the page to become unresponsive during the network request.","error":"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience."}],"ecosystem":"npm"}