{"id":17295,"library":"moleculer-http-client","title":"Moleculer HTTP Client Mixin","description":"This package provides an HTTP client mixin for Moleculer microservices, enabling them to make requests to external REST APIs. It is currently at version 0.4.2 and wraps the popular `got` library for HTTP requests. While there's no explicit release cadence stated for this particular mixin, it generally follows the Moleculer ecosystem's development pace. Its key differentiators include seamless integration into Moleculer services via mixins, providing declarative HTTP actions (`get`, `post`, `put`, `patch`), and centralized configuration for logging, error handling, and `got` options within the service settings. This approach simplifies HTTP communication within a microservice architecture, abstracting common concerns like request/response logging and error formatting directly into the service lifecycle.","status":"active","version":"0.4.2","language":"javascript","source_language":"en","source_url":"https://github.com/moleculerjs/moleculer-http-client","tags":["javascript","moleculer","microservice","microservices","http client","http-client","http-request","http request","typescript"],"install":[{"cmd":"npm install moleculer-http-client","lang":"bash","label":"npm"},{"cmd":"yarn add moleculer-http-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add moleculer-http-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for the Moleculer microservices framework it integrates with.","package":"moleculer","optional":false},{"reason":"Runtime dependency for making HTTP requests; this package is a wrapper around 'got'.","package":"got","optional":false}],"imports":[{"note":"The package exports a default service mixin for Moleculer. Use ES module syntax for modern Node.js applications.","wrong":"const HttpClientMixin = require('moleculer-http-client');","symbol":"HttpClientMixin","correct":"import HttpClientMixin from 'moleculer-http-client';"}],"quickstart":{"code":"import { ServiceBroker } from 'moleculer';\nimport HttpClientMixin from 'moleculer-http-client';\n\nconst broker = new ServiceBroker({\n    logger: true, // Enable console logger\n    logLevel: 'info' // Set logging level\n});\n\nbroker.createService({\n    name: \"myApiConsumer\",\n    mixins: [HttpClientMixin],\n    settings: {\n        httpClient: {\n            logging: true, // Log outgoing requests and incoming responses\n            responseFormatter: \"body\", // Only return the response body by default\n            defaultOptions: {\n                // Default options passed directly to the 'got' client\n                headers: {\n                    'User-Agent': 'moleculer-http-client-example/1.0',\n                },\n                timeout: {\n                    request: 5000 // 5 seconds timeout for all requests\n                }\n            }\n        }\n    },\n    actions: {\n        async fetchPosts(ctx) {\n            this.logger.info(`Attempting to fetch post from: ${ctx.params.url}`);\n            try {\n                // Call the 'get' action provided by the mixin\n                const response = await ctx.call(\"myApiConsumer.get\", {\n                    url: \"https://jsonplaceholder.typicode.com/posts/1\"\n                });\n                this.logger.info(\"Successfully fetched post:\", JSON.stringify(response));\n                return response;\n            } catch (error) {\n                this.logger.error(\"Error fetching post:\", error.message);\n                throw error; // Re-throw to propagate error in Moleculer\n            }\n        },\n        async submitData(ctx) {\n            this.logger.info(`Attempting to submit data to: ${ctx.params.url}`);\n            try {\n                // Call the 'post' action provided by the mixin\n                const response = await ctx.call(\"myApiConsumer.post\", {\n                    url: \"https://jsonplaceholder.typicode.com/posts\",\n                    json: {\n                        title: 'foo',\n                        body: 'bar',\n                        userId: 1,\n                    }\n                });\n                this.logger.info(\"Successfully submitted data (ID: %s)\", response.id);\n                return response;\n            } catch (error) {\n                this.logger.error(\"Error submitting data:\", error.message);\n                throw error;\n            }\n        }\n    }\n});\n\nasync function runExample() {\n    await broker.start();\n    broker.logger.info(\"Broker started. Calling fetchPosts action...\");\n    await broker.call(\"myApiConsumer.fetchPosts\", { url: \"https://jsonplaceholder.typicode.com/posts/1\" });\n\n    broker.logger.info(\"\\nCalling submitData action...\");\n    await broker.call(\"myApiConsumer.submitData\", { url: \"https://jsonplaceholder.typicode.com/posts\" });\n\n    await broker.stop();\n}\n\nrunExample();\n","lang":"typescript","description":"Demonstrates creating a Moleculer service using the `moleculer-http-client` mixin, configuring its HTTP client settings, and then using the mixin's `get` and `post` actions to communicate with an external REST API, including basic error handling."},"warnings":[{"fix":"Ensure `url` and `opt` are correctly placed in `ctx.meta` for streaming actions: `await ctx.call('service.post', streamPayload, { meta: { url: 'https://api.example.com', opt: { headers: {...} } } });`","message":"When performing streaming requests (e.g., POST/PUT/PATCH with `streamPayload`), the `url` and `opt` parameters must be passed in `ctx.meta`, while the stream data itself is passed directly as `ctx.params`. This deviates from typical Moleculer action parameter conventions where `ctx.params` usually holds all explicit arguments.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Review the changelog for `got` when upgrading it directly or if `moleculer-http-client` updates its `got` dependency. Test `moleculer-http-client` functionality thoroughly after such upgrades. Consider pinning the `got` version if strict stability is required, or ensure `moleculer-http-client`'s `package.json` specifies compatible `got` ranges.","message":"This mixin relies on the `got` HTTP client. Breaking changes in `got`'s major versions (e.g., `got@11` to `got@12`) might introduce incompatibilities or require configuration adjustments within `httpClient.defaultOptions` or action parameters, even if `moleculer-http-client`'s own version doesn't change significantly.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always use `try...catch` blocks around `await ctx.call('service.action', ...)` for HTTP requests to gracefully handle errors. Additionally, configure Moleculer's `errorHandler` at the broker level for global error management.","message":"Unhandled promise rejections from HTTP requests can crash your Moleculer service if not properly caught. Network errors, API errors (e.g., 4xx, 5xx responses), and timeouts from `got` will result in rejected promises.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that `mixins: [HttpClientMixin]` is present in your service definition. Ensure that the service name in `ctx.call` (e.g., `ctx.call('yourServiceName.get', ...)`) precisely matches the `name` property of your service.","cause":"The `HttpClientMixin` was not correctly added to the service's `mixins` array, or the service name used in `ctx.call` (e.g., 'myService') does not match the actual name of the service that has the mixin.","error":"Service 'myService' has no action 'myService.get'"},{"fix":"Double-check the URL for typos, verify that the target API is accessible (e.g., ping the host) from your Moleculer service's environment, and ensure no firewalls or network configurations are blocking the outbound connection.","cause":"This error indicates a network connection issue. The target API server is either not running, unreachable from where your Moleculer service is hosted, or the URL specified in the request is incorrect or malformed.","error":"RequestError: connect ECONNREFUSED"},{"fix":"Ensure your service definition includes a `settings` block with a properly structured `httpClient` object, for example: `settings: { httpClient: { logging: true, defaultOptions: {} } }`. All keys within `httpClient` should be correctly spelled.","cause":"The `httpClient` configuration object within the service `settings` is missing or malformed, preventing the mixin from properly initializing `got` options.","error":"TypeError: Cannot read properties of undefined (reading 'httpClient')"}],"ecosystem":"npm","meta_description":null}