Skip to content
How-to guides Guides

Guides

Task-oriented recipes for managing cloud browser profiles, human handoffs, live views, downloads, usage exports, browser-scoped keys, signed webhooks and offline tests with Klyroo.Hotkey. Each recipe states its goal, shows complete code and notes the edge cases. For initial setup, see Getting started.

On this page

Provision and reuse one browser per user

Goal: keep one persistent cloud browser per authenticated user without creating duplicates on concurrent requests or retries.

Pass your stable user ID as BrowserCreate.ExternalId and a persisted operation key as idempotencyKey, then store the returned HotkeyBrowser.Id in your own user directory:

C#
var browser = await hotkey.GetOrCreateBrowserAsync(
    new BrowserCreate(
        ExternalId: userId,
        TimeZone: "Europe/Paris",
        Languages: ["fr-FR"],
        Metadata: new Dictionary<string, string> { ["tenant"] = tenantId }),
    idempotencyKey: provisioningOperationId,
    cancellationToken: cancellationToken);

When Hotkey responds with 409 Conflict (browser_exists) and ExistingBrowserId, GetOrCreateBrowserAsync fetches that browser with GetBrowserAsync and verifies that existing.ExternalId == settings.ExternalId before returning it. If the external ID no longer matches, it throws InvalidDataException instead of silently linking the wrong browser.

To list or page through all browsers in a workspace with filters, use ListBrowsersAsync for a single page or EnumerateBrowsersAsync to follow cursors automatically:

C#
var filter = new BrowserFilter(
    State: "awake",
    Metadata: new Dictionary<string, string> { ["tenant"] = tenantId });

await foreach (var active in hotkey.EnumerateBrowsersAsync(filter, cancellationToken))
{
    Console.WriteLine($"{active.Id} ({active.ExternalId}): {active.WaitingAsks} waiting ask(s)");
}

Manage browser lifecycle, locale and tabs

Goal: wake a sleeping browser before running work, update its locale or metadata, inspect open tabs, and put it back to sleep when idle.

C#
// Wake the browser before automating or requesting a handoff on an existing tab.
var awake = await hotkey.WakeBrowserAsync(browserId, $"wake:{operationId}", cancellationToken);

// Update timezone, accepted languages or metadata. Pass null for a metadata value to clear that key.
var updated = await hotkey.UpdateBrowserAsync(
    browserId,
    new BrowserUpdate(
        TimeZone: "America/New_York",
        Languages: ["en-US", "fr-FR"],
        Metadata: new Dictionary<string, string?> { ["plan"] = "pro", ["legacy_tag"] = null }),
    $"update:{operationId}",
    cancellationToken);

// Inspect open tabs to choose a tab number for a handoff.
var tabs = await hotkey.ListTabsAsync(browserId, limit: 25, cancellationToken: cancellationToken);
foreach (var tab in tabs.Data)
{
    Console.WriteLine($"Tab {tab.Id}: {tab.Title} ({tab.Url}) [{tab.State}]");
}

// Put the browser to sleep when the job finishes, or delete it when offboarding a user.
await hotkey.SleepBrowserAsync(browserId, $"sleep:{operationId}", cancellationToken);

DeleteBrowserAsync(browserId) is never retried automatically; check HotkeyBrowserDeletion.Deleted and remove the browser mapping from your database once deleted.

Goal: let the authorized user complete a login, MFA challenge or approval step in their own browser session without sharing credentials with your backend.

Resolve browserId from your server-side user mapping, then call CreateAskAsync. Provide either a positive Tab number or an absolute HTTP/HTTPS Url without embedded credentials — never both:

C#
var ask = await hotkey.CreateAskAsync(
    new AskCreate(
        Browser: browserId,
        Reason: "Confirm the wire transfer in your banking portal",
        Url: new Uri("https://bank.example.com/approvals"),
        TimeoutMinutes: 15,
        ReturnUrl: new Uri("https://app.example.com/transfers/pending"),
        SaveSignIn: true),
    idempotencyKey: handoffOperationId,
    cancellationToken: cancellationToken);
  • Deliver ask.Link only to the authenticated user who owns browserId. Never log ask.Link (the HotkeyAsk class is not a record, so ToString() does not print the link).
  • Renew an expired link while the ask is still pending: var renewed = await hotkey.RenewAskLinkAsync(ask.Id, renewOperationId, cancellationToken);. Renewing invalidates the previous link.
  • Cancel an open ask if the user abandons the flow: await hotkey.CancelAskAsync(ask.Id, note: "Cancelled by operator", cancelOperationId, cancellationToken);.
  • Inspect or forget saved sign-ins when a user disconnects an integration:
C#
var signIns = await hotkey.ListSignInsAsync(browserId, limit: 50, cancellationToken: cancellationToken);
foreach (var entry in signIns.Data)
{
    if (entry.Site.Equals("bank.example.com", StringComparison.OrdinalIgnoreCase))
        await hotkey.ForgetSignInAsync(browserId, entry.Id, cancellationToken);
}

Verify and deduplicate signed webhook deliveries

Goal: authenticate incoming Hotkey deliveries before JSON parsing and ensure duplicate deliveries never advance a workflow twice.

Read the raw HTTP request bytes before any JSON binder touches the body, then pass them with Hotkey-Signature and your webhook endpoint secret to HotkeyWebhook.VerifyAndRead:

C#
app.MapPost("/webhooks/hotkey", async (
    HttpRequest request,
    IConfiguration config,
    IWorkflowQueue queue,
    CancellationToken cancellationToken) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer, cancellationToken);

    var signature = request.Headers["Hotkey-Signature"].ToString();
    var secret = config["Hotkey:WebhookSecret"]
        ?? throw new InvalidOperationException("Missing Hotkey:WebhookSecret.");

    var delivery = HotkeyWebhook.VerifyAndRead(buffer.ToArray(), signature, secret);
    if (delivery is null)
        return Results.Unauthorized();

    // Deduplicate on delivery.Id in durable storage (e.g., UNIQUE index on webhook_events.id).
    var inserted = await queue.TryEnqueueOnceAsync(delivery, cancellationToken);
    return Results.Ok(new { accepted = true, duplicate = !inserted });
});

VerifyAndRead returns null if:

  • Hotkey-Signature does not match t=<unix_seconds>,v1=<64_hex_chars>.
  • The timestamp is more than 300 seconds (5 minutes) behind or ahead of now.
  • The HMAC-SHA256 digest over "<timestamp>." + rawBody fails a constant-time comparison (CryptographicOperations.FixedTimeEquals).
  • The JSON body is invalid or lacks a non-empty id or type.

Always return a 2xx status as soon as delivery.Id is durably recorded, and run slow downstream work in a background worker.

Manage webhook endpoints programmatically

Goal: register, inspect, rotate or remove webhook endpoints from deployment tooling or an admin service.

C#
var endpoint = await hotkey.CreateWebhookEndpointAsync(
    new WebhookEndpointSettings(
        Url: new Uri("https://api.example.com/webhooks/hotkey"),
        Events: ["ask.done", "ask.expired", "ask.cancelled", "download.ready"],
        Description: "Production workflow receiver"),
    idempotencyKey: "webhook:prod-v1",
    cancellationToken: cancellationToken);

// Store endpoint.Secret in your secret manager immediately; it is returned on creation.

Webhook URLs are validated client-side before sending: they must use https:// with no embedded credentials (user:pass@) and no #fragment. Use ListWebhookEndpointsAsync, GetWebhookEndpointAsync, UpdateWebhookEndpointAsync and DeleteWebhookEndpointAsync to manage existing endpoints.

Configure origins and embed a live view

Goal: show an authorized browser inside your web app for read-only observation or interactive takeover.

First allow your application origin on the Hotkey workspace, then mint a short-lived embed for the user's browser:

C#
await hotkey.UpdateWorkspaceAsync(
    new WorkspaceUpdate(EmbedOrigins: ["https://app.example.com"]),
    idempotencyKey: "workspace:embed-origins:v1",
    cancellationToken: cancellationToken);

var embed = await hotkey.CreateEmbedAsync(
    browserId,
    new EmbedCreate(
        Origins: ["https://app.example.com"],
        Sites: ["reports.example.com"],
        ExpiresIn: 600,
        Mode: "view"),
    cancellationToken);
  • Mode defaults to "view" (read-only); pass "interact" only when the user is authorized to control the remote browser.
  • ExpiresIn must be between 30 and 86400 seconds, and Sites accepts at most 3 entries.
  • CreateEmbedAsync is never automatically retried because every call mints a new token.
  • Call RevokeEmbedAsync(embed.Id) as soon as the user closes the modal or signs out.

See the Hotkey embed contract for iframe attributes and origin enforcement.

Stream browser downloads and usage exports

Goal: copy files captured in a cloud browser (such as generated PDFs or CSV exports) or workspace usage reports into durable storage without buffering whole files in memory.

C#
var downloads = await hotkey.ListDownloadsAsync(browserId, limit: 20, cancellationToken: cancellationToken);
foreach (var file in downloads.Data)
{
    var tempPath = Path.Combine(downloadDir, $"{file.Id}.part");
    var finalPath = Path.Combine(downloadDir, $"{file.Id}.bin");
    try
    {
        await using (var output = File.Create(tempPath))
        {
            await hotkey.CopyDownloadToAsync(file.Id, output, cancellationToken);
        }
        File.Move(tempPath, finalPath, overwrite: true);
    }
    catch
    {
        if (File.Exists(tempPath)) File.Delete(tempPath);
        throw;
    }
}

Writing to a .part file first protects against interrupted transfers, because CopyDownloadToAsync and CopyUsageCsvToAsync leave the destination stream open and can leave partial bytes if the connection drops mid-stream.

To query structured usage metrics or export usage as CSV:

C#
var usage = await hotkey.GetUsageAsync(
    from: new DateOnly(2026, 11, 1),
    to: new DateOnly(2026, 11, 30),
    groupByExternalId: true,
    cancellationToken: cancellationToken);

await using var csv = File.Create("usage-november.csv");
await hotkey.CopyUsageCsvToAsync(csv, from: new DateOnly(2026, 11, 1), to: new DateOnly(2026, 11, 30), cancellationToken: cancellationToken);

Issue and revoke browser-scoped agent keys

Goal: enforce least privilege so a worker running automation for one user cannot access any other user's browser or workspace settings.

Keep your workspace API key restricted to the provisioning service. For per-user workers, mint a browser-scoped key and revoke it when the session or integration ends:

C#
var scopedKey = await hotkey.CreateBrowserAgentKeyAsync(
    browserId,
    name: $"user-{userId}-sync-worker",
    idempotencyKey: keyOperationId,
    cancellationToken: cancellationToken);

// Pass scopedKey.Secret to a per-user worker HttpClient (never log it or send it to a browser client).
// Later, when revoking access:
await hotkey.RevokeAgentKeyAsync(scopedKey.Id, cancellationToken);

Handle rate limits and transient errors

Goal: distinguish short transient faults (which HotkeyClient retries automatically) from longer rate limits or domain conflicts that your job queue should handle.

C#
try
{
    var ask = await hotkey.CreateAskAsync(settings, idempotencyKey, cancellationToken);
}
catch (HotkeyException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests && ex.RetryAfter is { } wait)
{
    // Hotkey asked for > 30s; reschedule in your background queue instead of blocking the request thread.
    await jobQueue.ScheduleRetryAsync(jobId, delay: wait, cancellationToken);
}
catch (HotkeyException ex)
{
    logger.LogWarning(ex, "Hotkey call failed with {Code} (HTTP {Status}, Request-Id {RequestId})",
        ex.Code, ex.StatusCode, ex.RequestId);
    throw;
}

Test workflows without network calls

Goal: unit test browser provisioning, conflict recovery, error handling and webhook verification deterministically with zero network traffic.

HotkeyClient takes a plain HttpClient, so tests inject an HttpMessageHandler stub; HotkeyWebhook.VerifyAndRead accepts an explicit now clock:

C#
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Klyroo.Hotkey;

using var http = new HttpClient(new StubHandler((req, _) =>
    Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("""{"id":"brw_1","external_id":"user_1","state":"awake"}""", Encoding.UTF8, "application/json")
    })));

var client = new HotkeyClient(http, "hk_test_key");
var browser = await client.GetBrowserAsync("brw_1");

var now = DateTimeOffset.FromUnixTimeSeconds(1_800_000_000);
var rawBody = """{"id":"evt_1","type":"ask.done","created":"2026-11-28T12:00:00Z","data":{}}"""u8.ToArray();
var signingInput = Encoding.UTF8.GetBytes("1800000000.").Concat(rawBody).ToArray();
var sig = "t=1800000000,v1=" + Convert.ToHexStringLower(HMACSHA256.HashData("whsec_test"u8, signingInput));

var verified = HotkeyWebhook.VerifyAndRead(rawBody, sig, "whsec_test", now);
Assert.Equal("evt_1", verified?.Id);