# Server-side storage (/vela-pro/persistence/backend)



By default, Vela Pro stores workspace layouts, drawings, indicator templates, favorites, editor drafts, and module data in `localStorage`. Connecting every adapter and module port to your backend lets authenticated users access their layouts, drawings, indicators, watchlists, alerts, and trading journal across browsers and devices.

## Example REST endpoints [#example-rest-endpoints]

The adapters on this page target a user-scoped REST API where each route stores and returns opaque JSON payloads for the signed-in user:

| Endpoint                                       | HTTP methods                  | Stored payload                                                                        |
| ---------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| `/api/users/me/state/:key`                     | `GET`, `PUT`                  | Workspace state document (`workspace`) and Pine code editor draft (`vela-pro-editor`) |
| `/api/users/me/drawings/:chart/:symbol`        | `GET`, `PUT`, `DELETE`        | Per-symbol drawings for a single chart key and symbol                                 |
| `/api/users/me/indicator-templates` and `/:id` | `GET` (list), `PUT`, `DELETE` | Saved indicator templates                                                             |
| `/api/users/me/indicator-favorites`            | `GET`, `PUT`                  | Starred built-in, library, and custom script favorites                                |
| `/api/users/me/watchlists`                     | `GET`, `PUT`                  | Watchlists and watchlist display preferences                                          |
| `/api/users/me/alerts`                         | `GET`, `PUT`                  | Alert rules and alert firing log                                                      |
| `/api/users/me/journal`                        | `GET`, `PUT`                  | Trading journal accounts, fills, notes, and annotations                               |

Each `GET` endpoint returns `404` when a user has no saved record yet. Your server does not need to inspect or transform the JSON bodies.

## Request helper [#request-helper]

All adapters below share two helper utilities: `request` attaches bearer authentication headers, and `userDoc` wraps a single JSON document endpoint. Crucially, `userDoc` distinguishes a failed network read from an empty `404` record and blocks outbound writes until an initial read succeeds, preventing transient server errors at page load from overwriting saved user data with empty defaults.

```ts
declare function getAccessToken(): string; // application auth token provider

export function request(path: string, init: RequestInit = {}): Promise<Response> {
    const headers = { authorization: `Bearer ${getAccessToken()}`, 'content-type': 'application/json' };
    return fetch(`/api/users/me/${path}`, { ...init, headers });
}

export function userDoc(path: string) {
    let readable = false;
    return {
        /** Returns stored JSON text, or null on 404. Throws on network or server errors. */
        async read(): Promise<string | null> {
            const res = await request(path);
            if (!res.ok && res.status !== 404) throw new Error(`${path}: ${res.status}`);
            readable = true;
            return res.ok ? await res.text() : null;
        },
        /** Fire-and-forget write that never rejects. */
        write(body: string): void {
            if (!readable) return;
            // Browsers cap keepalive request bodies at 64 KiB; larger payloads fall back to standard fetch.
            request(path, { method: 'PUT', body, keepalive: body.length < 60_000 }).catch(() => {});
        },
    };
}
```

## Workspace state and editor draft [#workspace-state-and-editor-draft]

`VelaStorage` reads and writes raw strings by key. Preloading state keys before constructing `VelaWorkspace` allows `storage.get()` to return synchronously so the saved layout renders on the first paint rather than flashing default constructor options while awaiting a promise.

```ts
import type { VelaStorage } from '@luxalgo/vela/widget';

declare function userDoc(path: string): { read(): Promise<string | null>; write(body: string): void };

export async function loadStateStorage(keys: readonly string[]): Promise<VelaStorage> {
    const docs = new Map(keys.map((key) => [key, userDoc(`state/${encodeURIComponent(key)}`)]));
    const texts = new Map<string, string | null>();
    await Promise.all([...docs].map(async ([key, doc]) => texts.set(key, await doc.read())));
    return {
        get: (key) => texts.get(key) ?? null,
        set: (key, value) => docs.get(key)?.write(value),
    };
}
```

If an initial read fails, `loadStateStorage` rejects so your application can display an error state and retry rather than mounting an uninitialized workspace. Because the Pine code editor draft uses the same `VelaStorage` contract, one preloaded instance serves both `'workspace'` and `'vela-pro-editor'`. See [Layouts and chart state](/vela-pro/persistence/layouts) for the full state document specification.

## Per-symbol drawings [#per-symbol-drawings]

```ts
import type { SymbolDrawingsStorage } from '@luxalgo/vela-pro';

declare function request(path: string, init?: RequestInit): Promise<Response>;

const path = (key: { chart: string; symbol: string }): string =>
    `drawings/${encodeURIComponent(key.chart)}/${encodeURIComponent(key.symbol)}`;
const unread = new Set<string>();

export const drawingsStorage: SymbolDrawingsStorage = {
    async load(key) {
        const res = await request(path(key)).catch(() => null);
        if (res?.ok) return await res.json();
        if (res?.status !== 404) unread.add(path(key)); // failed read rather than 404; block overwrites
        return null;
    },
    save(key, doc) {
        if (unread.has(path(key))) return;
        const body = doc ? JSON.stringify(doc) : undefined;
        const keepalive = (body?.length ?? 0) < 60_000;
        request(path(key), { method: doc ? 'PUT' : 'DELETE', body, keepalive }).catch(() => {});
    },
};
```

The `key.chart` identifier is produced by `chartKey`. Configure `chartKey` explicitly if your application supports workspace tabs or multiple named layouts; see [Drawing persistence](/vela-pro/persistence/stores/drawings#naming-charts-with-chartkey).

## Templates and favorites [#templates-and-favorites]

```ts
import type { IndicatorFavorite, IndicatorFavoritesStorage, IndicatorTemplate, IndicatorTemplatesStorage } from '@luxalgo/vela-pro';

declare function request(path: string, init?: RequestInit): Promise<Response>;
declare function userDoc(path: string): { read(): Promise<string | null>; write(body: string): void };

const one = (id: string): string => `indicator-templates/${encodeURIComponent(id)}`;

export const templatesStorage: IndicatorTemplatesStorage = {
    async list() {
        const res = await request('indicator-templates');
        if (!res.ok) throw new Error(`Templates: ${res.status}`);
        return (await res.json()) as IndicatorTemplate[];
    },
    async save(template) {
        const res = await request(one(template.id), { method: 'PUT', body: JSON.stringify(template) });
        if (!res.ok) throw new Error(`Template: ${res.status}`); // surfaced in the save dialog
    },
    async remove(id) {
        await request(one(id), { method: 'DELETE' });
    },
};

const favorites = userDoc('indicator-favorites');

export const favoritesStorage: IndicatorFavoritesStorage = {
    load: async () => JSON.parse((await favorites.read()) ?? '[]') as IndicatorFavorite[],
    save: (list) => favorites.write(JSON.stringify(list)),
};
```

See [Indicator templates](/vela-pro/persistence/stores/indicator-templates) and [Indicator persistence](/vela-pro/persistence/stores/indicators#indicator-favorites) for adapter lifecycle details.

## Module storage ports [#module-storage-ports]

Watchlist, Alerts, and Journal persist user records through dedicated module ports. The Trading module has no client-side storage port because orders, positions, and executions reside on your brokerage backend; see [Broker integration](/vela-pro/modules/trading/broker).

```ts
import type { AlertEvent, AlertRule, AlertsBackend } from '@luxalgo/vela-pro-alerts';
import type { JournalData, JournalStore } from '@luxalgo/vela-pro-journal';
import type { WatchlistState, WatchlistStorage } from '@luxalgo/vela-pro-watchlist';

declare function userDoc(path: string): { read(): Promise<string | null>; write(body: string): void };

const parse = <T>(text: string | null): T | null => (text ? (JSON.parse(text) as T) : null);

const lists = userDoc('watchlists');
export const watchlistStorage: WatchlistStorage = {
    load: async () => parse<WatchlistState>(await lists.read()),
    save: (state) => lists.write(JSON.stringify(state)),
};

const journalDoc = userDoc('journal');
export const journalStore: JournalStore = {
    load: async () => parse<JournalData>(await journalDoc.read()),
    save: async (data) => journalDoc.write(JSON.stringify(data)),
};

/** AlertsBackend.load() is synchronous, so preload alert state before calling enableVelaPro(). */
export async function loadAlertsBackend(): Promise<AlertsBackend> {
    const doc = userDoc('alerts');
    const kept = parse<{ rules: AlertRule[]; events: AlertEvent[] }>(await doc.read());
    return { load: () => kept ?? { rules: [], events: [] }, save: (state) => doc.write(JSON.stringify(state)) };
}
```

Refer to [Watchlist](/vela-pro/modules/catalog/watchlist), [Alerts](/vela-pro/modules/catalog/alerts), and [Journal](/vela-pro/modules/catalog/journal) for each port's schema. Client-side alerts evaluate only while the page is open in a browser; to trigger notifications while the user is offline, evaluate saved `AlertRule` definitions on your server as well.

## Complete initialization [#complete-initialization]

Preload the synchronous stores (`loadStateStorage` and `loadAlertsBackend`) in parallel before calling `enableVelaPro()` and constructing `VelaWorkspace`. All remaining stores load asynchronously in the background. Optional domain modules such as Trading and Journal are registered via the `plugins` array.

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import type { VelaStorage } from '@luxalgo/vela/widget';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro, type IndicatorFavoritesStorage, type IndicatorTemplatesStorage, type SymbolDrawingsStorage } from '@luxalgo/vela-pro';
import type { AlertsBackend } from '@luxalgo/vela-pro-alerts';
import { journal, type JournalStore } from '@luxalgo/vela-pro-journal';
import { trading, type Broker } from '@luxalgo/vela-pro-trading';
import type { WatchlistStorage } from '@luxalgo/vela-pro-watchlist';

declare function loadStateStorage(keys: readonly string[]): Promise<VelaStorage>;
declare function loadAlertsBackend(): Promise<AlertsBackend>;
declare const drawingsStorage: SymbolDrawingsStorage;
declare const templatesStorage: IndicatorTemplatesStorage;
declare const favoritesStorage: IndicatorFavoritesStorage;
declare const watchlistStorage: WatchlistStorage;
declare const journalStore: JournalStore;
declare const myBroker: Broker;

const [stateStorage, alertsBackend] = await Promise.all([loadStateStorage(['workspace', 'vela-pro-editor']), loadAlertsBackend()]);

enableVelaPro({
    symbolDrawings: { storage: drawingsStorage },
    indicatorTemplates: { storage: templatesStorage },
    indicatorLibrary: { favorites: favoritesStorage },
    codeEditor: { storage: stateStorage },
    watchlist: { storage: watchlistStorage },
    alerts: { backend: alertsBackend },
    plugins: [trading({ broker: myBroker }), journal({ store: journalStore })],
});

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: 'workspace',
    storage: stateStorage,
});
```

Pass all storage adapters in that single `enableVelaPro()` call. Because each feature installs once per page, storage options passed to a subsequent `enableVelaPro()` call are ignored.

## Implementation notes [#implementation-notes]

### Initial loading behavior [#initial-loading-behavior]

| Store                    | When `load` / `get` runs                                       | UI state while awaiting an async response                                                                                                                 |
| ------------------------ | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Workspace state document | Once during `new VelaWorkspace(...)`                           | Async promises render constructor defaults first, then switch to the saved layout. Preload before construction (as shown above) to avoid a layout switch. |
| Per-symbol drawings      | Whenever a chart displays a symbol while holding zero drawings | Renders the chart without drawings until resolved. Drawings created by the user before resolution take precedence over the response.                      |
| Templates and favorites  | Once during `enableVelaPro()`                                  | Empty list until resolved; stars toggled in the meantime are preserved.                                                                                   |
| Watchlists               | Once during `enableVelaPro()`                                  | Empty panel until resolved; `defaultSymbols` seeds a starter list only after `load()` resolves with `null`.                                               |
| Alerts                   | Synchronously during `enableVelaPro()`                         | Preload before calling `enableVelaPro()`.                                                                                                                 |
| Journal                  | Once during `enableVelaPro()`                                  | Empty journal view until resolved.                                                                                                                        |
| Editor draft             | On first editor open or programmatic editor API call           | Starter script template or configured `initialSource`.                                                                                                    |

### Write timing and page unload [#write-timing-and-page-unload]

| Store                    | Payload written                                           | Debounce / trigger                   | Unload behavior                                                             |
| ------------------------ | --------------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------- |
| Workspace state document | Full state document                                       | 500 ms after last change             | Flushed on `beforeunload`                                                   |
| Per-symbol drawings      | Single chart + symbol document, or `null`                 | 300 ms after last change             | Flushed on `pagehide`                                                       |
| Indicator templates      | Single `IndicatorTemplate`                                | Immediate on save, rename, or delete | No queued writes                                                            |
| Indicator favorites      | Full `IndicatorFavorite[]` array                          | 400 ms after last change             | Not flushed on unload                                                       |
| Watchlists               | Full `WatchlistState`                                     | Immediate on every change            | No queued writes                                                            |
| Alerts                   | All `AlertRule` items plus up to 300 recent firing events | 200 ms after last change             | Not flushed automatically; call `alertsController()?.flush()` on `pagehide` |
| Journal                  | Full `JournalData` snapshot                               | 250 ms after last change             | Not flushed on unload                                                       |
| Editor draft             | Script source string                                      | 400 ms after last edit               | Not flushed on unload                                                       |

Keep the following operational characteristics in mind when sizing and securing your endpoints:

* **Unawaited writes**: Most stores (`VelaWorkspace`, Watchlist, Journal, per-symbol drawings) invoke write methods without awaiting or catching returned promises. Handle network errors inside your adapter methods, as `userDoc.write()` does above.
* **Unload delivery limits**: Use `fetch(..., { keepalive: true })` so unload flushes survive page navigation. While `navigator.sendBeacon` also survives navigation, it cannot send custom `Authorization` headers and works only with cookie-authenticated endpoints. Browsers cap concurrent `keepalive` and beacon payloads at 64 KiB.
* **Payload growth**: Workspace state documents embed the full Pine Script® source of every indicator added from the menu across all chart cells, and `JournalStore` writes the complete journal dataset on each trade fill. Configure backend request body limits accordingly, and disable `keepalive` when payloads approach 64 KiB.
* **Last-write-wins concurrency**: Stores fetch their state once at startup and write full snapshots on change without merging across open browser tabs or multiple devices. Enforce optimistic concurrency or document versioning on your backend if required, and call `indicatorTemplatesController()?.reload()` when refreshing templates externally.

### Session and user switching [#session-and-user-switching]

Feature stores and module ports initialize once when `enableVelaPro()` executes. When a user signs out or switches accounts, perform a full page reload so no cached in-memory state carries over between sessions.

If you retain `localStorage` persistence on shared devices instead of using backend storage, namespace every key with the authenticated user's ID: pass user-specific `persist` strings to `VelaWorkspace` and `codeEditor`, a user prefix to `new LocalSymbolDrawingsStorage(prefix)`, and user-scoped keys to `new LocalIndicatorTemplatesStorage(key)`, `localIndicatorFavoritesStorage(key)`, `new LocalWatchlistStorage(key)`, `new LocalAlertsBackend(key)`, `new LocalJournalStore(key)`, and `trading({ paper: { persist: key } })`.

### Migrating from localStorage [#migrating-from-localstorage]

When migrating an existing application from `localStorage` to server-side storage, run a one-time upload of existing browser records before calling `enableVelaPro()`. Refer to [Overview](/vela-pro/persistence/overview#independent-stores) for the default `localStorage` keys. For single-key stores, check whether your backend returns `404`, read the local value (`localStorage.getItem('vela-workspace')`, `new LocalWatchlistStorage().load()`, and equivalents), upload it via `PUT`, and remove the local key upon success.

Per-symbol drawings store one `localStorage` entry per chart and symbol under `vela-pro.drawings:<chart>:<symbol>`:

```ts
import { DEFAULT_SYMBOL_DRAWINGS_KEY } from '@luxalgo/vela-pro';

declare function request(path: string, init?: RequestInit): Promise<Response>;

/** Uploads locally cached per-symbol drawings without overwriting existing server records. */
export async function migrateLocalDrawings(): Promise<void> {
    const prefix = `${DEFAULT_SYMBOL_DRAWINGS_KEY}:`;
    for (const entry of Object.keys(localStorage).filter((k) => k.startsWith(prefix))) {
        const name = entry.slice(prefix.length);
        const at = name.lastIndexOf(':'); // default symbol keys strip the provider colon
        if (at < 0) continue;
        const path = `drawings/${encodeURIComponent(name.slice(0, at))}/${encodeURIComponent(name.slice(at + 1))}`;
        const existing = await request(path);
        if (existing.status === 404) {
            const put = await request(path, { method: 'PUT', body: localStorage.getItem(entry) });
            if (!put.ok) continue; // retain local entry to retry on next load
        } else if (!existing.ok) continue;
        localStorage.removeItem(entry);
    }
}
```

If your server-side `chartKey` naming convention differs from the default DOM-derived chart names stored in `localStorage`, remap the chart key segment before uploading.

## Related [#related]

* [Overview](/vela-pro/persistence/overview)
* [Configuration precedence](/vela-pro/persistence/precedence)
* [Production checklist](/vela-pro/reference/production)
