# Sending Logs: React Native

`@tailcove/react-native` sends logs and JavaScript errors from iOS and Android apps built with React Native or
Expo. It is plain JavaScript with no native module, so it works in Expo (managed and bare) and in bare React Native
0.70 and later.

## The app key

A mobile app cannot keep a secret: anything inside the app binary can be read by someone who downloads it. So mobile
apps do not use the source's ingest token. They use an **app key**, which is public by design:

- It only works for the **app ids** you allow: your iOS bundle id and Android package name, such as `com.acme.shop`,
  or `com.acme.*` for every app under it. With none listed, nothing is accepted.
- It has a **rate limit of its own**, separate from the ingest token's, so a copied key cannot use up your source's
  quota.
- You can rotate or revoke it at any time. Installed apps keep the old key until they update, and their logs are
  refused from then on.

Generate the key and list your app ids under **Mobile apps** in your source's **Settings** tab.

## Install

```bash
npm install @tailcove/react-native @react-native-async-storage/async-storage
```

AsyncStorage is optional. With it, lines written while the phone is offline, or just before a crash, are kept and
sent on the next launch.

## Start the client

Start it once, as early as possible, for example in `index.js` or your root layout:

```ts
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Tailcove } from '@tailcove/react-native';

export const tailcove = Tailcove.init({
    appKey: '<your app key>',
    appId: 'com.acme.shop',
    release: '2.4.0',
    environment: 'production',
    storage: AsyncStorage,
});

tailcove.info('checkout opened', { items: 3 });
tailcove.error('payment failed', { provider: 'stripe' });
```

`Tailcove.instance` is the same client anywhere else in the app. Level helpers: `debug`, `info`, `notice`, `warning`
(`warn` too), `error`, `critical`, `alert`, `emergency`, or `log(level, message, context)`.

`appId` must be one of the app ids allowed for the key. To read it from the device instead of writing it in, use
`expo-application` (`Application.applicationId`) or `react-native-device-info` (`getBundleId()`).

## Errors and crashes

Uncaught JavaScript errors (the red screen in development, a crash in release builds) and promise rejections nothing
handled are reported automatically: an `error` line, or `critical` when the error is fatal, with the exception (class,
message, location and stack) and the last 20 log calls before it as breadcrumbs. Tailcove groups them into
[issues](https://tailcove.dev/docs/issues) like any other error. A fatal error is saved and sent before the app goes down; if the app dies
first, it is sent on the next launch.

```ts
try {
    await placeOrder();
} catch (error) {
    tailcove.captureException(error, { orderId });
}

tailcove.addBreadcrumb('tapped pay'); // a step in the trail, without a line of its own
```

Promise rejections are tracked through Hermes, React Native's default engine. On JavaScriptCore, report them in your
own `.catch()`.

In a release build the stack points into the JavaScript bundle. Tailcove does not apply source maps yet, so keep the
bundle's source map with each release to read a location.

Native crashes, in Swift, Objective-C, Kotlin or Java code, happen outside JavaScript. For those, add the Sentry
React Native SDK and point it at your source's DSN: see [Sentry SDKs](https://tailcove.dev/docs/sending-logs/sentry).

## Users and context

```ts
tailcove.setUser(user.id);            // only the id is sent, never a name or email
tailcove.setContext({ plan: 'pro' }); // on every following line
tailcove.setUser(null);               // on sign-out
```

Every line also carries `app.id` and `app.version`, `os.name` and `os.version`, the device model where React Native
knows it, `environment`, and a `session_id` that is new on each launch, so one session's lines are easy to find
together. The `host` is `ios` or `android`.

## How delivery works

Lines wait in a queue and go out in batches: once `batchSize` lines are waiting (default `50`), `flushIntervalMs`
after the first one (default `5000`), or when the app goes to the background. A line leaves the queue only once
Tailcove has accepted it. When the phone is offline, or Tailcove answers `429` or `5xx`, the batch stays queued and is
tried again with backoff, honouring `Retry-After`. A batch refused for good, for example after the key was revoked, is
dropped and reported to `onError`. At most `maxQueueSize` lines are kept (default `1000`); past that the oldest go
first. The client never throws into your app.

`await tailcove.flush()` sends now; `await tailcove.close()` sends, saves and detaches the error hooks.

## Secrets stay on the phone

Since 0.2.0 the client masks anything that looks like a secret before a line is queued, so it never leaves the device. That covers your own log calls and the errors it reports by itself. The client's own fields (`session_id`, `app`, `os`, `device`) aren't touched.

- A context field whose name says it holds a secret, such as `password`, `db_password`, `apiKey`, `x-api-key`, `client_secret`, `Authorization` or `cookies`, has its whole value replaced with `[redacted]`, nested objects included. `null`, `true` and `false` stay, so `has_password: true` still reads fine.
- In the message and in every other string, the value after a secret name becomes `[redacted]`: `password=hunter2`, `?token=abc123`, `"api_key": "..."`, `Authorization: Bearer ...`. A colon in plain prose doesn't count, so `password: too short` stays as written.
- Credentials you can tell by their shape become `[key]` wherever they appear: JWTs, AWS access key ids, Stripe secret keys, GitHub, Slack and Google API tokens, and private key blocks.

Names that only look similar, like `max_tokens`, `token_count` or `password_changed_at`, aren't touched. The rules are the ones Tailcove uses for [recommended masking](https://tailcove.dev/docs/transform-rules) on the server, so a line reads the same whichever side masked it, and masking twice changes nothing.

Add your own field names with `secretKeys`. Names are compared whole, ignoring case, `-`, `_`, `.` and spaces, so `customer_ssn` also covers `customerSsn` and `Customer-SSN`. Set `maskSecrets` to false only if you mask everything yourself.

`beforeSend` sees each line after masking and can change it or drop it:

```ts
Tailcove.init({
    appKey: '<your app key>',
    appId: 'com.acme.shop',
    secretKeys: ['customer_ssn'],
    beforeSend: (line) => {
        if (line.level === 'debug') return null;
        return line;
    },
});
```

If `beforeSend` throws, the line is still sent, masked as it was, and the error goes to `onError`.

## Options

- `appKey`, `appId` (required)
- `endpoint`: defaults to `https://ingest.tailcove.dev/api/v1/app/logs`
- `storage`: an object with `getItem`, `setItem` and `removeItem`, such as AsyncStorage
- `release`, `environment`, `context`: added to every line
- `batchSize`, `flushIntervalMs`, `maxQueueSize`, `timeoutMs`
- `captureErrors`, `captureRejections`: default `true`
- `traceLimit`: stack frames per error, default `20`
- `enabled`: `false` turns the client off, for example in tests
- `onError`: called when a batch cannot be sent or is refused
- `maskSecrets`: mask secrets before a line is queued, default `true` (see [Secrets stay on the phone](#secrets-stay-on-the-phone))
- `secretKeys`: more field names to treat as secret
- `beforeSend`: called with each line after masking; return the line, changed or not, or `null` to drop it

## Limits

The app key's own rate limit is 600 lines a minute and 200 MB a day per source by default, with a short burst above
it. Over the limit Tailcove answers `429` with `Retry-After`, and the client waits and tries again. Lines sent with the
app key count toward your plan's monthly GB like any other.
