---
title: "Nonce Authentication"
description: "Authorize the Email Editor v4 with short-lived nonces that your backend signs with the Secret key, instead of the API key alone."
url: https://docs.topol.io/email-editor/guide/nonce-authentication.html
---

# Nonce Authentication

**Email Editor v4 can authorize each session with a short-lived nonce that your backend signs with the Secret key.** A nonce is bound to one user, expires at the time your backend sets (an hour at most is recommended), and stops working as soon as you rotate the Secret key or revoke the API token.

**Nonce authentication is the setup we recommend for every integration.** The API key alone keeps working and is enough to try the editor, but it sits in your page source and never expires. You turn nonce authentication on by passing a `getNonce` callback; there is no separate option. Your `api.*` endpoints and callbacks for templates, autosaves, images, comments and saved sections keep working exactly as before.

> **INFO**
>
> Nonce authentication requires Email Editor v4. If you're still on v3, [upgrade to v4](https://docs.topol.io/email-editor/guide/v4-migration.html) first. You can add nonce authentication during the upgrade or after it.

## How it works

Your backend creates the nonce itself, with no call to Topol. The editor gets it from your page through `getNonce` and sends it to Topol, which checks the signature.

1.  **The editor asks your page.** It calls your `getNonce` callback when it loads and again before the current nonce expires.
2.  **Your page asks your backend.** `getNonce` runs on your page, not inside the editor iframe, so your own session cookies are sent and there is no CORS to set up.
3.  **Your backend signs a nonce** for the signed-in user with the [Secret key](https://docs.topol.io/email-editor/guide/how-to-get-secret-key.html). It doesn't call Topol.
4.  **The nonce goes back to the editor**, through your page.
5.  **Topol checks it.** The editor sends the nonce as a Bearer token on its requests to Topol, which verifies the signature and the expiry. Requests to your own `api.*` endpoints never carry it.

## Step 1: Sign nonces on your backend

A nonce is a JSON payload and its HMAC-SHA256 signature:

```
nc_<base64url(payload)>.<base64url(HMAC-SHA256(base64url(payload), key))>
```

The payload:

| Field | Type | Value |
| --- | --- | --- |
| `credPk` | string | Your API key, exactly as you pass it in `authorize.apiKey` |
| `entityId` | string | The account the editor works for. Use the same value as `authorize.entityId`; usage is attributed to it |
| `exp` | integer | Expiry in whole Unix seconds. Topol rejects a nonce once `exp` has passed but sets no upper limit, so keep it **at most one hour** from now |

`userId` is still accepted in the payload as a deprecated alias of `entityId` until the next major version; if both are present, `entityId` wins.

The signing `key` is the SHA-256 hex digest of your Secret key: `sha256_hex("sk_…")`. If your Secret key doesn't start with `sk_` (keys issued before the prefix existed), add `sk_` in front of it before hashing. Base64url means URL-safe Base64 without `=` padding.

Expose the nonce from an endpoint that only answers signed-in users:

**Node.js**

```js
import { createHash, createHmac } from "node:crypto";

const API_KEY = process.env.TOPOL_API_KEY;
const SECRET_KEY = process.env.TOPOL_SECRET_KEY;

function signTopolNonce(entityId) {
  const secret = SECRET_KEY.startsWith("sk_") ? SECRET_KEY : `sk_${SECRET_KEY}`;
  const key = createHash("sha256").update(secret).digest("hex");
  const payload = {
    credPk: API_KEY,
    entityId: String(entityId),
    exp: Math.floor(Date.now() / 1000) + 3600,
  };
  const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
  const signature = createHmac("sha256", key).update(body).digest("base64url");
  return `nc_${body}.${signature}`;
}

app.post("/api/topol/nonce", requireLogin, (req, res) => {
  res.json({ nonce: signTopolNonce(req.user.id) });
});
```

**PHP**

```php
function base64url(string $data): string
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function signTopolNonce(string $entityId): string
{
    $secret = getenv('TOPOL_SECRET_KEY');
    if (!str_starts_with($secret, 'sk_')) {
        $secret = 'sk_' . $secret;
    }
    $key = hash('sha256', $secret); // hex digest
    $payload = [
        'credPk' => getenv('TOPOL_API_KEY'),
        'entityId' => $entityId,
        'exp' => time() + 3600,
    ];
    $body = base64url(json_encode($payload));
    $signature = base64url(hash_hmac('sha256', $body, $key, true));

    return "nc_{$body}.{$signature}";
}

// POST /api/topol/nonce, for signed-in users only
header('Content-Type: application/json');
echo json_encode(['nonce' => signTopolNonce((string) $currentUser->id)]);
```

> **WARNING**
>
> Never send the Secret key to the browser, and never sign nonces in the browser. Your endpoint should sign nonces only for the user who is signed in.

## Step 2: Pass `getNonce` to the editor

Your API key stays in `authorize`. Add `getNonce` next to your other callbacks; it must resolve to the `nc_…` string.

> **Without authorize.apiKey**
>
> Without `authorize.apiKey`
>
> With `getNonce` you can leave `authorize.apiKey` out (cloud mode still needs it). The nonce then names your credential everywhere, and the built-in image storage keeps one folder per end user: the `entityId` the nonce was signed for. Sign it for the same `entityId` you pass in `authorize`. Images uploaded earlier with the API key stay in the same folder.

**Script tag**

```js
const editor = TopolEmailEditor({
  config: {
    authorize: {
      apiKey: "YOUR_API_KEY",
      entityId: "user-123",
    },
  },
  async getNonce() {
    const response = await fetch("/api/topol/nonce", { method: "POST" });
    if (!response.ok) throw new Error("Could not get a Topol nonce");
    return (await response.json()).nonce;
  },
  onEditorError({ source, message }) {
    console.error(source, message);
  },
});

editor.render("#app");
```

**@topol.io/editor**

```ts
import { EmailEditor } from "@topol.io/editor";

const editor = await EmailEditor.init({
  config: {
    authorize: { apiKey: "YOUR_API_KEY", entityId: "user-123" },
  },
  async getNonce() {
    const response = await fetch("/api/topol/nonce", { method: "POST" });
    if (!response.ok) throw new Error("Could not get a Topol nonce");
    return (await response.json()).nonce;
  },
});

await editor.render("#app");
```

**React**

```tsx
import { EmailEditor } from "@topol.io/editor-react";

async function getNonce() {
  const response = await fetch("/api/topol/nonce", { method: "POST" });
  if (!response.ok) throw new Error("Could not get a Topol nonce");
  return (await response.json()).nonce;
}

export function Editor() {
  return (
    <EmailEditor
      options={{ authorize: { apiKey: "YOUR_API_KEY", entityId: "user-123" } }}
      getNonce={getNonce}
    />
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { EmailEditor, type IEmailCallbacks } from "@topol.io/editor-vue";

const options = { authorize: { apiKey: "YOUR_API_KEY", entityId: "user-123" } };
const callbacks: IEmailCallbacks = {
  async getNonce() {
    const response = await fetch("/api/topol/nonce", { method: "POST" });
    if (!response.ok) throw new Error("Could not get a Topol nonce");
    return (await response.json()).nonce;
  },
};
</script>

<template>
  <EmailEditor :options="options" :callbacks="callbacks" />
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import { EmailEditor } from "@topol.io/editor-svelte";

  const options = { authorize: { apiKey: "YOUR_API_KEY", entityId: "user-123" } };

  async function getNonce() {
    const response = await fetch("/api/topol/nonce", { method: "POST" });
    if (!response.ok) throw new Error("Could not get a Topol nonce");
    return (await response.json()).nonce;
  }
</script>

<EmailEditor {options} {getNonce} />
```

In Vue, pass `getNonce` through the `callbacks` prop: event listeners can't return a value to the editor. In React and Svelte it is a prop like any other callback.

`getNonce` is the only callback whose resolved value the editor reads.

## Refresh and errors

-   **Refresh before expiry.** The editor reads `exp` from the nonce and calls `getNonce` again at about 80 % of its lifetime, so an open editor is not interrupted.
-   **One retry.** If Topol rejects a nonce, for example after you rotated the Secret key, the editor gets a new one and retries the request once.
-   **Timeout.** A `getNonce` call that doesn't finish within 15 seconds counts as failed.
-   **Errors.** If the first nonce can't be obtained, the editor doesn't start and calls `onEditorError` with `source: "authorize"`. If a later refresh fails, it calls `onEditorError` with `source: "nonceAuth"` and keeps working with the last nonce until it expires.

## Revoking access

Topol doesn't store nonces; it checks each one against your current Secret key. Rotating the Secret key in your [Topol Account](https://app.topol.io) invalidates every nonce signed with the old one, and revoking the API token rejects its nonces immediately, however long they still have to live.
