{"id":16246257,"url":"https://github.com/hardcodet/httpclient-js","last_synced_at":"2026-04-05T23:34:15.152Z","repository":{"id":54547494,"uuid":"258353032","full_name":"hardcodet/httpclient-js","owner":"hardcodet","description":"Simple HTTP/API client for typescript / javascript projects.","archived":false,"fork":false,"pushed_at":"2023-10-09T09:51:29.000Z","size":51,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-19T09:59:10.255Z","etag":null,"topics":["javascript","react","react-native","rest-client","retries","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hardcodet.png","metadata":{"files":{"readme":"README.MD","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-23T23:15:07.000Z","updated_at":"2024-10-03T11:53:34.000Z","dependencies_parsed_at":"2024-10-10T14:30:03.037Z","dependency_job_id":"7128ec6c-a784-4004-bf73-49042ee605d0","html_url":"https://github.com/hardcodet/httpclient-js","commit_stats":{"total_commits":12,"total_committers":3,"mean_commits":4.0,"dds":"0.16666666666666663","last_synced_commit":"56c890146a44aeb32309e119a3d803207d53804d"},"previous_names":["hardcodet/httpclient"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/hardcodet/httpclient-js","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hardcodet%2Fhttpclient-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hardcodet%2Fhttpclient-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hardcodet%2Fhttpclient-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hardcodet%2Fhttpclient-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hardcodet","download_url":"https://codeload.github.com/hardcodet/httpclient-js/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hardcodet%2Fhttpclient-js/sbom","scorecard":{"id":455610,"data":{"date":"2025-08-11","repo":{"name":"github.com/hardcodet/httpclient-js","commit":"c83a55ae5cd001e5ce3569edf09c386cd5bc462c"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3,"checks":[{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Code-Review","score":0,"reason":"Found 0/13 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 2 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-19T09:31:52.009Z","repository_id":54547494,"created_at":"2025-08-19T09:31:52.009Z","updated_at":"2025-08-19T09:31:52.009Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31454199,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-05T21:22:52.476Z","status":"ssl_error","status_checked_at":"2026-04-05T21:22:51.943Z","response_time":75,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","react","react-native","rest-client","retries","typescript"],"created_at":"2024-10-10T14:30:00.567Z","updated_at":"2026-04-05T23:34:15.115Z","avatar_url":"https://github.com/hardcodet.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Typescript / Javascript API Client\n\nThis is an opinionated HTTP client that provides simple access to REST-based APIs. It sits on\ntop of `axios` (https://github.com/axios/axios) and provides result unwrapping\n(with generics support for Typescript), pluggable authentication strategies\nand basic retry logic.\u003cbr/\u003e\nAlso supports on-the-fly class transformations (JSON to real classes) and validation\nbased on `class-transformer` and `class-validator`.\n\n```\npublic async getUser(): Promise\u003cUser\u003e {\n    const httpClient = new HttpClient(\"https://www.foo.com/api\");\n    const result: ApiResult\u003cUser\u003e = await httpClient.getAs\u003cUser\u003e(\"users/123\");\n    return result.getValueOrThrow();\n}\n```\n\n\n## Installation\n\n\u003ca href=\"https://www.npmjs.com/package/@hardcodet/httpclient\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/@hardcodet/httpclient.svg\" alt=\"NPM Version\" /\u003e\u003c/a\u003e\n\u003cbr\u003e\n\nUsing NPM:\n\n```\nnpm i @hardcodet/httpclient\n```\n\nUsing Yarn:\n\n```\nyarn add @hardcodet/httpclient\n```\n\n#### Optional: Class transformations / validation setup\n\nIf you are using the built-in class transformations based on `class-transformer`,\nyou will also need `reflect-metadata`:\n\n```\nnpm i reflect-metadata\n-- or --\nyarn add reflect-metadata\n```\n\nThen import it in a global place (typically your app initialization):\n\n```\nimport \"reflect-metadata\";\n```\n\n\n## Basic Usage\n\nSyntax is quite straightforward:\n\n1. Issue an HTTP call\n2. Process the `ApiResponse` (for `get`, `post`, ...) or `ApiResult`\n   (for `getAs`, `postAs`, ...) and handle the result. The `ApiResult` class provides\n   a `value` property that can be used to get and unwrap the parsed JSON response.\n\n```\npublic async doWork(): Promise\u003cSomeDto\u003e {\n\n    const httpClient = new HttpClient(\"https://www.foo.com/api\");\n    \n    const uri = \"/v1/bar\");\n    const payload = { ... };\n    \n    // send a POST with the specified body\n    const response: ApiResult\u003cSomeDto\u003e = await httpClient.postAs\u003cSomeDto\u003e(uri, payload);\n    \n    // unwrap the returned data (throws exception if the request fails)\n    const result: SomeDto = response.getValueOrThrow();\n    return result;\n}\n```\n        \n\u003cbr\u003e\nAlternatively, you can inspect the response object, e.g.\n\n```\nif (!response.success) {\n    if(response.notFound) {\n        // we got a 404\n        return undefined;\n    } else {\n        // some other error - throw\n        throw new Error(resonse.createError());\n    }\n} else {\n    const result: SomeDto = response.value;\n    return result;\n}\n```   \n    \nIf you don't expect a result, you can use `ensureSuccess`, which will\nthrow an error in case you won't get an `HTTP 2xx`:\n\n```\nconst response: ApiResponse = await httpClient.post(\"some/endpoint\");\nresponse.ensureSuccess();\n```     \n\n## Authentication\n\n`HttpClient` provides strategy-based authentication through the `IAuthClient` interface that\ncan be simply injected into a `HttpClient` instance:\n\n```\nconst basicAuth = new BasicAuthClient(\"myUserName\", \"myPassword\");\nconst httpClient = new HttpClient(\"https://www.foo.com/api\", {authClient: basicAuth});\nconst result = await httpClient.get(\"protected/endpoint\");\n```\n\nEvery time an invoked endpoint returns an `HTTP 401`, the client will try to resolve\na token through an injected auth strategy (if one is available).\n\n\nThere's currently 3 built-in implementations:\n\n- `Basic` auth (user name / password)\n- OAuth client credentials grant\n- A delegate-based strategy that allows you to inject some custom token fetch logic.\n  The resolved token will then be submitted as a `Bearer` token with subsequent requests.\n\n\n### Delegation based auth\n\nHere's a short sample with delegation. We simply use a second `HttpClient` without\nauthentication to fetch the token of the main `httpClient`:\n\n```\nconstructor() {\n    const authClient = new DelegateBearerAuthClient(() =\u003e this.getAccessToken());\n    this.httpClient = new HttpClient(\"https://api.foo.com\", { authClient });\n}\n\n\n/**\n * Invoked by the delegation authentication strategy of the HTTP client in order to\n * get a new access token when needed.\n */\nprivate async getAccessToken(): Promise\u003cstring\u003e {\n    // use an independent HTTP client - the default one would block because it's\n    // waiting on this method to resolve a token\n    const tokenClient = new HttpClient(\"https://www.auth-provider.com\");\n\n    const uri = \"v1/login?userId=foo\u0026\u0026password=bar\";\n    const result = await tokenClient.postAs\u003cstring\u003e(uri);\n    return result.getValueOrThrow();\n}\n```\n\n\n### Custom authentication strategies\n\n`IAuthClient` basically just provides a contract to perform a token fetch/refresh, and to\nconstruct an authorization header value that is being added to the request header when submitting\na request. You can easily build your own.\n\n```\nexport interface IAuthClient {\n\n    /**\n     * Asynchronously refreshes the token.\n     */\n    refreshToken(): Promise\u003cvoid\u003e;\n\n    /**\n     * Updates the header to be sent with an HTTP\n     * request in order to provide authentication.\n     */\n    getAuthHeader(): Promise\u003cobject\u003e;\n}\n```\n\n## Retries\n\nThe package comes with a simple retry mechanism. By default, it will perform up to 2 retries\n(3 attempts in total) before giving up in case the invoked endpoint returns a `5xx` error.\n\nFor `3xx` (redirects) or `4xx` errors, it will fail immediately without retries.) \n\n### Retry delays\n\nDelays between retries can follow 3 possible patterns:\n\n- Constant delays, e.g. 2 seconds between retries)\n- Linearly increasing delays, e.g. 2, 4, 6, 8 seconds between retries)\n- Exponentially increasing delays (default), e.g. 1, 4, 9, 16, 25 seconds between retries) \n\n```\n// up to 4 retries with 5 seconds wait time each\nconst options: HttpClientOptions = {\n    maxAttempts: 5,\n    retryDelay: 5000,\n    retryStrategy: RetryStrategy.Constant,\n};\nconst httpClient = new HttpClient(\"https://www.foo.com/api\", options);\n```\n\n\n## Transformation and Validation\n\n(Note: if you just need global transformations of date strings to `Date`, read below\non Json Processors and `IsoDateProcessor` specifically.)\n\nConsider this DTO:\n\n```\nclass User {\n    firstName: string;\n    lastName: string;\n    email: string;\n    dateOfBirth: Date;\n\n    getFullName(): string {\n        return firstName + \" \" + lastName;\n    }\n}\n```\n\nNote that if you fetch the JSON that matches this DTO from an API, the\nreturned object is *not* an instance of `User` but a plain Javascript object.\nAccordingly, you don't have a `getFullName` method, and `dateOfBirth` is actually\na string, not a `Date`. The snippet below would fail:\n\n```\n// get user\nconst result: ApiResult\u003cUser\u003e = await httpClient.getAs\u003cUser\u003e(\"users/123\");  \nconst user: User = result.value;\n\n// will fail - there is no such method on the returned object!\nconst fullName: string = user.getFullName();\n```\n\n\nIn order to get around this, you can use the transformation feature of the\nlibrary. Note the additional `User` type parameter in the `getAs` method:\n\n```\n// get user\nconst result: ApiResult\u003cUser\u003e = await httpClient.getAs(\"users/123\", User);  \nconst user: User = result.value;\n\n// works!\nconst fullName: string = user.getFullName();\n```\n\n#### Type conversions\n\nThere is still one gotcha: The javascript runtime still has no idea that the\n`dateOfBirth` field should be a Date, since JSON declares dates as regular\nstrings. In order to transform that string into a `Date` instance,\nyou will have to decorate your `UserDto.dateOfBirth` field with the\n`@Type(() =\u003e Date)` decorator:\n\n```\n@Type(() =\u003e Date)\ndateOfBirth: Date;\n```\n\nYou will also need the `Type` decorator for nested types.\nAll transformation comes from the `class-transformer` package. For more information,\nsee https://github.com/typestack/class-transformer.\n\n\n#### Validation\n\nTransformed types can also be validated based on validation decorators from\nthe `class-validator` package. For example, in order to make sure the returned\nuser data contains a valid email address, decorate it like this:\n\n```\n@IsEmail()\nemail: string;\n```\n\nFor more information on validation, see https://github.com/typestack/class-validator. \n\n\n#### Simpler version: JSON Processors\n\nA simpler alternative to decorating every DTO you have is injecting a global JSON\nprocessor. If we review our `User` DTO above, the `getFullName` method may be\nan anti-pattern anyway: The DTO should only capture state. This leaves us with\na pretty prototypical use case: We just want all date strings to be parsed into\nactual `Date` objects.\n\n```\ninterface User {\n    firstName: string;\n    lastName: string;\n    email: string;\n    dateOfBirth: Date;  // NEEDS TO BE TRANSFORMED\n}\n```\n\nAn alternative here is to use a JSON processor which transforms incoming or\noutgoing JSON. And because date transformations are so common, there's the\nbuilt-in `IsoDateProcessor` that we can use right away:\n\n```\nconst c = new HttpClient(options);\nc.inboundProcessors.push(new IsoDateProcessor())\n```\n\nThe injected `IsoDateProcessor` will process retrieved JSON objects\nand transform any string that matches an ISO8601 date for us.\n\n```\n// get user\nconst result: ApiResult\u003cUser\u003e = await httpClient.getAs\u003cUser\u003e(\"users/123\");  \nconst user: User = result.value;\n\n// works, since dateOfBirth is a Date object now\nconst year: string = user.dateOfBirth.getFullYear();\n```\n\nFor more flexibility, just check the `IJsonProcessor` interface and the built-in\n`StringTransformJsonProcessor` class.\n\n\n## Options\n\n```\nconst defaultOptions: HttpClientOptions = {\n    timeout: 10000,\n    maxAttempts: 3,\n    retryDelay: 1000,\n    retryStrategy: RetryStrategy.Exponential,\n    authClient: undefined,\n    customHeaders: undefined,\n};\n```\n\n|Option Value |Description                                                             |Default                  |\n|-------------|------------------------------------------------------------------------|-------------------------|\n|timeout      |Max time for a request until it fails.                                  |10000 (ms)               |\n|maxAttempts  |Maximum attempts until the client gives up. Set to 1 to disable retries.|3                        |\n|retryDelay   |Base delay between retries. Actual delay depends on the retry strategy. |1000 (ms)                |\n|retryStrategy|Constantly, linearly or exponentially growing delays.                   |RetryStrategy.Exponential|\n|authClient   |Pluggable authentication strategy.                                      |-                        |\n|customHeaders|Custom headers to be submitted with every request.                      |-                        |\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhardcodet%2Fhttpclient-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhardcodet%2Fhttpclient-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhardcodet%2Fhttpclient-js/lists"}