{"id":17368,"library":"sn-http-request","title":"ServiceNow HTTP Request Client","description":"sn-http-request is a specialized JavaScript HTTP client designed specifically for interacting with ServiceNow instances. It aims to simplify common HTTP operations within the ServiceNow ecosystem by providing features such as automatic user token refresh, asynchronous request queuing, request cancellation, request/response interceptors, and efficient request batching (defaulting to batch requests within a 50ms window). The current stable version is 24.0.3, though its public release cadence might be slower as it's primarily intended for internal ServiceNow development. Its key differentiators compared to generic HTTP clients like Axios or the Fetch API include built-in XSRF token handling and request compression, making it optimized for ServiceNow's API landscape and reducing boilerplate for common tasks in that environment.","status":"active","version":"24.0.3","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","react","angular","adapter","component","wrapper"],"install":[{"cmd":"npm install sn-http-request","lang":"bash","label":"npm"},{"cmd":"yarn add sn-http-request","lang":"bash","label":"yarn"},{"cmd":"pnpm add sn-http-request","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for Gzip compression of request payloads when `httpRequestCompressionThreshold` is set.","package":"fflate","optional":false}],"imports":[{"note":"The library primarily uses named exports and a factory pattern for client instantiation. ESM is the preferred import style.","wrong":"const snHttpFactory = require('sn-http-request').snHttpFactory;","symbol":"snHttpFactory","correct":"import { snHttpFactory } from 'sn-http-request';"},{"note":"For CommonJS environments, destructuring the `require` call is the correct way to access the named export `snHttpFactory`.","wrong":"const snHttpFactory = require('sn-http-request'); // Would import the entire module, not the factory function directly","symbol":"snHttpFactory (CJS)","correct":"const { snHttpFactory } = require('sn-http-request');"},{"note":"When using TypeScript, import `SnHttpClientInstance` as a type for explicit client type declarations.","symbol":"SnHttpClientInstance","correct":"import type { SnHttpClientInstance } from 'sn-http-request';"}],"quickstart":{"code":"import { snHttpFactory } from 'sn-http-request';\n\nconst SN_INSTANCE_URL = process.env.SN_INSTANCE_URL ?? 'https://yourinstance.service-now.com';\nconst SN_USERNAME = process.env.SN_USERNAME ?? 'admin';\nconst SN_PASSWORD = process.env.SN_PASSWORD ?? 'password';\n\nconst snHttp = snHttpFactory({\n  baseURL: SN_INSTANCE_URL + '/api/now/table/',\n  auth: {\n    username: SN_USERNAME,\n    password: SN_PASSWORD,\n  },\n  // Max 2 concurrent requests by default, set to 5 for demonstration\n  maxConcurrent: 5,\n  // Disable batching for this client instance for immediate requests\n  batching: false,\n  // Example interceptor to log requests\n  interceptors: {\n    request: [\n      (config) => {\n        console.log(`[Request Interceptor] Making ${config.method?.toUpperCase()} request to ${config.url}`);\n        return config;\n      },\n    ],\n    response: [\n      (response) => {\n        console.log(`[Response Interceptor] Received ${response.status} from ${response.config.url}`);\n        return response;\n      },\n    ],\n  },\n});\n\nasync function fetchIncident(sysId: string) {\n  try {\n    console.log(`\nFetching incident with sys_id: ${sysId}...`);\n    const response = await snHttp.get(`incident/${sysId}`);\n    console.log('Incident Data:', JSON.stringify(response.data, null, 2));\n  } catch (error: any) {\n    console.error('Error fetching incident:', error.message || error);\n    if (error.response) {\n      console.error('Response status:', error.response.status);\n      console.error('Response data:', error.response.data);\n    }\n  }\n}\n\n// Example: Replace with a valid incident sys_id from your ServiceNow instance\nfetchIncident('a_valid_incident_sys_id_here');\n\n// Example: Creating a new incident (requires POST permissions and appropriate payload)\nasync function createIncident() {\n  try {\n    console.log('\\nCreating a new incident...');\n    const newIncidentData = {\n      short_description: 'Test incident from sn-http-request client',\n      impact: '3',\n      urgency: '3',\n    };\n    const response = await snHttp.post('incident', { data: newIncidentData });\n    console.log('New Incident Created:', JSON.stringify(response.data, null, 2));\n  } catch (error: any) {\n    console.error('Error creating incident:', error.message || error);\n    if (error.response) {\n      console.error('Response status:', error.response.status);\n      console.error('Response data:', error.response.data);\n    }\n  }\n}\n\n// Uncomment to run the create incident example\n// createIncident();","lang":"typescript","description":"This quickstart demonstrates how to create an `sn-http-request` client instance, configure it with base URL, authentication, and interceptors, and then perform a GET request to fetch a ServiceNow incident. It also includes an example for creating a new incident via a POST request."},"warnings":[{"fix":"Review the npm page and GitHub repository regularly for updates and consider this context when planning long-term dependencies. For general JavaScript HTTP needs outside of a ServiceNow context, alternatives like Axios or the native Fetch API might be more suitable.","message":"The `sn-http-request` library is primarily intended for internal ServiceNow development use. While publicly available, its release cadence and feature prioritization may differ from general-purpose HTTP clients, potentially leading to slower updates or fixes for external use cases.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always consult ServiceNow API documentation for the specific API version you are targeting. Implement robust error handling and defensive programming (e.g., checking for property existence before access) to gracefully handle unexpected API changes. Keep `sn-http-request` updated to leverage any compatibility fixes.","message":"As with any API client, changes to the underlying ServiceNow REST API (e.g., changes to endpoint paths, required parameters, response field names, or authentication methods) can cause breaking changes to applications using `sn-http-request`.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"To disable batching for a client instance, set `batching: false` in the `snHttpFactory` options. For individual requests, set `batch: false` within the request config (e.g., `snHttp.post('/users/1', { data: {fName: 'Fred'}, batch: false });`).","message":"By default, `sn-http-request` clients will batch HTTP requests made within a 50ms window. While beneficial for performance in some scenarios, this can lead to unexpected delays or behavior if immediate, unbatched requests are expected.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Increase the `timeout` setting in your request configuration or `snHttpFactory` options. Verify network connectivity to the ServiceNow instance and check the instance's availability. Ensure the target API endpoint is correct and accessible. For server-side issues, check ServiceNow instance logs.","cause":"This error often indicates a timeout before the server sends a response, or an issue connecting to the remote service.","error":"Error sending HTTP request"},{"fix":"Verify that the `username` and `password` provided to `snHttpFactory` are correct for your ServiceNow instance and have the 'itil' role or other required permissions for the target API. Ensure any `xsrfToken` is correctly configured and still valid. Review ServiceNow security rules and API access policies.","cause":"This specific error message (or similar 'unauthorized' errors like 401 or 403 Forbidden) typically means the provided credentials or authentication token are invalid or lack the necessary permissions for the requested operation.","error":"The HTTP request is unauthorized with client authentication scheme 'Digest'."},{"fix":"Double-check the `baseURL` configured in `snHttpFactory` and the relative paths provided to `get`, `post`, etc. Ensure the ServiceNow API endpoint exists and is correctly spelled. Verify that the user account has access to the table or API being queried.","cause":"The requested API endpoint or resource could not be found on the ServiceNow instance.","error":"HTTP status code 404: Not Found"}],"ecosystem":"npm","meta_description":null}