{"id":17575,"library":"dgraph-js-http","title":"Dgraph JavaScript HTTP Client","description":"dgraph-js-http is the official JavaScript HTTP client for Dgraph, a distributed graph database. It enables interaction with Dgraph instances over HTTP, supporting fundamental graph operations like queries, mutations, and schema alterations. This client is suitable for both browser and Node.js environments where a gRPC connection, typically handled by the `dgraph-js` library, might be impractical or undesirable. The latest release series is currently `v23.0.0-rc1`, indicating a development stage. While the project previously followed a CalVer (Calendar Versioning) scheme aligned with Dgraph server releases, the recent release cadence seems more feature-driven. Key differentiators include its lightweight HTTP-based approach, comprehensive API for DQL operations, and robust support for Dgraph Cloud features such as ACLs, API key management (`setCloudApiKey`), and multi-tenancy via `loginIntoNamespace()`. The library actively incorporates security fixes and addresses known vulnerabilities.","status":"active","version":"23.0.0-rc1","language":"javascript","source_language":"en","source_url":"https://github.com/dgraph-io/dgraph-js-http","tags":["javascript","typescript"],"install":[{"cmd":"npm install dgraph-js-http","lang":"bash","label":"npm"},{"cmd":"yarn add dgraph-js-http","lang":"bash","label":"yarn"},{"cmd":"pnpm add dgraph-js-http","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"ESM imports are recommended. CommonJS require() pattern is also supported, but TypeScript type inference is better with ESM.","wrong":"const DgraphClient = require('dgraph-js-http').DgraphClient;","symbol":"DgraphClient","correct":"import { DgraphClient } from 'dgraph-js-http';"},{"note":"Used to establish a connection to a specific Dgraph Alpha server endpoint. Multiple stubs can be passed to DgraphClient for workload distribution.","wrong":"const DgraphClientStub = require('dgraph-js-http').DgraphClientStub;","symbol":"DgraphClientStub","correct":"import { DgraphClientStub } from 'dgraph-js-http';"},{"note":"Specific error classes like `APIError` and `HTTPError` are imported directly from the `lib/errors` submodule, not the top-level package.","wrong":"import { APIError } from 'dgraph-js-http';","symbol":"errors","correct":"import { APIError, HTTPError } from 'dgraph-js-http/lib/errors';"}],"quickstart":{"code":"import { DgraphClient, DgraphClientStub, Predicate, Type } from 'dgraph-js-http';\n\nasync function runDgraphOperations() {\n  // Connect to Dgraph (default: http://localhost:8080)\n  const clientStub = new DgraphClientStub(process.env.DGRAPH_ALPHA_ADDR ?? 'http://localhost:8080');\n  const dgraphClient = new DgraphClient(clientStub);\n\n  try {\n    // Drop all data to start fresh (for example/testing)\n    await dgraphClient.alter({ dropAll: true });\n    console.log('Dropped all data.');\n\n    // Set schema\n    const schema = `\n      name: string @index(exact) .\n      age: int .\n      married: bool .\n    `;\n    await dgraphClient.alter({ schema: schema });\n    console.log('Schema set successfully.');\n\n    // Add data (mutation)\n    const mu = dgraphClient.newMutation();\n    const p = {\n      name: 'Alice',\n      age: 26,\n      married: true,\n      'dgraph.type': 'Person'\n    };\n    const mutationResponse = await mu.setSetJson(p).commit();\n    console.log('Data added:', mutationResponse.getUidsMap().get('blank-0'));\n\n    // Query data\n    const query = `\n      query {\n        q(func: eq(name, \"Alice\")) {\n          name\n          age\n          married\n        }\n      }\n    `;\n    const res = await dgraphClient.newTxn().query(query);\n    const people = res.getData();\n    console.log('Queried data:', JSON.stringify(people, null, 2));\n\n  } catch (e) {\n    console.error('Error interacting with Dgraph:', e);\n  } finally {\n    // It's good practice to close the client stub in long-running processes if not needed.\n    // In simple scripts, this might not be strictly necessary.\n    // clientStub.close(); // DgraphClientStub does not have a public .close() method as of v23\n  }\n}\n\nrunDgraphOperations();","lang":"typescript","description":"This quickstart initializes a Dgraph client, drops existing data, defines a schema, performs a data mutation, and then queries the inserted data. It demonstrates basic setup and common DQL operations using the HTTP client."},"warnings":[{"fix":"Replace `setSlashApiKey(apiKey)` with `setCloudApiKey(apiKey)`.","message":"The `setSlashApiKey` method was deprecated in `v21.03.0` and removed in subsequent releases. Using it will result in an error or undefined behavior.","severity":"breaking","affected_versions":">=21.07.0"},{"fix":"Upgrade your Dgraph server instance to `v1.0.9` or later, or use an older `dgraph-js-http` client version if compatibility with very old Dgraph servers is required.","message":"Version `0.2.0` introduced a breaking change by dropping support for Dgraph server versions older than `1.0.9`. Ensure your Dgraph instance is up-to-date when using `0.2.0` or newer client versions.","severity":"breaking","affected_versions":">=0.2.0"},{"fix":"For `X-Dgraph-CommitNow`, use `commitNow=true` as a query parameter. For `X-Dgraph-MutationType`, use the standard `Content-Type` header. Ensure your client library is updated to handle these changes or adjust manual HTTP requests.","message":"Dgraph versions `v1.1.0` and above deprecated the `X-Dgraph-CommitNow` and `X-Dgraph-MutationType` HTTP headers. While the client might abstract this, direct HTTP interactions or older client versions could lead to issues.","severity":"breaking","affected_versions":">=1.1.0 (Dgraph server)"},{"message":"When connecting to Dgraph Cloud or a multi-tenancy instance, ensure you use the `loginIntoNamespace()` method for proper authentication and authorization. Simply passing `accessToken` and `refreshToken` directly to the `clientStub` is not the recommended way as the client manages the token lifecycle.","severity":"gotcha"},{"fix":"Ensure your Dgraph server is configured with appropriate CORS headers (`--cors-dir` or `--cors` flags). For Dgraph Cloud, check their documentation for configuring allowed origins. Explicitly allowing `localhost:3000` (or your dev server origin) and necessary headers like `X-Dgraph-AuthToken` is crucial. Updating `dgraph-js-http` to at least `v20.07.0` fixed some CORS issues.","message":"CORS issues are common when using this client in browser environments, especially with Dgraph running locally or in Docker. This can manifest as 'Access-Control-Allow-Origin' or 'Request header field X-Dgraph-AuthToken is not allowed' errors.","severity":"gotcha","affected_versions":"All"},{"message":"The `dgraph-js-http` client should be used for HTTP/REST interactions. If gRPC is preferred or required (e.g., for certain Node.js server-side applications with `dgraph-js`), ensure you are using the correct library. Mixing client types can lead to unexpected errors like `ECONNRESET` or functionality limitations.","severity":"gotcha"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Use `dgraphClient.setCloudApiKey(apiKey)` instead. The `setSlashApiKey` method was deprecated in `v21.03.0` and removed in later versions.","cause":"Attempting to use the deprecated `setSlashApiKey` method which has been removed.","error":"TypeError: clientStub.setSlashApiKey is not a function"},{"fix":"Configure your Dgraph server (e.g., via Docker flags like `--cors_origins \"http://localhost:3000\" --cors_allowed_headers \"X-Dgraph-AuthToken, Content-Type\"`) to explicitly allow your client's origin and required headers. Ensure Dgraph-js-http is updated to at least v20.07.0.","cause":"Dgraph server is not configured to allow requests from the client's origin, or missing necessary `Access-Control-Allow-Headers` in the preflight response.","error":"Access to fetch at 'http://localhost:8080/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."},{"fix":"Verify that you are using the `dgraph-js-http` client when connecting to an HTTP endpoint. If connecting via gRPC (using `dgraph-js`), ensure the endpoint is correct and SSL/TLS certificates are properly configured. Check server logs for more details.","cause":"This error typically indicates an issue with the underlying network connection. It can occur if a gRPC client (`dgraph-js`) is trying to connect to an HTTP-only endpoint, or if there's a problem with TLS/SSL setup.","error":"Error: 14 UNAVAILABLE: read ECONNRESET"},{"fix":"Ensure you are setting the correct API key using `dgraphClient.setCloudApiKey(apiKey)` for Dgraph Cloud, or `clientStub.login(\"username\", \"password\")` and `clientStub.setAlphaAuthToken(token)` for Dgraph instances with ACLs enabled. Verify the token's validity and permissions for the operation.","cause":"The `X-Dgraph-AuthToken` header is either missing, incorrect, or not accepted by the Dgraph server for the attempted operation (e.g., alter operations often require authentication).","error":"Errors: [{\"message\":\"Invalid X-Dgraph-AuthToken\"}]"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}