Dgraph JavaScript HTTP Client
raw JSON →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.
Common errors
error TypeError: clientStub.setSlashApiKey is not a function ↓
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. ↓
--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 ↓
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"}] ↓
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. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
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.
Install
npm install dgraph-js-http yarn add dgraph-js-http pnpm add dgraph-js-http Imports
- DgraphClient wrong
const DgraphClient = require('dgraph-js-http').DgraphClient;correctimport { DgraphClient } from 'dgraph-js-http'; - DgraphClientStub wrong
const DgraphClientStub = require('dgraph-js-http').DgraphClientStub;correctimport { DgraphClientStub } from 'dgraph-js-http'; - errors wrong
import { APIError } from 'dgraph-js-http';correctimport { APIError, HTTPError } from 'dgraph-js-http/lib/errors';
Quickstart
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();