{"id":17301,"library":"nestjs-http-promise","title":"NestJS HTTP Promise Module with Retries","description":"nestjs-http-promise is a NestJS module that extends the framework's official HTTP capabilities by providing a promise-based API for Axios-powered requests. This library, currently at version 4.0.0, aims to simplify HTTP client interactions by eliminating the need for explicit `.toPromise()` calls on RxJS Observables, which are typically returned by NestJS's default HttpModule. A key differentiator is its out-of-the-box integration of automatic request retries using `axios-retry` and enhanced Axios stack traces for improved debugging. The package generally follows major NestJS and Axios version updates, ensuring compatibility with the latest ecosystem features. It offers both static and asynchronous configuration options, allowing for flexible setup within various NestJS architectural patterns. Its primary function is to provide a more imperative, promise-centric approach to HTTP requests within a declarative NestJS module structure, contrasting with the Observable-first approach of the base NestJS HTTP module.","status":"active","version":"4.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/benhason1/nestjs-http-promise","tags":["javascript","nestjs","http","promise","retry","retries","axios","typescript"],"install":[{"cmd":"npm install nestjs-http-promise","lang":"bash","label":"npm"},{"cmd":"yarn add nestjs-http-promise","lang":"bash","label":"yarn"},{"cmd":"pnpm add nestjs-http-promise","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core NestJS framework dependency, required for module and service integration.","package":"@nestjs/common","optional":false},{"reason":"Required by NestJS for dependency injection and decorator functionality.","package":"reflect-metadata","optional":false},{"reason":"Underlying HTTP client library used for making requests.","package":"axios","optional":false}],"imports":[{"note":"Use named import for the module. CommonJS `require` is generally not used in modern NestJS TypeScript projects and may lead to module resolution issues.","wrong":"const { HttpModule } = require('nestjs-http-promise')","symbol":"HttpModule","correct":"import { HttpModule } from 'nestjs-http-promise'"},{"note":"HttpService is a named export. Attempting a default import will result in 'Module ''nestjs-http-promise'' has no default export' or undefined.","wrong":"import HttpService from 'nestjs-http-promise'","symbol":"HttpService","correct":"import { HttpService } from 'nestjs-http-promise'"},{"note":"This interface is crucial for implementing asynchronous module configuration via `registerAsync` and must be imported correctly.","wrong":"import { IHttpModuleOptionsFactory } from 'nestjs-http-promise'","symbol":"HttpModuleOptionsFactory","correct":"import { HttpModuleOptionsFactory } from 'nestjs-http-promise'"}],"quickstart":{"code":"import { Module, Injectable, INestApplication } from '@nestjs/common';\nimport { HttpModule, HttpService, HttpModuleOptionsFactory, HttpModuleOptions } from 'nestjs-http-promise';\nimport { NestFactory } from '@nestjs/core';\n\n// Example of an async configuration service\n@Injectable()\nclass HttpConfigService implements HttpModuleOptionsFactory {\n  async createHttpOptions(): Promise<HttpModuleOptions> {\n    // Simulate fetching configuration data asynchronously, e.g., from a config service or environment variables\n    const configurationData = await Promise.resolve({\n      baseURL: 'https://jsonplaceholder.typicode.com',\n      timeout: 5000,\n      maxRetries: 3,\n      isBetterStackTraceEnabled: true // Enable improved stack traces by default\n    });\n\n    return {\n      baseURL: configurationData.baseURL,\n      timeout: configurationData.timeout,\n      retries: configurationData.maxRetries,\n      isBetterStackTraceEnabled: configurationData.isBetterStackTraceEnabled,\n    };\n  }\n}\n\n@Injectable()\nclass MyApiService {\n  constructor(private readonly httpService: HttpService) {}\n\n  /**\n   * Fetches a post by ID. This call benefits from the module's configured retries.\n   */\n  async fetchPost(id: number): Promise<any> {\n    console.log(`Attempting to fetch post ${id}...`);\n    // The HttpService methods return Promises directly\n    const response = await this.httpService.get(`/posts/${id}`);\n    return response.data;\n  }\n\n  /**\n   * Creates a new post. Retries can be overridden per request.\n   */\n  async createPost(title: string, body: string): Promise<any> {\n    console.log('Attempting to create a new post...');\n    const response = await this.httpService.post('/posts', { title, body, userId: 1 }, {\n      retries: 0 // No retries for create operations for this specific request\n    });\n    return response.data;\n  }\n}\n\n@Module({\n  imports: [\n    // Asynchronously configure HttpModule using a factory class\n    HttpModule.registerAsync({\n      useClass: HttpConfigService,\n    }),\n  ],\n  providers: [MyApiService, HttpConfigService], // HttpConfigService must be provided if used with useClass\n  exports: [MyApiService], // Export the service if it's used by other modules\n})\nclass ApiIntegrationModule {}\n\nasync function bootstrap() {\n  const app: INestApplication = await NestFactory.create(ApiIntegrationModule);\n  await app.listen(3000, () => {\n    console.log('NestJS Application listening on port 3000');\n  });\n\n  const apiService = app.get(MyApiService);\n\n  try {\n    const post = await apiService.fetchPost(1);\n    console.log('\\nFetched Post 1:', post);\n\n    const newPost = await apiService.createPost('Hello Registry', 'This is a test post from the registry quickstart.');\n    console.log('\\nCreated New Post:', newPost);\n  } catch (error: any) {\n    console.error('\\nAn error occurred during API calls:');\n    console.error('Error message:', error.message);\n    if (error.response) {\n      console.error('Response status:', error.response.status);\n      console.error('Response data:', error.response.data);\n    } else if (error.code === 'ECONNABORTED') {\n      console.error('Request timed out or cancelled.');\n    }\n  } finally {\n    await app.close();\n    console.log('\\nApplication closed.');\n  }\n}\n\n// To run this quickstart, save it as a .ts file in a NestJS project and execute with `ts-node` or compile.\n// In a real application, `bootstrap()` would be called from `main.ts`.\nbootstrap();","lang":"typescript","description":"This quickstart demonstrates how to install, configure (asynchronously), inject, and use `nestjs-http-promise` to perform promise-based HTTP requests with built-in retries, fetching and creating a test post."},"warnings":[{"fix":"Ensure your project's `axios` version is `^1.x.x` and your NestJS core packages (`@nestjs/common`, etc.) are compatible with `^10.x.x` (or `>=7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0` as per peer deps).","message":"Version 3.0.0 introduced significant dependency upgrades, bumping Axios from v0.x.x to v1.x.x and NestJS peer dependency to v10.x.x. This may require manual updates to your project's `axios` and `@nestjs/*` dependencies to maintain compatibility.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Pass `{ isBetterStackTraceEnabled: false }` in `HttpModule.register()` or `createHttpOptions()` if you need to disable the enhanced stack traces.","message":"The `isBetterStackTraceEnabled` feature, which adds data to Axios stack traces, is enabled by default. While generally helpful, it can be explicitly disabled by setting `isBetterStackTraceEnabled: false` in the module configuration if it causes unexpected behavior or performance overhead in specific environments.","severity":"gotcha","affected_versions":">=1.2.1"},{"fix":"Ensure the class passed to `useClass` is added to the `providers` array of the module importing `HttpModule.registerAsync()`.","message":"When using `HttpModule.registerAsync()` with `useClass`, the implementing class (e.g., `HttpConfigService`) must implement the `HttpModuleOptionsFactory` interface and must also be provided in the `providers` array of the importing module. Failure to provide the class will result in a NestJS DI error.","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":"Verify that `HttpModule` (either `HttpModule.register()` or `HttpModule.registerAsync()`) is correctly listed in the `imports` array of the module that declares the component injecting `HttpService`.","cause":"HttpModule was not properly imported or configured in the module where HttpService is being injected.","error":"Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument at index [0] is available in the ApiIntegrationModule context."},{"fix":"Run `npm install nestjs-http-promise` or `yarn add nestjs-http-promise`. Check that the import statement matches `import { ... } from 'nestjs-http-promise'`.","cause":"The package was not installed or an incorrect import path was used.","error":"Error: Cannot find module 'nestjs-http-promise'"},{"fix":"Ensure `HttpModule` is correctly imported in the module that provides `HttpService`. For `registerAsync`, double-check the `useFactory` or `useClass` implementation to ensure valid `HttpModuleOptions` are returned.","cause":"HttpService was injected but its dependencies (Axios) might not have been properly initialized, or the module was not set up correctly leading to an undefined HttpService.","error":"TypeError: Cannot read properties of undefined (reading 'get') (or similar for post, put, etc.) on HttpService instance."}],"ecosystem":"npm","meta_description":null}