Opaque Cursor Encoding And Decoding

A cursor codec that encodes and decodes opaque cursors so API clients never depend on internal offsets or key names.

TypescriptData Fetching

Code

export type CursorDirection = "forward" | "backward";

export interface CursorFields {
  readonly id: string;
  readonly direction: CursorDirection;
}

export type CursorResult<T> =
  | { readonly ok: true; readonly value: T }
  | { readonly ok: false; readonly error: string };

function toBase64Url(text: string): string {
  return Buffer.from(text, "utf8").toString("base64url");
}

function fromBase64Url(encoded: string): string {
  return Buffer.from(encoded, "base64url").toString("utf8");
}

export function encodeCursor(fields: CursorFields): string {
  return toBase64Url(JSON.stringify(fields));
}

export function decodeCursor(cursor: string): CursorResult<CursorFields> {
  if (typeof cursor !== "string" || cursor.length === 0) {
    return { ok: false, error: "cursor must be a non-empty string" };
  }
  let parsed: unknown;
  try {
    parsed = JSON.parse(fromBase64Url(cursor));
  } catch {
    return { ok: false, error: "cursor is not valid base64url JSON" };
  }
  if (!parsed || typeof parsed !== "object") {
    return { ok: false, error: "cursor payload must be an object" };
  }
  const record = parsed as Record<string, unknown>;
  if (typeof record.id !== "string" || record.id.length === 0) {
    return { ok: false, error: "cursor payload missing a string id" };
  }
  const direction = record.direction === undefined ? "forward" : record.direction;
  if (direction !== "forward" && direction !== "backward") {
    return { ok: false, error: `cursor direction must be forward or backward, got ${String(direction)}` };
  }
  return { ok: true, value: { id: record.id, direction } };
}

Offset pagination skips and repeats rows when items are inserted or deleted between requests.

Use case: API designers and clients implementing stable pagination over mutable datasets

Inputs / outputs

  • Input: a record id and optional sort direction, or an opaque cursor string
  • Output: an encoded cursor string, or decoded cursor fields with validation errors

Error conditions

  • cursor is not valid base64 JSON
  • decoded payload misses required fields
  • direction is not a known value

Approach

encode cursor fields as base64url JSON; decode validates structure and types before returning; direction defaults to forward.

Implementation

export type CursorDirection = "forward" | "backward";

export interface CursorFields {
  readonly id: string;
  readonly direction: CursorDirection;
}

export type CursorResult<T> =
  | { readonly ok: true; readonly value: T }
  | { readonly ok: false; readonly error: string };

function toBase64Url(text: string): string {
  return Buffer.from(text, "utf8").toString("base64url");
}

function fromBase64Url(encoded: string): string {
  return Buffer.from(encoded, "base64url").toString("utf8");
}

export function encodeCursor(fields: CursorFields): string {
  return toBase64Url(JSON.stringify(fields));
}

export function decodeCursor(cursor: string): CursorResult<CursorFields> {
  if (typeof cursor !== "string" || cursor.length === 0) {
    return { ok: false, error: "cursor must be a non-empty string" };
  }
  let parsed: unknown;
  try {
    parsed = JSON.parse(fromBase64Url(cursor));
  } catch {
    return { ok: false, error: "cursor is not valid base64url JSON" };
  }
  if (!parsed || typeof parsed !== "object") {
    return { ok: false, error: "cursor payload must be an object" };
  }
  const record = parsed as Record<string, unknown>;
  if (typeof record.id !== "string" || record.id.length === 0) {
    return { ok: false, error: "cursor payload missing a string id" };
  }
  const direction = record.direction === undefined ? "forward" : record.direction;
  if (direction !== "forward" && direction !== "backward") {
    return { ok: false, error: `cursor direction must be forward or backward, got ${String(direction)}` };
  }
  return { ok: true, value: { id: record.id, direction } };
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { decodeCursor, encodeCursor } from "./example.ts";

test("encode then decode round trip", () => {
  const cursor = encodeCursor({ id: "row-42", direction: "forward" });
  const decoded = decodeCursor(cursor);
  assert.deepEqual(decoded, { ok: true, value: { id: "row-42", direction: "forward" } });
});

test("direction defaults to forward when absent", () => {
  const raw = Buffer.from(JSON.stringify({ id: "row-1" }), "utf8").toString("base64url");
  assert.deepEqual(decodeCursor(raw), { ok: true, value: { id: "row-1", direction: "forward" } });
});

test("rejects malformed cursor with a reason", () => {
  const decoded = decodeCursor("!!!not-base64-json!!!");
  assert.equal(decoded.ok, false);
  if (!decoded.ok) assert.match(decoded.error, /base64url JSON/);
});

test("rejects payload missing required fields", () => {
  const raw = Buffer.from(JSON.stringify({ direction: "forward" }), "utf8").toString("base64url");
  const decoded = decodeCursor(raw);
  assert.equal(decoded.ok, false);
  if (!decoded.ok) assert.match(decoded.error, /missing a string id/);
});

test("rejects unknown direction", () => {
  const raw = Buffer.from(JSON.stringify({ id: "x", direction: "sideways" }), "utf8").toString("base64url");
  const decoded = decodeCursor(raw);
  assert.equal(decoded.ok, false);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts

Limitations and error handling

no encryption (opaque is not secure); no signature verification; payload is not compressed.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic