---
title: "TogoHq.Sdk"
description: "Every method and option of the .NET server SDK, and the Azure Functions middleware that sends events before an invocation returns."
canonical: "https://www-stage.togohq.ai/docs/reference/sdk-dotnet"
applies_to: "TogoHq.Sdk 1.x"
updated: "2026-11-24T00:00:00Z"
---

# TogoHq.Sdk

Every method and option of the .NET server SDK, and the Azure Functions middleware that sends events before an invocation returns.

```bash
dotnet add package TogoHq.Sdk                    # any .NET 8+ process
dotnet add package TogoHq.Sdk.Functions.Worker   # Azure Functions, isolated worker
```

.NET 8 or later. `TogoHq.Sdk` has no dependencies; `TogoHq.Sdk.Functions.Worker` depends on it and
on Microsoft's Azure Functions worker core package, which NuGet installs with it. Use **one client per process**, shared by every request.
Nothing on the client throws: a problem is logged as `[togo] …` and the event is retried or dropped.
A guide to using it: [.NET and Azure Functions](/docs/dotnet).

## `new TogoClient(options)`

```csharp
using TogoHq.Sdk;

await using var togo = new TogoClient(new TogoClientOptions { WriteKey = writeKey });
```

## Options

| `TogoClientOptions` | Default                | What it does                                                                                                   |
| ------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `WriteKey`          | —                      | Required. `togo_pkt_…` (test) or `togo_pkl_…` (live). Spaces and a newline around it are ignored               |
| `Endpoint`          | `https://in.togohq.ai` | Where events are sent. Not an `https://` URL, or one that redirects: nothing is sent, with an error            |
| `BatchSize`         | `100`                  | Events per request, 100 to 500                                                                                 |
| `FlushInterval`     | 10 seconds             | How long an event may wait before it is sent, 10 to 60 seconds                                                 |
| `MaxQueueSize`      | `10000`                | Events held in memory while Togo is unreachable, with 32 MiB; past either, the oldest are dropped and reported |
| `DefaultProperties` | —                      | Properties on every `Track` event, such as `service = "billing"`                                               |
| `Log`               | standard error         | Where `[togo] …` lines go; the Functions package uses `ILogger`                                                |
| `OnError`           | —                      | Called for every event, or part of one, that will not be recorded. See [`OnError`](#onerror)                   |
| `AppVersion`        | —                      | Your service's version, such as `"2.4.0"`. Read as `$app_version`, so a chart splits by release                |
| `AppBuild`          | —                      | Your service's build, such as `"412"`. Read as `$app_build`                                                    |

`AppVersion` and `AppBuild` are each 1–64 characters; a value that is not is left out, and the SDK
logs one error. The SDK never reads them from your assembly: set them, or nothing is sent.

A `BatchSize` or `FlushInterval` outside its range is moved into it, with a warning in your logs.
To send an event at once, `await togo.FlushAsync()` after it rather than lowering either.

`DefaultProperties` is fixed when the client is created, because a client shared by every request
must not carry one request's value onto the next. An event's own value for the same key wins, and
the SDK logs one error for the collision.

Property names starting with `$` are reserved for Togo
([Reserved properties](/docs/reference/reserved-properties)), and a name longer than 255 characters,
or holding a control character or an email address, is one Togo cannot use. The SDK reports either
through [`OnError`](#onerror) and logs an error naming it. With a live key it drops the property
from a `Track` call, from `DefaultProperties` and from `SetPersonProperties`, and sends the rest;
with a test key it sends the property as well, so `verify_tracking` reports it with its fix.

A string value longer than 1,024 characters is cut to its first 1,024 and the event is still sent,
and past 256 properties the first 256 in sort order are kept. Both are reported through
[`OnError`](#onerror); with a test key the value or the properties are sent whole, so
`verify_tracking` shows what Togo keeps.

## The person argument

Every call names who it is about with a `TogoPerson`, which has at least one of:

| Member        | What it is                                                                        |
| ------------- | --------------------------------------------------------------------------------- |
| `UserId`      | Your id for the signed-in user — the same one the browser passes to `identify()`  |
| `AnonymousId` | The browser's anonymous id, forwarded, for a visitor who has not signed in        |
| `SessionId`   | Optional. Pass only the browser's `getSessionId()`, so the event joins that visit |

`TogoPerson.User(id)` and `TogoPerson.Anonymous(id)` build the common cases. An event
with neither `UserId` nor `AnonymousId` is dropped with an error. Server events carry no device,
browser or location.

## `Track(eventName, properties, person)`

```csharp
togo.Track("order_paid", new Dictionary<string, object?> { ["plan"] = "pro" }, TogoPerson.User(userId));
```

A property value is a `string`, a `bool`, a number or `null`, with nothing nested. An event with any
other type of value, such as a `DateTime` or an enum, is dropped with an error naming the property:
convert it yourself. `Track(eventName, person)` sends an event with no properties.

Returns the event's `eventId`, or `null` when nothing was queued — no person named, a refused name,
an unsupported value, a malformed write key or one already rejected, after disposal, or a full
queue. An id means the event was queued, not that it arrived. A test passes these ids to
[`verify_tracking_by_event_ids`](/docs/reference/mcp-tools#verify_tracking_by_event_ids) after
`await togo.FlushAsync()`.

## `SetPersonProperties(update, person)`

```csharp
togo.SetPersonProperties(
    new PersonPropertyUpdate { Email = user.Email, Set = new Dictionary<string, object?> { ["plan"] = "pro" } },
    TogoPerson.User(userId));
```

`Email`, `Name`, `Set`, `SetOnce` and `Unset`, as in the browser
([Set person properties](/docs/guides/person-properties)): `Email` and `Name` set the reserved
person properties `$email` and `$name`, and assigning `null` to one removes it. Set them there, never
as an `email` or `name` key in `Set`, which the server drops. A `SessionId` on the person is
ignored. Returns the profile write's `eventId`, or `null` when nothing was queued.

## `FlushAsync()`

`await togo.FlushAsync()` sends everything queued now. A send that fails on the network or with a
server error is retried twice within about two seconds before the task completes. While Togo has
asked the SDK to wait, after an outage or a rate limit, it sends nothing and returns at once; the
events go when the wait ends. It never throws.

Where `AWS_LAMBDA_FUNCTION_NAME`, `FUNCTIONS_WORKER_RUNTIME`, `VERCEL` or `NETLIFY` is set, the
client logs one warning when its interval timer sends events twice with no `FlushAsync()` call
between: a function that returns with events still queued. Once is not enough, because a function
that runs past the interval and then flushes lets the timer fire once first; `UseTogo()` flushes
every invocation, so it never warns. It is a log line, never an `OnError` call, because nothing was
lost that time.

## `DisposeAsync()`

Sends what is queued and stops the client. A `Track` after it is ignored, with an error in your
logs. A client registered with `AddTogo` is disposed by the host when it shuts down.

## `OnError`

```csharp
services.AddTogo(o =>
{
    o.WriteKey = Environment.GetEnvironmentVariable("TOGO_WRITE_KEY")!;
    o.OnError = error => SentrySdk.CaptureMessage(error.Message);
});
```

Pass it to the error tracker your service already uses. It is called once for every event that
will not be recorded, or value dropped from one, and once when the client stops sending. Your logs
still show every one. It receives a `TogoError`: `Code`, `Message`, `EventIds`, `EventName` and
`Property` (the property's name when the report is about one, never its value), with
the same codes as the [Node.js SDK's](/docs/reference/sdk-node#onerror), listed in `TogoErrorCodes`.
It runs on the thread pool after the call that caused it has returned, and whatever it throws is
logged. `FlushAsync()`, and so `UseTogo()`, wait up to 2 seconds for it to finish, so a function
still reports before it returns. Treat a code you do not recognise as a lost event.

Two codes only the .NET SDK sends:

| `Code`                   | What was lost                                                                                                   |
| ------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `property_value_invalid` | The event: a property value was not a string, bool, number or `null`, such as a `DateTime`. Convert it yourself |
| `client_config_invalid`  | Everything: `Endpoint` is not an `https://` URL, or a `DefaultProperties` value has such a type                 |

## Azure Functions: `UseTogo()` and `AddTogo()`

```csharp
using TogoHq.Sdk.Functions.Worker;

var builder = FunctionsApplication.CreateBuilder(args);
builder.UseTogo();
builder.Services.AddTogo(o => o.WriteKey = Environment.GetEnvironmentVariable("TOGO_WRITE_KEY")!);
builder.Build().Run();
```

`UseTogo()` adds a middleware that sends what each invocation tracked before the invocation
completes, also when the function throws; the function's result or exception is unchanged. It waits
at most 5 seconds for the send: if Togo cannot be reached, the response goes out and the events stay
queued for a retry. To change the limit, or to add it where you configure the worker defaults:

```csharp
builder.UseTogo(o => o.FlushTimeout = TimeSpan.FromSeconds(2));
// or
ConfigureFunctionsWorkerDefaults(worker => worker.UseTogo());
```

`AddTogo()` registers one shared client as `ITogoClient`, and an overload passes the
`IServiceProvider` so the key can come from configuration.

## Delivery

Events are batched and retried with backoff when the endpoint is unreachable or busy, keeping the
same event id across attempts.
