Dgraph JavaScript HTTP Client

raw JSON →
23.0.0-rc1 verified Thu Apr 23 auth: no javascript

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.

error TypeError: clientStub.setSlashApiKey is not a function
cause Attempting to use the deprecated `setSlashApiKey` method which has been removed.
fix
Use dgraphClient.setCloudApiKey(apiKey) instead. The setSlashApiKey method was deprecated in v21.03.0 and removed in later versions.
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.
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.
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.
error Error: 14 UNAVAILABLE: read ECONNRESET
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.
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.
error Errors: [{"message":"Invalid X-Dgraph-AuthToken"}]
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).
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.
breaking The `setSlashApiKey` method was deprecated in `v21.03.0` and removed in subsequent releases. Using it will result in an error or undefined behavior.
fix Replace `setSlashApiKey(apiKey)` with `setCloudApiKey(apiKey)`.
breaking 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.
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.
breaking 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.
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.
gotcha 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.
gotcha 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.
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.
gotcha 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.
npm install dgraph-js-http
yarn add dgraph-js-http
pnpm add dgraph-js-http

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.

import { DgraphClient, DgraphClientStub, Predicate, Type } from 'dgraph-js-http';

async function runDgraphOperations() {
  // Connect to Dgraph (default: http://localhost:8080)
  const clientStub = new DgraphClientStub(process.env.DGRAPH_ALPHA_ADDR ?? 'http://localhost:8080');
  const dgraphClient = new DgraphClient(clientStub);

  try {
    // Drop all data to start fresh (for example/testing)
    await dgraphClient.alter({ dropAll: true });
    console.log('Dropped all data.');

    // Set schema
    const schema = `
      name: string @index(exact) .
      age: int .
      married: bool .
    `;
    await dgraphClient.alter({ schema: schema });
    console.log('Schema set successfully.');

    // Add data (mutation)
    const mu = dgraphClient.newMutation();
    const p = {
      name: 'Alice',
      age: 26,
      married: true,
      'dgraph.type': 'Person'
    };
    const mutationResponse = await mu.setSetJson(p).commit();
    console.log('Data added:', mutationResponse.getUidsMap().get('blank-0'));

    // Query data
    const query = `
      query {
        q(func: eq(name, "Alice")) {
          name
          age
          married
        }
      }
    `;
    const res = await dgraphClient.newTxn().query(query);
    const people = res.getData();
    console.log('Queried data:', JSON.stringify(people, null, 2));

  } catch (e) {
    console.error('Error interacting with Dgraph:', e);
  } finally {
    // It's good practice to close the client stub in long-running processes if not needed.
    // In simple scripts, this might not be strictly necessary.
    // clientStub.close(); // DgraphClientStub does not have a public .close() method as of v23
  }
}

runDgraphOperations();