Distance Matrix API in Node.js and TypeScript

Typed distance matrix requests in Node.js and TypeScript with fetch: timeouts, tiling big matrices, retries with Retry-After and running on serverless and edge.

By Wayline Engineering · · Updated · 3 min read

You can call a distance matrix API from Node.js with nothing but the built-in fetch: send a list of origins and destinations, get back the road distance and drive time for every pair. This guide builds a small, typed client in TypeScript that is safe for production: it times out, tiles large matrices, retries only what should be retried, and runs unchanged on Node 18+, Vercel, AWS Lambda and Cloudflare Workers.

Examples use the Wayline Distance Matrix API (POST /v1/matrix). Points are { lat, lng } objects.

1. Types first

ts
export interface LatLng {
  lat: number;
  lng: number;
}

export interface MatrixElement {
  status: "OK" | "NO_ROUTE" | string;
  distance_meters?: number;
  duration_seconds?: number;
}

export interface MatrixResponse {
  rows: { elements: MatrixElement[] }[];
  region: string;
  map_version: string;
  units_charged: number;
}

Typing status as a union plus string keeps the compiler honest about checking it while staying forward-compatible with new statuses.

2. One request with a timeout

ts
const API = "https://api.wayline.cloud";

export async function matrix(
  origins: LatLng[],
  destinations: LatLng[],
  init: { signal?: AbortSignal } = {},
): Promise<MatrixResponse> {
  const res = await fetch(`${API}/v1/matrix`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.WAYLINE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ origins, destinations }),
    signal: init.signal ?? AbortSignal.timeout(15_000),
  });
  if (!res.ok) throw new MatrixError(res.status, await res.text(), res.headers.get("retry-after"));
  return (await res.json()) as MatrixResponse;
}

export class MatrixError extends Error {
  constructor(
    public status: number,
    public body: string,
    public retryAfter: string | null,
  ) {
    super(`Wayline matrix ${status}: ${body.slice(0, 200)}`);
  }
}

AbortSignal.timeout is built into Node 18+ and every edge runtime, so there is no need for a timer library.

3. Retry the right failures

ts
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function matrixWithRetry(o: LatLng[], d: LatLng[], attempts = 5) {
  for (let i = 0; ; i++) {
    try {
      return await matrix(o, d);
    } catch (err) {
      const retryable =
        err instanceof MatrixError && (err.status === 429 || err.status >= 500);
      if (!retryable || i === attempts - 1) throw err;
      const after = Number(err.retryAfter) * 1000 || Math.min(8000, 500 * 2 ** i);
      await sleep(after + Math.random() * 250);
    }
  }
}

Do not retry 400-level errors other than 429: they mean the request itself is wrong (for example OUT_OF_COVERAGE or too many elements). The error reference lists every code and whether it is retryable.

4. Tile matrices larger than the limit

ts
export async function bigMatrix(
  origins: LatLng[],
  destinations: LatLng[],
  maxElements: number,
  concurrency = 4,
): Promise<MatrixElement[][]> {
  const side = Math.floor(Math.sqrt(maxElements));
  const out: MatrixElement[][] = origins.map(() => new Array(destinations.length));
  const jobs: (() => Promise<void>)[] = [];
  for (let oi = 0; oi < origins.length; oi += side)
    for (let di = 0; di < destinations.length; di += side)
      jobs.push(async () => {
        const res = await matrixWithRetry(
          origins.slice(oi, oi + side),
          destinations.slice(di, di + side),
        );
        res.rows.forEach((row, i) =>
          row.elements.forEach((el, j) => (out[oi + i][di + j] = el)),
        );
      });
  // simple worker pool: `concurrency` tiles in flight at a time
  await Promise.all(
    Array.from({ length: concurrency }, async () => {
      for (let job = jobs.shift(); job; job = jobs.shift()) await job();
    }),
  );
  return out;
}

The per-request element limit is listed on the pricing page. Square tiles minimize the number of requests; the worker pool keeps you under your rate limit instead of firing every tile at once.

5. Serverless and edge notes

  • Keep the key on the server. Call the API from a route handler, Lambda or Worker, never from browser code shipped to users. See key security.
  • Reuse connections. Define the client at module scope so warm invocations reuse it.
  • Cache stable pairs. Store results keyed by rounded coordinates plus map_version; on Workers the Cache API is a good fit. The serverless guide has full examples for Vercel, Lambda and Workers.

6. Or install the SDK

npm install @wayline/sdk gives you the same calls with typed responses and built-in retries. See the JavaScript SDK guide.

Summary

ConcernWhat to do
TimeoutsAbortSignal.timeout(15_000) on every call
Partial failuresCheck each element's status
Rate limitsRetry 429/5xx only, honor Retry-After, add jitter
Large matricesSquare tiles under the element limit, bounded concurrency
CostBilled per element on 2xx only; cache stable pairs

Get a free test key and try it with your own points.

GuidesDistance matrixCode

Start building in minutes

Create an account, grab a test key and make your first request in under five minutes.