# Node (server)

> Create and manage links and send purchase events from your backend. Zero dependencies; authenticates with your secret key.

- You need: Node.js 18 or newer, and a secret key from Dashboard → Settings → Keys

Source: https://straitlink.in/docs/sdks/node/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

## Install

Install it from npm, pinned to a version:

```bash
npm install @straitlink/node@0.8.2
```



## Create the client

```ts
import { StraitClient } from '@straitlink/node';

const links = new StraitClient({
  apiKey: process.env.SECRET_KEY!,   // st_live_… from Dashboard → Settings → Keys
  baseUrl: 'https://strait.link',
});

console.log((await links.listLinks()).length, 'links');
```

**You should see:** a number and `links`, such as `0 links` in a new workspace. A `StraitError` with status 401 means the key is wrong or is a publishable key.

## Handle deep links

A server doesn't open links: it creates them, and hears about every tap and open through [webhooks](https://straitlink.in/docs/webhooks/) (`link.clicked`, `app.opened`).

```ts
// Create a link
const link = await links.createLink({
  slug: 'launch',
  longUrl: 'https://yourapp.com/launch',
  tags: ['campaign'],
});

// List / update / deactivate
await links.listLinks();
await links.updateLink('launch', { longUrl: 'https://yourapp.com/launch-v2' });
await links.deleteLink('launch');
```

## Deferred deep links

Deferred matching happens in the app, through the app SDKs. Your server hears about each match as an `install.matched` [webhook](https://straitlink.in/docs/webhooks/), with the link and the tap id (`clickId`).

## Events

```ts
// Send a conversion / revenue event (no publishable key needed server-side)
await links.sendEvent({ event: 'purchase', value: 49.99, currency: 'USD' });

// Name the tap it came from, when you know it (for example from a webhook)
const clickId = '9a1c7e52-4b3d-4f8e-a6d1-0c2b5e7f9a34'; // clickId from an app.opened or install.matched webhook
await links.sendEvent({ event: 'purchase', value: 49.99, currency: 'USD', clickId });
```

On a server nothing is remembered for you: `sendEvent` passes `clickId` through only when you give it. Use a tap id you received, such as `clickId` from an `app.opened` or `install.matched` webhook. The server keeps it only if it's a tap of your workspace; otherwise it drops the id and still records the event.

Failures throw a `StraitError` with `.status` and the parsed `.body`.

## Verify a webhook

`verifyWebhook` (version 0.6.5 and later) checks that a [webhook](https://straitlink.in/docs/webhooks/) delivery came from Strait: the `X-Strait-Signature` HMAC of the timestamp and the raw body, compared in constant time, and no more than 5 minutes old. Pass the **raw** body, before any JSON parsing.

```ts title="Express"
import express from 'express';
import { verifyWebhook } from '@straitlink/node';

const app = express();

app.post('/webhooks/strait', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhook(req.body, req.headers, process.env.WEBHOOK_SECRET!)) return res.status(401).end();
  const delivery = JSON.parse(req.body.toString('utf8')); // { id, event, createdAt, data }
  // handle delivery.event / delivery.data …
  res.status(204).end();
});
```

It also takes a fetch `Headers` and a string body, for example `verifyWebhook(await request.text(), request.headers, secret)` in a route handler. To allow more clock drift, pass `{ toleranceSeconds: 600 }`.

**You should see:** press **Send test event** next to the webhook in Dashboard → Settings → Webhooks, and the dashboard shows `204` from your server. With a wrong secret it shows `401`.

> **Keep the secret key on the server**
>
> The secret key can create and change links. Store it in an environment variable and never ship it in an app, a web page or a public repository. If it leaks, revoke it in the dashboard and create a new one.

## Methods

| Method | Endpoint |
|---|---|
| `createLink(input)` | [`POST /v1/links`](https://straitlink.in/docs/api/create-link/) |
| `listLinks()` | [`GET /v1/links`](https://straitlink.in/docs/api/list-links/) |
| `updateLink(slug, fields)` | [`PATCH /v1/links/:slug`](https://straitlink.in/docs/api/update-link/) |
| `deleteLink(slug)` | [`DELETE /v1/links/:slug`](https://straitlink.in/docs/api/deactivate-link/) |
| `sendEvent(input)` | [`POST /v1/event`](https://straitlink.in/docs/api/send-event/) |
| `verifyWebhook(rawBody, headers, secret, opts?)` | No request: checks a [webhook](https://straitlink.in/docs/webhooks/) signature |

Full request and response details are in the [REST API reference](https://straitlink.in/docs/api/).

## Common errors

- **`StraitClient: apiKey is required` or `baseUrl must use https://`.** The constructor checks both. Plain `http` works only for `localhost`, `127.0.0.1` and `::1`.
- **`StraitError` with `status` 401.** The key is wrong, revoked, or a publishable key. The link API needs a secret key.
- **`StraitError` with `status` 402.** A plan limit: `.body.reason` is `links` (new links this month) or `clicks` (taps this month). Links you already have keep working.
- **`verifyWebhook: pass the raw request body`.** The body was already parsed as JSON. Use `express.raw()` on the webhook route instead of `express.json()`.
- **Any other `StraitError`.** `.message` is the API's `error`; every one is in the [Error reference](https://straitlink.in/docs/errors/).
