@mongalayer/client

Configuration

Set up and configure the Mongalayer client SDK.

The Mongalayer client SDK is a lightweight HTTP client that communicates with a Mongalayer server. It works in any JavaScript runtime that supports fetch, mainly built for usage inside browser applications.

The client API is intentionally designed to mirror the server-side MongoDB driver methods (find, findOne, insertOne, updateMany, etc.), so querying from the client feels like writing native MongoDB code — similar to how Atlas App Services allowed client applications to talk to MongoDB directly.

For users coming from Atlas App Services, Mongalayer is focused on the querying part of the Web SDK. This means there is no concept of automatically syncing client-side data or real-time listeners.

Creating a client

import { MongalayerClient } from "@mongalayer/client";

const client = new MongalayerClient("https://.../api/mongalayer");

The first argument is the URL of your Mongalayer endpoint.

Options

Pass an optional second argument to configure the client:

const client = new MongalayerClient("https://.../api/mongalayer", {
    format: "json",
    headers: {
        "Authorization": "Bearer [my-token]"
    },
    credentials: "include"
});

format

Controls how the client sends requests:

ValueDescription
"json"Sends action and payload as a single JSON body (default) — supports batch operations
"routed"Uses URL path segments: /{database}/{collection}/{operation}

This gives you flexibility in how you structure your API routes and can be useful for integrating with existing RESTful endpoints.

JSON format (default):

POST /api/mongalayer
{
  "action": { "database": "myapp", "collection": "projects", "operation": "find" },
  "payload": { "filter": {} }
}
The JSON format is the recommended option for most use cases, especially if you want to use batch operations.

Routed format:

POST /api/mongalayer/myapp/projects/find
{ "filter": {} }

headers

HTTP headers to include with every request. Can be a static object, a function, or an async function:

// Dynamic headers (re-evaluated on each request)
headers: () => ({
    "Authorization": `Bearer ${getToken()}`
})

// Async headers
headers: async () => {
    const token = await getToken();
    return { "Authorization": `Bearer ${token}` };
}

// Static headers - highly discouraged for auth tokens
headers: {
    "Authorization": "Bearer token"
}

credentials

Maps directly to the credentials option of the Fetch API:

credentials: "include"   // Send cookies cross-origin
credentials: "same-origin" // Send cookies for same-origin only
credentials: "omit"       // Never send cookies

autoBatch

When enabled, supported read operations (find, findOne, aggregate) called on collections are automatically collected and sent as a single batch request, instead of one HTTP request per call. This is false by default.

const client = new MongalayerClient("https://.../api/mongalayer", {
    autoBatch: true
});

const db = client.db("myapp");

// These three calls are queued and flushed together in one request
const [user, projects, stats] = await Promise.all([
    db.collection<User>("users").findOne({ _id: "user-1" }),
    db.collection<Project>("projects").find({ owner: "user-1" }),
    db.collection<Asset>("assets").aggregate([{ $group: { _id: "$status", count: { $sum: 1 } } }])
]);

// OR

// These single calls are also batched together, even without Promise.all
const user = await db.collection<User>("users").findOne({ _id: "user-1" });
const projects = await db.collection<Project>("projects").find({ owner: "user-1" });
const stats = await db.collection<Asset>("assets").aggregate([{ $group: { _id: "$status", count: { $sum: 1 } } }]);
Auto-batching only applies to the batchable read operations (find, findOne, aggregate). All other operations are always sent as individual requests.
Auto-batching requires the "json"format. With the "routed" format, the batched call throws because routed requests cannot describe multiple operations.

You can override the setting per collection, or opt a single call out of batching, via collection-level batching.

autoBatchDelay

The time window, in milliseconds, that operations are collected before an auto-batch is flushed and executed. Defaults to 10. Only relevant when autoBatch is enabled.

const client = new MongalayerClient("https://.../api/mongalayer", {
    autoBatch: true,
    autoBatchDelay: 25
});

A larger delay groups more operations into a single request at the cost of added latency, while a smaller delay flushes sooner.

Updating configuration

You can update client settings after creation:

client.setFormat("routed");

client.setHeaders(() => ({
    "Authorization": `Bearer ${getToken()}`
}));

client.setCredentials("include");

Database and collection access

The client uses a chainable API similar to the MongoDB driver:

const db = client.db("myapp");
const projects = db.collection("projects");

// Or chain directly
const result = await client.db("myapp").collection("projects").find({});

Context parameter

Every collection method accepts an optional context parameter as the last argument. This value is a JSON stringified and Base64-encoded query parameter, and can be used to pass additional information to your HTTP layer (not to Mongalayer itself):

await projects.find({}, { limit: 10 }, { source: "dashboard" });
//                                       ^^^^^^^^^^^^^^^^^^^^^^^^
//                                       Sent as ?context=... query param

This is useful when your HTTP middleware needs to differentiate between request sources or pass extra metadata.

The context parameter is not validated or interpreted by Mongalayer. It is purely for your HTTP layer's use.
Copyright © 2026