CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sync-request

Make synchronous web requests with cross-platform support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

sync-request

Synchronous HTTP request library with cross-platform support for Node.js and browsers. Provides an API similar to then-request but with synchronous execution, supporting all major HTTP methods and comprehensive request configuration options.

Package Information

  • Package Name: sync-request
  • Package Type: npm
  • Language: TypeScript/JavaScript
  • Installation: npm install sync-request

Core Imports

import request, { HttpVerb, Response, Options, FormData } from "sync-request";

For CommonJS:

const request = require("sync-request");
const { FormData } = request;

For browser usage (when built):

// Available as window.syncRequest when included via script tag
const response = syncRequest('GET', 'https://api.example.com/data');

Note: The package re-exports HttpVerb, Response, and Options types from its dependencies for TypeScript users:

// All types are available via named imports
import request, { HttpVerb, Response, Options, FormData } from "sync-request";

// Use type inference (also works)
const response = request('GET', 'https://api.example.com'); // response is automatically typed as Response

Basic Usage

const request = require("sync-request");

// Simple GET request
const response = request('GET', 'https://jsonplaceholder.typicode.com/posts/1');
console.log(response.getBody('utf8'));

// POST request with JSON data
const postResponse = request('POST', 'https://jsonplaceholder.typicode.com/posts', {
  json: { title: 'New Post', body: 'Post content', userId: 1 },
  headers: { 'Content-Type': 'application/json' }
});

// Handle response
if (postResponse.statusCode === 201) {
  console.log('Post created:', postResponse.getBody('utf8'));
}

Architecture

sync-request provides cross-platform synchronous HTTP requests through different mechanisms:

  • Node.js: Uses sync-rpc with worker processes to execute then-request asynchronously while providing a synchronous interface
  • Browser: Leverages XMLHttpRequest's synchronous mode (deprecated but supported for compatibility)
  • Common Interface: Both platforms expose identical API for consistent usage across environments

Important: This library is not recommended for production use as synchronous requests can block the event loop in Node.js and freeze browsers. Use then-request for production applications.

Capabilities

HTTP Request Function

Make synchronous HTTP requests with comprehensive options support.

/**
 * Make a synchronous HTTP request
 * @param method - HTTP method (GET, POST, PUT, DELETE, HEAD, etc.)
 * @param url - Request URL as string or URL object
 * @param options - Request configuration options
 * @returns Response object with status, headers, and body
 */
function request(method: HttpVerb, url: string | URL, options?: Options): Response;

Usage Examples:

// GET with headers
const response = request('GET', 'https://api.example.com/users', {
  headers: {
    'Authorization': 'Bearer token123',
    'User-Agent': 'MyApp/1.0'
  }
});

// POST with form data
const form = new FormData();
form.append('username', 'john_doe');
form.append('email', 'john@example.com');

const response = request('POST', 'https://api.example.com/users', {
  form: form
});

// Request with query parameters
const response = request('GET', 'https://api.example.com/search', {
  qs: { q: 'javascript', limit: 10, offset: 0 }
});

// Request with timeout and retry
const response = request('GET', 'https://api.example.com/data', {
  timeout: 5000,
  retry: true,
  maxRetries: 3,
  retryDelay: 1000
});

Form Data Handling

Custom FormData implementation for multipart/form-data requests.

/**
 * FormData class for handling multipart/form-data
 */
class FormData {
  /**
   * Append a field to the form
   * @param key - Field name
   * @param value - Field value (string, Blob, or Buffer)
   * @param fileName - Optional filename for file uploads
   */
  append(key: string, value: string | Blob | Buffer, fileName?: string): void;
}

Usage Example:

const request = require('sync-request');
const { FormData } = request;

const form = new FormData();
form.append('text_field', 'Hello World');
form.append('file', fileBuffer, 'document.pdf');

const response = request('POST', 'https://api.example.com/upload', {
  form: form
});

Types

/**
 * HTTP methods supported by sync-request (re-exported from 'then-request')
 * Standard HTTP methods as string literals
 */
type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH' | 'OPTIONS' | string;

/**
 * Request configuration options
 */
interface Options {
  /** Query string parameters as object */
  qs?: { [key: string]: any };
  /** HTTP headers */
  headers?: { [key: string]: string | string[] };
  /** Request body for POST/PUT requests */
  body?: string | Buffer;
  /** JSON data - automatically stringified and sets Content-Type */
  json?: any;
  /** FormData for multipart/form-data requests */
  form?: FormData;
  /** Enable file caching (Node.js only) */
  cache?: 'file';
  /** Follow HTTP redirects (default: true) */
  followRedirects?: boolean;
  /** Maximum number of redirects (default: Infinity) */
  maxRedirects?: number;
  /** Headers allowed during redirects */
  allowRedirectHeaders?: string[];
  /** Enable gzip compression (default: true) */
  gzip?: boolean;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** Socket timeout in milliseconds (Node.js only) */
  socketTimeout?: number;
  /** Retry failed requests */
  retry?: boolean;
  /** Delay between retries in milliseconds (default: 200) */
  retryDelay?: number;
  /** Maximum number of retries (default: 5) */
  maxRetries?: number;
  /** Custom agent configuration */
  agent?: boolean;
}

/**
 * HTTP response object (re-exported from 'then-request' via 'http-response-object')
 * The actual Response implementation provides these key properties and methods
 */
interface Response {
  /** HTTP status code */
  statusCode: number;
  /** Response headers */
  headers: { [key: string]: string | string[] };
  /** Response body (string in browser, Buffer in Node.js) */
  body: string | Buffer;
  /** Final URL after redirects */
  url: string;
  
  /**
   * Get response body with optional encoding
   * Throws error if status code >= 300
   * @param encoding - Text encoding (e.g., 'utf8')
   * @returns Response body as string or Buffer
   */
  getBody(encoding?: string): string | Buffer;
}

Error Handling

sync-request handles errors in several ways:

HTTP Error Status Codes

The getBody() method throws an error for HTTP status codes >= 300:

try {
  const response = request('GET', 'https://api.example.com/not-found');
  const body = response.getBody('utf8'); // Throws error for 404
} catch (error) {
  console.error('HTTP Error:', error.statusCode, error.message);
  console.error('Response body:', error.body.toString());
}

Network and Request Errors

Network failures, timeouts, and other request errors are thrown as exceptions:

try {
  const response = request('GET', 'https://invalid-domain.example', {
    timeout: 1000
  });
} catch (error) {
  console.error('Request failed:', error.message);
}

Checking Status Without Throwing

To handle status codes manually without exceptions:

const response = request('GET', 'https://api.example.com/data');

if (response.statusCode >= 200 && response.statusCode < 300) {
  // Success
  const data = response.getBody('utf8');
} else if (response.statusCode === 404) {
  // Handle not found
  console.log('Resource not found');
} else {
  // Handle other errors
  console.error('HTTP Error:', response.statusCode);
}

Platform-Specific Behavior

Node.js Environment

  • Uses worker processes via sync-rpc for true synchronous behavior
  • Supports all request options including socketTimeout, cache, and agent
  • Requires nc (netcat) utility for optimal performance; falls back to slower method if unavailable
  • Response body is a Buffer by default

Browser Environment

  • Uses synchronous XMLHttpRequest (not recommended for production)
  • Some options like socketTimeout, cache, and agent are ignored
  • Response body is always a string
  • Cross-domain requests follow browser CORS policies

Common Limitations

  • Performance Impact: Blocks the event loop/main thread during request execution
  • Scalability Issues: Cannot handle concurrent requests efficiently
  • Browser Compatibility: Synchronous XHR is deprecated and may cause browser freezing
  • Production Warning: Not suitable for production applications - use then-request instead
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sync-request@6.1.x
Publish Source
CLI
Badge
tessl/npm-sync-request badge