Skip to docs content
Browse documentation
On this page

Server JavaScript SDK

Send events, identify people, and update insights from your server.

Server JavaScript SDK

The server entry point lives in the same @getbutters/js package as the browser SDK . Import Butters from @getbutters/js/server in Node, Bun, or server-side application code with native fetch support.

Install

Version 0.2.0 includes the browser, server, and feedback entry points. Install it from npm:

npm install @getbutters/js@^0.2.0

Create a client

import { Butters } from '@getbutters/js/server'

const butters = new Butters({
  key: process.env.BUTTERS_API_KEY, // secret ev_… key, server environment only
  project: process.env.BUTTERS_PROJECT_ID,
  // host: 'https://app.getbutters.com', // default
  // timeoutMs: 10_000, // default, includes reading the response
})

Use a secret key from the API page. Publishable keys (pk_…) are refused by this client. Keep credentials in server environment variables. In Next.js, do not use NEXT_PUBLIC_ variables for the key or import the client into a component with 'use client'.

Track events and identify people

await butters.identify('user_123', { plan: 'pro' })
const event = await butters.track('billing', 'Plan upgraded', {
  user_id: 'user_123',
  description: 'Upgraded to **Pro**',
  tags: { plan: 'pro' },
  metadata: { amount: 4900 },
  notify: true,
})
console.log(event.id)

track(category, title, fields?) returns the created event. Fields include description, icon, tags, metadata, url, user_id, notify, and created_at (Unix seconds). identify(userId, properties?) returns { ok: true }.

Pass user_id on each event. identify() does not set an implicit user for later calls, so sharing one client between simultaneous requests does not mix users. The client has no browser storage or automatic pageviews.

Set and increment insights

await butters.setInsight('Queue depth', 10, '📈')
await butters.incrementInsight('Queue depth', -1)

setInsight(title, value, icon?) creates or replaces a card's value. incrementInsight(title, amount, icon?) adds a finite number atomically, creating the card if needed. Both return { ok: true }. See Insights and Counters for limits and examples.

Astro server setup

For an Astro application, use on-demand rendering with the Node adapter. Add the Node adapter to your site with npx astro add node and configure server output in astro.config.mjs:

import { defineConfig } from 'astro/config'
import node from '@astrojs/node'

export default defineConfig({
  output: 'server',
  adapter: node({ mode: 'standalone' }),
})

Keep your existing integrations when editing the configuration. Set BUTTERS_API_KEY and BUTTERS_PROJECT_ID in .env for development and in your hosting environment for production. Neither variable should have the PUBLIC_ prefix.

Create src/lib/butters.server.ts. Read credentials through Astro's server environment API inside the request lifecycle:

import { getSecret } from 'astro:env/server'
import { Butters } from '@getbutters/js/server'

export function createButters() {
  const key = getSecret('BUTTERS_API_KEY')
  const project = getSecret('BUTTERS_PROJECT_ID')
  if (!key || !project) throw new Error('Butters server credentials are missing')
  return new Butters({ key, project })
}

Use the client in an endpoint, Astro action, or server-rendered frontmatter. For a temporary integration test, create src/pages/api/butters-test.ts:

import type { APIRoute } from 'astro'
import { createButters } from '../../lib/butters.server'

export const prerender = false

export const POST: APIRoute = async () => {
  const butters = createButters()
  const event = await butters.track('integration', 'Astro server connected', {
    notify: false,
  })
  return Response.json({ eventId: event.id })
}

Send a POST to /api/butters-test and check your project's Feed. Remove the test endpoint afterward. In production, record events after your app's normal authentication and business logic, and get user_id from the trusted server session. Await SDK calls before responding. Avoid tracking from prerendered frontmatter, which runs at build time.

This server example targets Astro's Node adapter. Use the browser feedback component on static Astro sites as well as server-rendered sites.

See Astro's server environment API for runtime secret configuration.

Next.js server usage

Store your credentials in .env.local:

BUTTERS_API_KEY=ev_YOUR_SECRET_KEY
BUTTERS_PROJECT_ID=YOUR_PROJECT_ID

Create lib/butters.ts as a server module:

import 'server-only'
import { Butters } from '@getbutters/js/server'

export const butters = new Butters({
  key: process.env.BUTTERS_API_KEY!,
  project: process.env.BUTTERS_PROJECT_ID!,
})

Import this client from a route handler or server action. Authenticate the caller using your application's normal checks before recording user actions. Await requests before returning, especially on serverless hosts. Use the authenticated user ID from your own application:

import { butters } from '@/lib/butters'

// After your app has authenticated the caller:
await butters.track('billing', 'Invoice paid', {
  user_id: authenticatedUser.id,
  metadata: { invoice_id: invoice.id },
})

Verify the integration

Send a test event from a server script with your environment variables loaded:

await butters.track('integration', 'Server SDK connected', { notify: false })

Open the configured project's Feed and check for Server SDK connected. Set Queue depth to 10, increment it by -1, and check that the insight shows 9. A successful identify() updates the person's profile; it does not create an event in the feed.

Errors and timeouts

Calls reject on failure. Catch ButtersError for HTTP failures:

import { ButtersError } from '@getbutters/js/server'

try {
  await butters.incrementInsight('Signups', 1)
} catch (error) {
  if (error instanceof ButtersError) {
    console.error(error.status, error.message, error.retryAfter)
  } else {
    throw error // network, timeout, or invalid response
  }
}

retryAfter is the response's Retry-After header, or null. The client does not retry writes automatically: a lost response may follow a successful save, so resending could duplicate an event or increment. Redirects are refused. Requests time out after 10 seconds by default.

  • Invalid API key (401): check the key and its team.
  • Project not found (404): check the configured project ID and team.
  • 402 response: check the team's event allowance.
  • Insight value must be numeric to increment (400): set a numeric value before incrementing.

See API Reference for field limits and endpoint responses.