# Use GenderAPI.io V2 with JavaScript and Node.js

> Call GenderAPI.io V2 from Node.js with native fetch. Download an ES module for single and mixed batch requests, data/meta responses and credit-aware errors.

Canonical HTML: https://www.genderapi.io/integrations/javascript

Last reviewed: 2026-09-27

## Runtime and example download

Node.js 22+. Downloadable HTTP integration example; not a separately published SDK.

- [Download the example](https://www.genderapi.io/examples/v2/genderapi-v2.mjs)

## Keep the integration on your Node.js server

This guide calls the GenderAPI.io V2 endpoint https://api.genderapi.io/api/v2/gender with a Bearer API key. Use Node.js 22 or later and download genderapi-v2.mjs into your project. This ES module uses built-in fetch and AbortSignal.timeout; no npm package is needed. The .mjs extension lets you import it from another ES module without changing package.json.

Set GENDERAPI_API_KEY in the server environment. Do not bundle it into React, Vue or browser JavaScript. Let your own server authenticate application users and call GenderAPI.io. The placeholder below is not a working key; importing the module or running it without an explicit run flag sends no request.

**Configure your Node.js environment**

```bash
node --version
export GENDERAPI_API_KEY="YOUR_API_KEY"
```

- [Download genderapi-v2.mjs](https://www.genderapi.io/examples/v2/genderapi-v2.mjs)
- [Verify your key with the free usage endpoint](https://www.genderapi.io/docs/v2/authentication#environment-setup)

## Send one JSON POST with an explicit AI policy

Save this code as single.mjs beside the downloaded module and run node single.mjs. It sends the V2 fields type and value with options.ai_mode: off. Read the estimate from response.data and the request and billing details from response.meta. A completed lookup costs 1 credit even when gender is null; the sample name does not guarantee a particular result.

The helper requires an explicit AI mode and a 24-character hexadecimal key, then checks meta.access.mode is api_key. A successful trial response triggers an access-mismatch error instead of silently proceeding. The server may already have consumed a trial credit before the helper detects that mismatch.

**Single lookup in Node.js**

```javascript
import { predict, GenderAPIError } from "./genderapi-v2.mjs";

try {
  const response = await predict({
    type: "name", value: "Alice", options: { ai_mode: "off" },
  });
  const result = response.data;
  console.log(result.result_status, result.gender);
  console.log(result.confidence, result.confidence_kind);
  console.log(response.meta.usage);
} catch (error) {
  if (!(error instanceof GenderAPIError)) throw error;
  // Do not log error.body: it can include the submitted value.
  console.error("Request failed:", error.code, error.requestId);
  process.exitCode = 1;
}
```

- [All single-request fields](https://www.genderapi.io/docs/v2/request-parameters)

## Keep the result and its evidence together

An inferred association is not a person's self-declared gender. Keep the original input, the returned evidence and any information provided by the person separate. An unknown result is a valid outcome; it should not become a guessed category in your application.

| Field | How to use it |
| --- | --- |
| `data.gender / data.result_status` | Use male or female only when identified. Preserve native JSON null when the result is unknown. |
| `data.name / data.match` | Inspect the returned name and selected candidate. A substring match does not prove that the input belongs to someone with that given name. |
| `data.confidence / data.confidence_kind` | Confidence is on a 0–1 scale or null. observed_frequency comes from stored counts; model_reported is an AI score. Evaluate thresholds separately for each kind. |
| `data.source / data.sample_count` | Distinguish dataset, ai and none. AI results have no stored sample count. A sample count is not a measured accuracy score. |
| `meta.access.mode` | Confirm api_key for an account integration. Missing or unrecognized keys can instead use the shared IP trial. |
| `meta.usage` | Read charged_credits and billing_status. A successful unknown is billable. A lost response does not establish that the request was free. |

- [Response fields and unknown outcomes](https://www.genderapi.io/docs/v2/responses)
- [Accuracy and confidence explained](https://www.genderapi.io/accuracy-methodology)
- [Data sources and the dated database profile](https://www.genderapi.io/data-provenance)

## Handle each item in a mixed batch

GenderAPI.io V2 uses POST https://api.genderapi.io/api/v2/gender/batch for mixed batches: up to 50 items with an account key or 10 for the IP trial. These examples require an account key. Give every item a stable, unique id and explicit AI mode. A batch can mix names, emails and usernames, with optional country context on each item.

Read every item in data and the summary in meta.summary. HTTP 200 can include item errors; an all-failed batch can be a top-level Problem response containing the results. Successful unknowns count as succeeded. The original index and id let you attach an outcome to the correct source row.

For larger jobs, divide input into groups of at most 50 and submit sequentially at first. Save each response and its usage before advancing. Stop on transport, account or unconfirmed-billing failures and reconcile the current group. Add concurrency only after checking your account limits; a batch-size limit is not a throughput guarantee.

**Batch lookup in Node.js**

```javascript
import { predictBatch, GenderAPIError } from "./genderapi-v2.mjs";

const items = [
  { id: "row-1", type: "name", value: "Alice", options: { ai_mode: "off" } },
  { id: "row-2", type: "email", value: "alex@example.com", options: { ai_mode: "off" } },
  { id: "row-3", type: "username", value: "sample_handle", options: { ai_mode: "off" } },
];
try {
  const response = await predictBatch(items);
  for (const item of response.data) {
    if (item.error) {
      console.log(item.id, "failed", item.error.code);
    } else {
      console.log(item.id, item.data.result_status, item.data.gender);
    }
  }
  console.log(response.meta.summary, response.meta.usage);
  if (response.meta.summary.failed > 0) process.exitCode = 2;
} catch (error) {
  if (!(error instanceof GenderAPIError)) throw error;
  // error.body can retain an all-failed batch and billing details.
  console.error("Batch needs review:", error.code, error.requestId);
  process.exitCode = 1;
}
```

- [Batch input, results and billing](https://www.genderapi.io/docs/v2/batch)

## Choose when to use AI

forceToGenderize is optional for names, email addresses and usernames. With it enabled, omit ai_mode or use fallback; off and always conflict with it and return 422. A positive starting balance is enough to begin a request even if its final charge takes the balance below zero.

Nickname mode can return a gender with name: null. It can also return an unknown result. Neither ordinary fallback nor nickname inference guarantees a correct or non-null answer.

This JavaScript helper always requires options.ai_mode. For nickname inference, send forceToGenderize: true together with options: { ai_mode: 'fallback' }.

| Request option | Behavior | Credits for a successful lookup |
| --- | --- | --- |
| options.ai_mode: off | Use the dataset only. | 1, including an unknown result |
| options.ai_mode: fallback | Try the dataset, then ordinary AI when no gender is returned. This is the single-request default. | 1 total, including AI fallback |
| options.ai_mode: always | Ask AI directly. | 2 |
| forceToGenderize: true | Try the dataset first, then allow AI to interpret a personal nickname or alias even without a real given name. | 1 for a resolved dataset result; 2 total if AI is used |

- [AI options and nickname inference](https://www.genderapi.io/docs/v2/ai-options)
- [Credits and usage](https://www.genderapi.io/docs/v2/credits-and-usage)

## Decide what to do after a failure

The examples send each operation once. They do not retry automatically: a new submission is a new billable operation. A timeout or connection failure means the client did not receive a complete response; it does not prove that the server stopped or that no credits were charged.

Keep the returned request ID and billing state with your job record. The error object retains the response for controlled inspection, but it can contain the original input; do not put the whole object, response or API key into routine logs.

| Outcome | Application decision |
| --- | --- |
| Successful unknown | Keep null, reason and usage. This is a completed billable result, not a failed row to retry automatically. |
| 422 validation error | Correct the input identified by the Problem Details fields before making a new request. |
| 401 / 403 | Review account access or available credits. Repeatedly submitting the same request will not resolve the underlying issue. |
| 429 | Respect Retry-After when present. Confirm the error and billing state, then schedule a deliberate later attempt. |
| Network error, timeout or unreadable response | Record that the result and charge are not confirmed. Reconcile before resubmitting; the client cannot cancel completed server work. |
| billing_status: unconfirmed | charged_credits and remaining_credits can be null. Contact support with request_id before retrying; do not replace null with zero. |
| Some batch items failed | Store completed items first. Review failed items and their billing; resubmit only the eligible failures, not the whole batch. |

- [Problem Details and retry decisions](https://www.genderapi.io/docs/v2/errors-and-retries)
- [Credits and billing confirmation](https://www.genderapi.io/docs/v2/credits-and-usage)

## Understand the fetch timeout and response checks

The default timeout is 10,000 milliseconds using AbortSignal.timeout, including reading the response body. Aborting the client does not establish that server processing or billing stopped. The module disables redirects, distinguishes HTTP failures from unreadable responses, and never retries automatically.

Transport-fixture tests exercise successful responses, unknowns, partial batches, credential fallbacks and errors. No real prediction or credit operation is needed for these tests; they are not a live availability or accuracy benchmark.

**Optional explicit Node.js demos**

```bash
node genderapi-v2.mjs --run-single
# Run separately to submit another billable sample batch:
node genderapi-v2.mjs --run-batch
```

- [Node.js fetch reference](https://nodejs.org/api/globals.html#fetch)
- [Node.js AbortSignal.timeout reference](https://nodejs.org/api/globals.html#static-method-abortsignaltimeoutdelay)

## Can I paste this into browser JavaScript?

Keep it on your server. A browser bundle exposes the API key to its users. Call your own authenticated backend from the browser, and have that backend send the GenderAPI request.

## Will an unknown result use credits?

Yes. A successful ordinary lookup costs 1 credit even when gender is null. Ordinary fallback AI is included in that credit. Always-AI costs 2; forceToGenderize costs 1 for a resolved dataset result or 2 when AI runs.

## Does this example retry a failed request?

No. Each new request is an independent operation. Inspect the error, per-item results and billing state before deciding whether to resubmit. A missing response does not establish that the previous attempt was free.

## Is this a package I need to install?

No. Download the example directly from this GenderAPI.io guide. It has no third-party runtime dependency and is not a separately published SDK. Review and adapt it for your application; the GenderAPI.io V2 documentation remains the API contract.

## Reference documentation

- [GenderAPI.io V2 authentication](https://www.genderapi.io/docs/v2/authentication)
- [V2 response fields](https://www.genderapi.io/docs/v2/responses)
- [Batch results and limits](https://www.genderapi.io/docs/v2/batch)
- [Error and retry reference](https://www.genderapi.io/docs/v2/errors-and-retries)
