> For the complete documentation index, see [llms.txt](https://k4k3ru.gitbook.io/k4k3ru-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-typescript.md).

# Sign a Request with TypeScript

Build an authenticated K4K3RU JSON-RPC request with TypeScript on Node.js. Node.js handles HMAC-SHA256, and TweetNaCl signs with the 64-byte Ed25519 private key issued by K4K3RU.

## Prerequisites

* Node.js 20 or later.
* An API credential created with `hmac-sha256` or `ed25519`.
* `K4K3RU_API_KEY`, `K4K3RU_SECRET_KEY`, and `K4K3RU_SIGNATURE_ALGORITHM` set in your environment.

Create a project and install the example dependencies:

```bash
npm install tweetnacl
npm install --save-dev typescript tsx @types/node
```

## Example

Save this program as `sign-request.ts`:

```typescript
import { createHmac, randomBytes } from "node:crypto";
import nacl from "tweetnacl";

type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };

function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`set ${name}`);
  return value;
}

function canonicalize(value: JsonValue): JsonValue {
  if (Array.isArray(value)) return value.map(canonicalize);
  if (value !== null && typeof value === "object") {
    return Object.fromEntries(
      Object.keys(value)
        .sort()
        .map((key) => [key, canonicalize(value[key])]),
    );
  }
  return value;
}

function sign(algorithm: string, secret: Buffer, payload: Buffer): Buffer {
  if (algorithm === "hmac-sha256") {
    return createHmac("sha256", secret).update(payload).digest();
  }
  if (algorithm === "ed25519") {
    if (secret.length !== nacl.sign.secretKeyLength) {
      throw new Error(`invalid Ed25519 private key length: ${secret.length}`);
    }
    return Buffer.from(nacl.sign.detached(payload, secret));
  }
  throw new Error(`unsupported signature algorithm: ${algorithm}`);
}

const apiKey = requireEnv("K4K3RU_API_KEY");
const secret = Buffer.from(requireEnv("K4K3RU_SECRET_KEY"), "base64url");
const algorithm = requireEnv("K4K3RU_SIGNATURE_ALGORITHM");
const method = "PaymentOnchain.CreateIntent";
const params: JsonValue = { productName: "usdc-base-mainnet-1" };
const timestamp = Math.floor(Date.now() / 1000);
const nonce = randomBytes(16).toString("base64url");
const canonicalParams = JSON.stringify(canonicalize(params));
const payload = Buffer.from(`${method}\n${timestamp}\n${nonce}\n${canonicalParams}`, "utf8");
const signature = sign(algorithm, secret, payload).toString("base64url");

console.log(JSON.stringify({
  id: "1",
  method,
  params,
  auth: { apiKey, timestamp, nonce, signature },
}, null, 2));
```

Run it with:

```bash
npx tsx sign-request.ts
```

The program prints a request body that you can send to `https://api.k4k3ru.com/` with `Content-Type: application/json`. Build the payload and request from the same `params` object so their values cannot diverge.

## Next Steps

See [API Request Authentication](/k4k3ru-docs/api/authentication.md) for canonicalization, freshness, replay-protection, and troubleshooting requirements.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-typescript.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
