{"id":16103,"library":"light-my-request","title":"Light my Request","description":"light-my-request is a utility library designed to simulate HTTP requests against Node.js HTTP servers without requiring the server to be bound to a network port or even in a listening state. This makes it an ideal tool for writing fast, isolated tests for server logic, as well as for debugging server-side applications. The current stable version is 6.6.0. The project maintains a consistent release cadence, frequently delivering minor versions and patch updates to address features, bug fixes, and performance improvements, as evidenced by the regular 6.x releases. A core differentiator of this library is its ability to interact directly with an `http.createServer` dispatch function, effectively injecting fake request and response objects without relying on actual socket connections. It provides flexibility by supporting both traditional callback-based request handling and modern Promise-based (async/await) patterns, alongside a fluent, chainable API for constructing complex requests.","status":"active","version":"6.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/fastify/light-my-request","tags":["javascript","http","inject","fake","request","server","typescript"],"install":[{"cmd":"npm install light-my-request","lang":"bash","label":"npm"},{"cmd":"yarn add light-my-request","lang":"bash","label":"yarn"},{"cmd":"pnpm add light-my-request","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for simulating multipart/form-data or x-www-form-urlencoded payloads, such as file uploads.","package":"form-auto-content","optional":true}],"imports":[{"note":"The primary function to initiate a fake HTTP request. While CJS environments can `require('light-my-request')` directly to get the `inject` function, ESM environments must use named imports.","wrong":"const inject = require('light-my-request').inject","symbol":"inject","correct":"import { inject } from 'light-my-request'"},{"note":"This is a TypeScript type definition for the function that handles incoming requests, typically passed to `http.createServer`. It should be imported as a type.","wrong":"import { DispatchFunc } from 'light-my-request'","symbol":"DispatchFunc","correct":"import type { DispatchFunc } from 'light-my-request'"},{"note":"Allows importing all named exports from the module into a single namespace object, useful for TypeScript or when accessing multiple utilities from the library.","wrong":null,"symbol":"* as LightMyRequest","correct":"import * as LightMyRequest from 'light-my-request'"}],"quickstart":{"code":"import { inject } from 'light-my-request';\nimport http from 'node:http';\n\nconst dispatch = function (req, res) {\n  let body = '';\n  req.on('data', chunk => { body += chunk; });\n  req.on('end', () => {\n    if (req.method === 'POST' && req.url === '/echo') {\n      res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': body.length });\n      res.end(body);\n    } else if (req.url === '/') {\n      const reply = 'Hello World';\n      res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length });\n      res.end(reply);\n    } else {\n      res.writeHead(404); \n      res.end('Not Found');\n    }\n  });\n};\n\nasync function runInjection() {\n  try {\n    const getResponse = await inject(dispatch).get('/').end();\n    console.log('GET /:', getResponse.payload); // Expected: Hello World\n\n    const postResponse = await inject(dispatch)\n      .post('/echo')\n      .payload('This is a test POST body')\n      .end();\n    console.log('POST /echo:', postResponse.payload); // Expected: This is a test POST body\n\n  } catch (err) {\n    console.error('Injection failed:', err);\n  }\n}\n\nrunInjection();","lang":"typescript","description":"Demonstrates basic GET and POST request injection using the async/await and chained API, showing how to interact with a standard Node.js HTTP dispatch function."},"warnings":[{"fix":"Ensure your server logic under test is designed to be independent of network specifics or provide mocks for network-dependent features if necessary.","message":"light-my-request operates by directly invoking an HTTP dispatch function, not by making actual network requests. This means your Node.js HTTP server does not need to be running or listening on a port for `inject` to work. Code paths that rely on a live network socket (e.g., `server.address()`, `socket.remoteAddress`) will not function as they would in a real HTTP context.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `import { inject } from 'light-my-request'` instead of `const inject = require('light-my-request')` in ESM files. For TypeScript, ensure your `tsconfig.json` correctly configures `moduleResolution`.","message":"When using `light-my-request` in an ESM (ECMAScript Module) context, you must use named imports for functions like `inject`. Direct default `require()` patterns from CommonJS are not compatible and will result in runtime errors.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Migrate from `inject(dispatch, options, (err, res) => { ... })` to `inject(dispatch, options).then(res => { ... }).catch(err => { ... })` or `try { const res = await inject(dispatch, options); } catch (err) { ... }`.","message":"While callback-based APIs are still supported, the library's examples and modern usage strongly encourage the adoption of Promise-based or async/await syntax for better asynchronous control flow and error handling. Callbacks may be de-emphasized in future major versions.","severity":"deprecated","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"In an ESM file (`.mjs` or `type: 'module'` in `package.json`), use `import { inject } from 'light-my-request';`. If using TypeScript, ensure correct `moduleResolution` in `tsconfig.json`.","cause":"Attempting to use CommonJS `require` syntax or an incorrect named import in an ESM module context, leading to `inject` being undefined.","error":"TypeError: (0, light_my_request_1.inject) is not a function"},{"fix":"Ensure you `await` the `inject` call when using `async/await`, or handle the `.then()` and `.catch()` branches correctly when using Promises. For example: `const res = await inject(...); console.log(res.payload);`","cause":"This typically occurs when attempting to access properties like `payload` from the response object before the Promise returned by `inject` has resolved, or if the `inject` call itself failed and was not caught.","error":"TypeError: Cannot read properties of undefined (reading 'payload')"},{"fix":"Install `form-auto-content` if you intend to use it for `multipart/form-data` requests: `npm install form-auto-content`.","cause":"Attempting to use the `form-auto-content` package for multipart data without explicitly installing it as a dependency.","error":"Error: Cannot find module 'form-auto-content'"}],"ecosystem":"npm"}