> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-mioty-service-center/integrations/api-reference/javascript-examples.md).

# JavaScript Examples

Runnable Node.js examples for the KiloCenter gRPC API — install @grpc/grpc-js with dynamic proto loading, call methods.

This page provides runnable Node.js examples for the KiloCenter gRPC API using dynamic proto loading. For the full API reference, see API Reference.

For general Node.js gRPC documentation, see [grpc.io/docs/languages/node](https://grpc.io/docs/languages/node/).

### Prerequisites

> All commands in this guide assume your working directory is `kilocenter-modules/`.

Install the gRPC and proto-loader packages:

```bash
npm install @grpc/grpc-js @grpc/proto-loader
```

No stub generation is needed — `@grpc/proto-loader` loads `.proto` files at runtime. Ensure the proto files are accessible at the paths referenced below (relative to the KiloCenter repository root):

* `KC-Core/api/proto/kilocenter.proto`
* `KC-Core/api/proto/core.proto`
* `KC-Core/api/proto/identity.proto`

### Get System Status

Retrieves the current system status including version, uptime, and service health.

```javascript
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

// KiloCenter KC-Gateway gRPC endpoint
const server = "localhost:9090";

const packageDef = protoLoader.loadSync("KC-Core/api/proto/kilocenter.proto", {
  keepCase: false,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
  includeDirs: ["KC-Core/api/proto"],
});

const proto = grpc.loadPackageDefinition(packageDef);
const client = new proto.kilocenter.api.v1.KiloCenterService(
  server,
  grpc.credentials.createInsecure()
);

client.GetSystemStatus({}, (err, resp) => {
  if (err) {
    console.error("GetSystemStatus failed:", err.message);
    process.exit(1);
  }

  console.log("Version:            ", resp.version);
  console.log("Status:             ", resp.status);
  console.log("Uptime:             ", resp.uptime);
  console.log("Active Endpoints:   ", resp.activeEndpoints);
  console.log("Active Base Stations:", resp.activeBasestations);
  console.log("Messages Processed: ", resp.messagesProcessed);

  for (const svc of resp.services) {
    console.log(`  Service: ${svc.name}  healthy=${svc.healthy}  latency=${svc.latencyMs}ms`);
  }
});
```

### List Endpoints

Lists registered endpoints with pagination support. High-volume profile: default page size 100, max 1000.

```javascript
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const server = "localhost:9090";

const packageDef = protoLoader.loadSync("KC-Core/api/proto/kilocenter.proto", {
  keepCase: false,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
  includeDirs: ["KC-Core/api/proto"],
});

const proto = grpc.loadPackageDefinition(packageDef);
const client = new proto.kilocenter.api.v1.KiloCenterService(
  server,
  grpc.credentials.createInsecure()
);

function listEndpoints(pageToken = "") {
  client.ListEndPoints({ pageSize: 100, pageToken }, (err, resp) => {
    if (err) {
      console.error("ListEndPoints failed:", err.message);
      process.exit(1);
    }

    console.log("Total endpoints:", resp.totalCount);

    for (const ep of resp.endpoints) {
      console.log(`  EUI: ${ep.epEui}  Name: ${ep.name}  Status: ${ep.status}  Class: ${ep.epClass}`);
    }

    if (resp.nextPageToken) {
      listEndpoints(resp.nextPageToken);
    }
  });
}

listEndpoints();
```

### Authentication

#### Community Edition

Community Edition runs single-tenant with organization enforcement off, so the examples above need only the `authorization` header: sign in with `Login` and send `Bearer <access_token>`. Each call also needs a role: `GetSystemStatus` is open to every role, `ListEndPoints` to Endpoint Managers and administrators. See [User Roles and Permissions](/kilo-mioty-service-center/security/users-and-roles.md).

#### Enterprise: JWT User Principal

Requires three headers: `authorization`, `x-organization-id`, and `x-user-id`. The `x-user-id` value must match the authenticated user in the JWT. Missing `x-user-id` returns `ErrTokenUserIDHeaderRequired`; a mismatch returns `ErrTokenIdentityMismatch`.

```javascript
const token = "your-jwt-token";
const orgId = "your-organization-uuid";
const userId = "your-user-uuid";

const metadata = new grpc.Metadata();
metadata.set("authorization", "Bearer " + token);
metadata.set("x-organization-id", orgId);
metadata.set("x-user-id", userId);

client.ListEndPoints({ pageSize: 100 }, metadata, (err, resp) => {
  if (err) {
    console.error("ListEndPoints failed:", err.message);
    return;
  }
  console.log("Total endpoints:", resp.totalCount);
});
```

#### Enterprise: Service-Account API Key

Requires two headers: `authorization` and `x-organization-id`. Do **not** send `x-user-id` — including it returns `ErrTokenIdentityMismatch` to prevent user injection.

A service-account key acts as a Base Station Manager and Endpoint Manager in the organization it was created for, so the call below succeeds for that organization. Calls that need the Admin or Tenant Manager role, and any call for another organization, return `PERMISSION_DENIED`.

```javascript
const apiKey = "your-api-key";
const orgId = "your-organization-uuid";

const metadata = new grpc.Metadata();
metadata.set("authorization", "Bearer " + apiKey);
metadata.set("x-organization-id", orgId);

client.ListEndPoints({ pageSize: 100 }, metadata, (err, resp) => {
  if (err) {
    console.error("ListEndPoints failed:", err.message);
    return;
  }
  console.log("Total endpoints:", resp.totalCount);
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.kiloiot.io/kilo-mioty-service-center/integrations/api-reference/javascript-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
