Tripletex API for builders: authentication and session tokens, step by step

Key takeaways:

  1. Internal integrations (one company) use a refresh token from Company > API Tokens and POST /token/session/:createFromRefreshToken. Integrations for many customers need a consumer token from Tripletex plus one employee token per customer, and POST /token/session/:create.

  2. Every API call uses HTTP Basic auth: username 0 (your own company) or a client id, password = the session token.

  3. Create a session token once, cache it, and reuse it until it expires or you get a 401. Token creation is rate limited (180 per minute today, with plans to go toward about 10).

  4. All Tripletex tokens are server-side secrets. They never belong in React, Lovable client code or a VITE_ variable.

To call the Tripletex API from an app built with Lovable, Claude Code or Cursor, you first turn a long-lived token into a short-lived session token, then send that session token with HTTP Basic auth on every request: username 0 (your own company) and password = the session token. Which long-lived token you start from depends on who the integration is for: a refresh token for your own company, or a consumer token plus your customers' employee tokens if you are building for many Tripletex customers. All of this runs on a server, such as a Supabase Edge Function, never in the browser.

This guide is written for builders and for the AI coding agent working with them. Every API detail comes from the official Tripletex API documentation, the OpenAPI spec (version 2.75.23) and the authentication guide on developer.tripletex.no, as of November 2026. The code is based on the official API spec; test it against the Tripletex test environment before production.

Which access path do you need: internal or commercial?

Tripletex has two ways in. Pick the one that matches who will use your app.

Internal integrationCommercial integration
Who it is forOne company (or one company group) connecting its own Tripletex accountAn app used by several Tripletex customers, or by an accounting office
What you getA JWT refresh token (starts with tlxr_)A consumer token (identifies your app) plus one employee token per customer
How you get itA user admin creates it under Company > API Tokens. The account needs the Integrations module. No application to Tripletex.Apply to Tripletex through their form. Tripletex says to expect a reply within 2 to 3 weeks.
Session callPOST /token/session/:createFromRefreshTokenPOST /token/session/:create

Most apps built for one business use the internal path. If you are building a product you will sell to other Tripletex users, you need the commercial path, and you should read the Tripletex developer terms first. Details are on the getting started page.

Step 1: How do you create the token in Tripletex?

Internal: a user with user admin rights opens Company > API Tokens and generates a token. The secret is shown only once, so copy it straight into your server's secret store.

Commercial: after approval, Tripletex emails you the consumer token and your application name. Each customer then creates an employee token in their own Tripletex under the API access tab: they choose New token, pick your integration from the dropdown (or use Adapted setup and type your application name, which is case-sensitive), and set entitlements. Some rules from the docs:

  • The token is shown only once. Generating a new one invalidates the old one.
  • A token can never have more rights than the user who created it. The owner of an employee token needs at least "User admin".
  • To appear in the dropdown, send Tripletex your production application name and the entitlements you need through their contact form.

Step 2: How do you create a session token?

A session token is what you actually authenticate with. You create it with one call, without any auth header.

Internal integration (refresh token). ttlSeconds sets the lifetime, from 300 (5 minutes) to 28800 (8 hours):

curl -s -X POST "https://tripletex.no/v2/token/session/:createFromRefreshToken" \
  -H "Content-Type: application/json" \
  -d '{"refreshToken":"'"$TRIPLETEX_REFRESH_TOKEN"'","ttlSeconds":28800}'

Commercial integration (consumer + employee token). expirationDate is a date in YYYY-MM-DD format:

curl -s -X POST "https://tripletex.no/v2/token/session/:create" \
  -H "Content-Type: application/json" \
  -d '{"consumerToken":"...","employeeToken":"...","expirationDate":"2026-12-01"}'

Both return the session token inside a wrapper: {"value": {..., "token": "<session token>", "expirationDate": ...}}.

Why do most tutorials use PUT with query parameters?

Older guides, SDKs and many AI answers show PUT /token/session/:create?consumerToken=...&employeeToken=...&expirationDate=.... That endpoint still exists, but the spec marks it as Legacy: "Please use POST :create to create session tokens." The POST version sends the tokens in the request body, which Tripletex calls the preferred endpoint "for better security". Tokens in a URL tend to end up in logs. If your AI tool generates the PUT version, ask it to switch.

A small trap: in Postman, :create is read as a path variable. The Tripletex FAQ suggests defining a parameter named create with the value :create.

Step 3: How does Basic auth work with username 0?

Every normal API call uses HTTP Basic auth:

  • Username: 0 (or blank) means the company of the token owner. Any other value is the id of an accounting client.
  • Password: the session token.

So the header is Authorization: Basic base64("0:<session token>"). A quick check that everything works:

curl -s -u "0:$SESSION_TOKEN" "https://tripletex.no/v2/token/session/>whoAmI"

If you work with an accountant token, username 0 only works for /company/>withLoginAccess (which lists the clients you can reach) and /token/session/>whoAmI. Every other call needs the client's id as the username.

How long should a session token live, and when do you renew it?

  • Internal: you choose ttlSeconds. A long lifetime (up to 8 hours) means fewer token calls. Renew a few minutes before it runs out.
  • Commercial: the session expires when Tripletex server time (CET) passes midnight and the date reaches the expirationDate you sent. Set it a few days ahead and renew well before.
  • Always: if a call returns 401, throw the cached token away, create a new one and retry that call once.

Tripletex's own advice on the rate limiting page: create one session token, store it with its expiry, reuse it until it expires or you get a 401, and share it across processes.

Why must you cache session tokens?

Creating session tokens is rate limited: 180 per minute per API key or employee token today, and Tripletex plans to lower this toward about 10 per minute (no date announced). Going over gives error code 26000 RATE_LIMIT_EXCEPTION. When you create more than 10 tokens in a minute, responses carry an X-Tlx-Session-Token-Warning header. Treat that header as a bug report.

The pattern AI tools most often generate, creating a new session token inside every request handler, will break when the limit drops. Here is a cached client for an internal integration, written for a Supabase Edge Function (Deno). In Node, replace Deno.env.get with process.env.

// supabase/functions/_shared/tripletex.ts
// Based on the official API spec; test against the Tripletex test environment before production.

const BASE_URL = Deno.env.get("TRIPLETEX_BASE_URL")!; // production: https://tripletex.no/v2
const REFRESH_TOKEN = Deno.env.get("TRIPLETEX_REFRESH_TOKEN")!; // tlxr_..., server-side secret
const TTL_SECONDS = 8 * 60 * 60; // 28800, the maximum the API accepts
const RENEW_BEFORE_MS = 10 * 60 * 1000; // renew 10 minutes before expiry

let cached: { token: string; expiresAt: number } | null = null;
let pending: Promise<string> | null = null;

async function createSession(): Promise<{ token: string; expiresAt: number }> {
  const res = await fetch(`${BASE_URL}/token/session/:createFromRefreshToken`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ refreshToken: REFRESH_TOKEN, ttlSeconds: TTL_SECONDS }),
  });
  if (!res.ok) {
    // Log status and body (it contains a requestId). Never log the refresh token.
    throw new Error(`Tripletex session failed: ${res.status} ${await res.text()}`);
  }
  const { value } = await res.json();
  return { token: value.token, expiresAt: Date.now() + TTL_SECONDS * 1000 };
}

export function getSessionToken(): Promise<string> {
  if (cached && Date.now() < cached.expiresAt - RENEW_BEFORE_MS) {
    return Promise.resolve(cached.token);
  }
  // Only one creation at a time, even when many requests arrive together.
  pending ??= createSession()
    .then((s) => {
      cached = s;
      return s.token;
    })
    .finally(() => {
      pending = null;
    });
  return pending;
}

// company "0" = the token owner's own company; an accountant passes the client id.
export async function tripletex(
  path: string,
  init: { method?: string; body?: string } = {},
  company = "0",
): Promise<Response> {
  for (let attempt = 0; attempt < 2; attempt++) {
    const token = await getSessionToken();
    const res = await fetch(`${BASE_URL}${path}`, {
      ...init,
      headers: {
        "Content-Type": "application/json",
        Authorization: "Basic " + btoa(`${company}:${token}`),
      },
    });
    if (res.status !== 401 || attempt === 1) return res;
    cached = null; // expired or revoked: create a fresh token and retry once
  }
  throw new Error("unreachable");
}

Usage: const res = await tripletex("/customer?fields=id,name&count=100");

The in-memory cache lives as long as one function instance. Serverless platforms start and stop instances often, and each cold start would create a new token. If your app has real traffic, keep the token in a server-only database table (row level security on, no policies, written only with the service role key) so all instances share one token, as Tripletex recommends.

What changes for a commercial integration?

You keep one consumer token for your app and store one employee token per customer, encrypted, on the server. Each customer gets their own cached session token. Creating one:

// Based on the official API spec; test against the Tripletex test environment before production.
async function createCommercialSession(employeeToken: string) {
  // YYYY-MM-DD, three days ahead
  const expirationDate = new Date(Date.now() + 3 * 86_400_000).toISOString().slice(0, 10);
  const res = await fetch(`${BASE_URL}/token/session/:create`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      consumerToken: Deno.env.get("TRIPLETEX_CONSUMER_TOKEN"),
      employeeToken,
      expirationDate,
    }),
  });
  if (!res.ok) throw new Error(`Tripletex session failed: ${res.status} ${await res.text()}`);
  const { value } = await res.json();
  // The token stops working at midnight (CET) when the date reaches expirationDate.
  // Renewing after 24 hours keeps you well inside that window.
  return { token: value.token as string, renewAt: Date.now() + 86_400_000 };
}

The rate limit for API calls (100 requests per 10 seconds) counts per employee and integration, so each customer has their own budget. Pagination, rate limits and retries are covered in part two: Syncing with Tripletex in practice.

Where do you store Tripletex secrets?

  • Refresh tokens, consumer tokens, employee tokens and session tokens are all secrets. Anyone holding one can read and change accounting data within its entitlements.
  • Keep them in server-side secrets: supabase secrets set TRIPLETEX_REFRESH_TOKEN=tlxr_..., or your host's environment variables.
  • Never put them in React components, Lovable client code, a VITE_ or NEXT_PUBLIC_ variable, or a Supabase table the browser can read. Anything in the frontend bundle is public.
  • The browser calls your own server function. That function checks who the user is and what they may do, then calls Tripletex.
  • Use separate secrets for test and production. Test credentials do not work in production anyway, because the two environments are separate.

If a token has been in frontend code or in a public repository, assume it is leaked: create a new token in Tripletex (which invalidates the old employee token) and update your server secret.

How do you use the Tripletex test environment?

  1. Sign up for a free test account at api-test.tripletex.tech. Access is granted almost instantly after you verify your email and set a password.
  2. The receipt screen shows a consumer token, an employee token and the application name. Save all three.
  3. Point TRIPLETEX_BASE_URL at the test environment. Its API docs are at api-test.tripletex.tech/v2-docs/; check the base URL there before you hard-code it. The old api.tripletex.io host is discontinued.
  4. Test accounts expire after 6 months (you can ask for an extension), contain no production data, and do not send emails, so invoices and orders do not reach anyone.

One current note: on 3 November 2026 Tripletex announced that existing JWT refresh tokens in the test environment will soon be invalidated. If a test refresh token suddenly fails, generate a new one; creating one in advance won't help (announcement).

Is the Tripletex MCP server enough, or do you need API code?

Tripletex has an MCP server in beta. It lets Claude, ChatGPT, VS Code and other MCP clients work in Tripletex with the user's own permissions. It is free in all packages during the beta, and sending invoices or posting vouchers needs the user's approval.

  • The MCP server is enough when a person works in Tripletex through an AI assistant: looking things up, preparing invoices, checking what is outstanding. A human is in the loop and approves the important steps.
  • You need API code when your app does something on its own: syncing customers from your app, creating an invoice when an order is paid, pulling hours every night, or serving many users who never see Tripletex. That needs a server, stored tokens, retries and logging.

The MCP server is also a good way for your coding agent to explore real data in a test account before you write the integration.

What do 401, 403 and 429 errors mean?

Errors come back as JSON with status, code, message, validationMessages and a requestId. Log the whole body; the request id is what Tripletex support asks for.

  • 401 (code 3000, Authentication): the session token is expired, deleted or wrong. Also check that you are not using test credentials against production (or the other way round), that the refresh token has not been rotated, and that accountant tokens send a client id as username, not 0.
  • 403 (code 9000, Security): you are authenticated but not allowed. The token lacks the entitlement for that endpoint, or its owner lacks the rights. Some endpoints are only available in certain Tripletex packages. If you see "Company owned users(employeeToken) can only access /token/session/>whoAmI", the token cannot be used for normal calls; create it again with a user that has the right access.
  • 429 (Too Many Requests): you passed 100 requests per 10 seconds, created session tokens too fast (code 26000), or an endpoint is blocked (next point). Wait for the Retry-After header, then back off.
  • The 30-failures block: 30 failed requests in a row (status 400 or above, not counting 429) to the same endpoint and method block that endpoint with 429. The waits grow: 15, 30, 60, 75, 90 and at most 120 seconds. This usually happens when code retries a 401 or 422 unchanged in a loop. Don't retry 4xx errors without changing something: read message and validationMessages first.

Brief for your AI coding tool

Paste this into Lovable, Claude Code or Cursor and adjust it to your app:

Add a server-side Tripletex API client to this app.

Context:
- Tripletex API v2. Production base URL https://tripletex.no/v2. Test environment:
  https://api-test.tripletex.tech (check the base URL in its /v2-docs/).
- This is an INTERNAL integration for our own company: a JWT refresh token (tlxr_ prefix)
  stored as the server secret TRIPLETEX_REFRESH_TOKEN. Base URL in TRIPLETEX_BASE_URL.

Requirements:
- All Tripletex calls run in a Supabase Edge Function (or other server code), never in the
  browser. No Tripletex token in frontend code, VITE_ variables or client-readable tables.
- Create session tokens with POST /token/session/:createFromRefreshToken and a JSON body
  { refreshToken, ttlSeconds } (ttlSeconds 300-28800). Do NOT use the legacy
  PUT /token/session/:create with query parameters.
- Cache the session token with its expiry and reuse it. Never create one per request.
  Only one token creation may run at a time. Renew 10 minutes before expiry.
- Auth on every call: HTTP Basic, username "0", password = session token.
- On 401: drop the cached token, create a new one, retry the call once.
- On 429: wait for Retry-After, then back off with jitter. Never retry other 4xx errors
  unchanged; log status, code, message, validationMessages and requestId.
- Never log tokens.
- Write the code against the test environment first and list what I must test there.

When to bring in a developer

You can get authentication working yourself with the steps above. Bring in an experienced developer when:

  • You are building a commercial integration for many Tripletex customers: per-customer tokens, encrypted storage, onboarding and offboarding.
  • Your app writes to Tripletex (invoices, vouchers, payments) and a mistake would reach customers or the books.
  • Tokens have already been in frontend code or a public repository, and you are not sure what else is exposed.
  • You see 401s or 429s in production and can't tell which part of the code causes them.
  • Nobody has checked the code your AI tool wrote before real accounting data flows through it.

We take over this kind of work: connecting vibe-coded apps to real systems, Tripletex integrations, and a code audit if you want an independent check before going live. For the bigger picture, read Connecting a vibe-coded app to real systems. Rocksoft is a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.

Related guides

FAQ

Can I call the Tripletex API directly from my React or Lovable frontend?

No. Every way of authenticating needs a token that gives access to accounting data, and anything in the browser is public. Put the calls in a server function and let the frontend call that function.

Do I need to apply to Tripletex to use the API?

Not for an internal integration in your own company: a user admin creates a token under Company > API Tokens, and the account needs the Integrations module. For an app used by several Tripletex customers, you apply for a consumer token; Tripletex says to expect 2 to 3 weeks.

How long does a Tripletex session token last?

For internal integrations, as long as you ask for: ttlSeconds between 300 (5 minutes) and 28800 (8 hours). For commercial integrations, until midnight CET when the date reaches the expirationDate you sent.

Should I use PUT or POST to create a session token?

POST with a JSON body. The PUT version with tokens in query parameters is marked Legacy in the official spec.

What does username 0 mean?

It means "the company the token belongs to". Accountant integrations send the client's id instead, which they find with GET /company/>withLoginAccess.

Why do I suddenly get 429 errors when I only make a few calls?

Usually because the code creates a new session token for every request, or because it retried a failing call 30 times in a row and Tripletex blocked that endpoint for a while. Cache the token and stop retrying 4xx errors unchanged.