---
title: "Server-Side Overview"
framework: javascript
version: "2.1.2"
---

# Server-Side Overview

Server-Side Data moves query execution from the browser to your own backend. Your engine receives queries from Studio, translates them for your backend, and returns results in the format widgets expect.

> **Note**
>
> You may not need Server-Side Data. The built-in engine accepts arrays of rows via [Sync Data](https://www.ag-grid.com/studio/javascript/sync-data/) and [Async Data](https://www.ag-grid.com/studio/javascript/async-data/). Only adopt Server-Side Data when you need to push query execution to a backend.

> **Warning**
>
> Dashboards can place severe load on data backends. Ensure the backends you communicate with are scaled suitably for your use case.

The example below is using a custom engine that demonstrates how to set up server-side data access.

#### AlaSQL Server Side

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  createStudio,
} from "ag-studio";
import { setupAlaSqlTables } from "./data.ts";
import { AlaSqlDataEngine } from "./engine.ts";

const initialState: AgReportState = {
  panels: {
    filters: {
      collapsed: true,
    },
  },
  pages: [
    {
      id: "sales-dashboard",
      widgets: {
        "region-filter": {
          type: "list-filter",
          dataMapping: {
            value: [{ id: "sales.region" }],
          },
          format: {
            title: { enabled: true, text: "Filter by Region" },
          },
        },
        "category-filter": {
          type: "list-filter",
          dataMapping: {
            value: [{ id: "sales.category" }],
          },
          format: {
            title: { enabled: true, text: "Filter by Category" },
          },
        },
        "revenue-by-region": {
          type: "bar-chart-grouped",
          dataMapping: {
            categoryKey: [{ id: "sales.region" }],
            valueKey: [{ id: "sales.revenue", aggregation: "sum" }],
          },
          format: {
            title: {
              enabled: true,
              text: "Revenue by Region",
              typography: { fontSize: 16, fontWeight: "bold" },
            },
          },
        },
        "revenue-by-product": {
          type: "bar-chart-grouped",
          dataMapping: {
            categoryKey: [{ id: "sales.product" }],
            valueKey: [{ id: "sales.revenue", aggregation: "sum" }],
          },
          format: {
            title: {
              enabled: true,
              text: "Revenue by Product",
              typography: { fontSize: 16, fontWeight: "bold" },
            },
          },
        },
        "sales-grid": {
          type: "grid",
          dataMapping: {
            cols: [
              { id: "sales.region" },
              { id: "sales.product" },
              { id: "sales.category" },
              { id: "sales.quantity", aggregation: "sum" },
              { id: "sales.revenue", aggregation: "sum" },
              { id: "sales.cost", aggregation: "sum" },
            ],
          },
          format: {
            title: {
              enabled: true,
              text: "Sales Summary",
              typography: { fontSize: 16, fontWeight: "bold" },
            },
            style: {
              grandTotalRow: { enabled: true },
              theme: { rowHeight: 28 },
            },
          },
        },
      },
      widgetLayout: {
        "region-filter": { xTrack: 0, yTrack: 0, xSpan: 6, ySpan: 12 },
        "category-filter": { xTrack: 0, yTrack: 12, xSpan: 6, ySpan: 12 },
        "revenue-by-region": { xTrack: 6, yTrack: 0, xSpan: 9, ySpan: 24 },
        "revenue-by-product": { xTrack: 15, yTrack: 0, xSpan: 9, ySpan: 24 },
        "sales-grid": { xTrack: 0, yTrack: 24, xSpan: 24, ySpan: 14 },
      },
      filter: {
        page: [],
      },
    },
  ],
  selectedPageId: "sales-dashboard",
};

let studioApi: AgStudioApi;

function toggleMode() {
  const currentMode = studioApi.getProperty("mode");
  const newMode = currentMode === "edit" ? "view" : "edit";
  studioApi.setProperty("mode", newMode);
  updateModeButton(newMode);
}

function updateModeButton(mode: "view" | "edit") {
  document.getElementById("toggleMode")!.textContent =
    mode === "edit" ? "View Mode" : "Edit Mode";
}

// 1. Populate AlaSQL tables with sample data
setupAlaSqlTables();

// 2. Create the engine - Studio will call init() to build the schema
const engine = new AlaSqlDataEngine();

// 3. Create Studio - Studio owns the engine lifecycle:
//    init(context) → execute(requests) → dispose()
const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
const studioProperties: AgStudioProperties = {
  mode: "view",
  initialState,
  data: engine,
};
studioApi = createStudio(studioDiv, studioProperties);
updateModeButton(studioApi.getProperty("mode")!);

(window as any).toggleMode = toggleMode;

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).toggleMode = toggleMode;
}
```

[Live example: AlaSQL Server Side](https://www.ag-grid.com/studio/examples/server-side-data/alasql-serverside/typescript/)

## When to Use Server-Side Data

The built-in engine loads all row data into the browser and runs operations in-memory. This works well when the dataset fits in browser memory, you can afford the initial transfer latency, and you want instant filtering and sorting with no server round-trip.

Adopt Server-Side Data when:

- **Dataset is too large:** The data cannot be shipped to the browser and must be queried remotely.
- **Analytics backend:** You already have a system (e.g. ClickHouse, Snowflake, BigQuery, a REST API) that serves aggregated data.
- **Computation delegation:** You want to push aggregation, filtering, and sorting to a database engine rather than compute them client-side.

## The AgDataEngine Interface

Implement the `AgDataEngine` interface. Your engine declares its data sources via `getDataSources()`, executes queries via `execute()`, and optionally performs async setup in `init()`. If your engine discovers its schema from a remote service, await that discovery in `init()` and return the result from `getDataSources()`.

```ts
export class MyDataEngine implements AgDataEngine {
    async init(): Promise<void> {
        // Optional: async setup before the schema is consulted.
    }

    getDataSources(): AgDataSourcesDefinition {
        return {
            sources: [
                {
                    id: 'sales',
                    fields: [
                        { id: 'region', format: 'textFormat' },
                        { id: 'revenue', format: 'numberFormat' },
                    ],
                },
            ],
        };
    }

    async execute(...requests: AgExecuteRequest<AgResultShape>[]): Promise<AgExecuteResult[]> {
        return Promise.all(requests.map((req) => this.runOne(req)));
    }

    private async runOne(request: AgExecuteRequest<AgResultShape>): Promise<AgExecuteResult> {
        const { query } = request;
        const rows = await this.queryBackend(query); // Your backend call
        return { dataShape: 'rows', rows, metadata: { rowCount: rows.length } };
    }
}
```

Properties available on the `AgDataEngine` interface.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `init` | `Function` |  | Optional async lifecycle hook called by Studio before the engine is queried. Use this to bootstrap resources that must resolve before the schema is consulted - wasm compilation, HTTP fetches, database connections. Studio awaits this before calling getDataSources or finalize. Engines with no async setup can omit this entirely. |
| `getDataSources` | `Function` |  | Declare the data sources the engine exposes to Studio. Called once, after init resolves. Studio uses this to build the canonical schema it operates against. The return value is the same AgDataSourcesDefinition shape a caller would pass on the `data` property when using the built-in engine. Engines that know their fields upfront can build this eagerly in a constructor; engines that discover fields from a remote service will typically await that discovery in init and return the resulting definition here. Schema is read once per engine lifecycle; if your underlying schema can change, rebuild the engine on the host application side. |
| `finalize` | `Function` |  | Called after getDataSources once Studio has built its schema view. Use this to perform any one-time post-schema setup. Engines with nothing to do here can omit this method. |
| `execute` | `Function` |  | Execute one or more queries. Results are returned in request order, one AgExecuteResult per AgExecuteRequest. Studio batches requests that arrive together (typically within one render cycle). All requests in a batch share `info.batchId`. Engines that can coalesce backend calls should group by `batchId`. Cancellation: each request carries an optional `options.signal` that Studio aborts when the batch is superseded. Propagate it into your backend call (e.g. pass to `fetch`). |
| `executeCube` | `Function` |  | Execute one or more cube queries, returning one AgCubeResult per request. Optional capability - engines that implement this unlock pivot and nested-tree widgets over server-side data; engines that omit it cannot serve those widget types. |
| `reload` | `Function` |  | Invalidate any cached state so the next query recomputes against the current data. Engines without caches can omit this. |
| `addEventListener` | `Function` |  | Subscribe a listener to validation events the engine emits. Engines that never emit validation events can omit this. If you implement this method, you MUST also implement removeEventListener - Studio calls it on teardown. |
| `removeEventListener` | `Function` |  | Unsubscribe a listener previously registered via addEventListener. |
| `dispose` | `Function` |  | Release large data structures to reduce GC pressure on page unload. |
| `update` | `Function` |  | Apply in-place updates to the engine's data sources. Engines that manage their data externally (read-only backends, on-demand fetchers) can omit this. |

### Using Your Engine

```js
const studioProperties = {
    data: new MyDataEngine(),

    // other studio properties ...
}
```

Studio calls `init()` during startup, then `getDataSources()` once to freeze the schema. From that point on, Studio calls `execute()` as the user interacts with the dashboard.

> **Note**
>
> `getDataSources()` is called once per engine lifecycle. The schema is frozen after that call; Studio will not re-read it. If your underlying schema changes at runtime (e.g. new columns added to a database), destroy the Studio instance and create a new one with a fresh engine.

## Migrating from the Built-In Engine

Swap the `data` property from an inline data definition to an engine instance:

**Before:**

```js
const studioProperties = {
    data: {
        sources: [{
            id: 'sales',
            fields: [/* ... */],
            data: [/* rows */]
        }]
    },

    // other studio properties ...
}
```

**After:**

```js
const studioProperties = {
    data: new MyDataEngine(),

    // other studio properties ...
}
```

Extract the schema from your current config into your engine's `getDataSources()`, then implement query translation in `execute()`. See [Server-Side Implementation](https://www.ag-grid.com/studio/javascript/server-side-data-implementation/) for the full query anatomy.
