> For the complete documentation index, see [llms.txt](https://docs.blynk.io/en/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.blynk.io/en/html-widget-developer-guide/getting-started.md).

# Getting Started

### How it works

```typescript
// Bridge

interface BridgeOptions {
  logEnabled?: boolean;        // forward log() to the Blynk platform logger. Default: true
  isOnErrorEnabled?: boolean;  // enable onError and sendError(). Default: true
}

// Injected by the host before your scripts run. Absent in a plain browser tab and the editor preview
declare class BlynkBridge {
  constructor(options?: BridgeOptions);

  // Datastreams
  getValue(target: DatastreamTarget): Promise<ValueObject>;
  getValues(): Promise<ValueObject[]>;                                  // positioned by index. Web: [] until the first push
  sendValue(target: DatastreamTarget, value: string | number): void;   // fire-and-forget; throws if a selector can't be resolved

  // Historical & map data
  getHistoricalData(options: HistoricalDataOptions): Promise<HistoricalDataResult>;
  getMapData(options: MapDataOptions): Promise<MapDataResult>;

  // Device
  getDeviceInfo(): Promise<DeviceInfo>;
  getDeviceTags(): Promise<Tag[]>;

  // Device metadata
  getAllDeviceMetadata(options?: MetadataReadOptions): Promise<MetadataDescriptor[]>;
  getDeviceMetadata(selector: MetadataSelector, options?: MetadataReadOptions): Promise<MetadataDescriptor>;
  updateDeviceMetadata(selector: MetadataSelector, valuePatch: Record<string, unknown>): Promise<MetadataDescriptor>;

  // Device files & assets
  getDeviceFiles(): Promise<DeviceFile[]>;
  getDeviceFile(selector: FileSelector): Promise<DeviceFile>;
  getDeviceFileBlob(fileId: number): Promise<Blob>;
  uploadDeviceFile(file: Blob | File, options?: UploadFileOptions): Promise<unknown>;   // settles once stored
  deleteDeviceFile(fileId: number): Promise<unknown>;                                  // settles once deleted
  getAssets(): Promise<Asset[]>;
  getAsset(selector: FileSelector): Promise<Asset>;
  getAssetBlob(assetId: number): Promise<Blob>;

  // Events
  getDeviceEventsPermissions(): Promise<{ canView: boolean; canEdit: boolean }>;
  getDeviceEvents(options?: DeviceEventsOptions): Promise<EventsPage>;
  getDeviceEventComments(logEventId: EventLogId): Promise<EventComment[]>;
  addDeviceEventComment(logEventId: EventLogId, comment: string): Promise<EventComment>;      // comment: 1..300 chars after trimming
  resolveDeviceEvent(logEventId: EventLogId, resolveComment?: string | null): Promise<EventMutation>;
  archiveDeviceEvent(logEventId: EventLogId): Promise<EventMutation>;
  unarchiveDeviceEvent(logEventId: EventLogId): Promise<EventMutation>;
  createDeviceEventNote(note: EventNote): Promise<EventMutation>;                            // resolves with id: null

  // Data Engine
  executeDataEngineQuery(options: DataEngineQueryOptions): Promise<DataEngineResult>;

  // Key-value storage
  getStorageItem(scope: StorageScope, key: string): Promise<unknown | null>;     // null when the key is not set
  setStorageItem(scope: StorageScope, key: string, value: unknown): Promise<null>; // any JSON up to 16 KB; null removes the key
  removeStorageItem(scope: StorageScope, key: string): Promise<null>;
  clearStorage(scope: StorageScope): Promise<null>;

  // User & organization
  isPermissionAllowed(permission: Permission): Promise<boolean>;
  getUnitSystems(): Promise<UnitSystems>;

  // Navigation: native screens, web and mobile
  openDeviceInfo(): Promise<null>;
  openDeviceEvents(options?: { logEventId?: EventLogId }): Promise<null>;   // logEventId: scroll to and highlight it
  openAutomations(): Promise<null>;

  // Navigation: dashboard pages, mobile only (isPageActionsSupported())
  getPages?(): Promise<Array<{ id: number; name: string }>>;
  showPage?(index: number): void;   // position in getPages(), not a page id
  closePage?(): void;               // one step back
  closeAllPages?(): void;           // back to the main dashboard

  // Theme
  getTheme(): Promise<Theme>;

  // Host capabilities: synchronous, no round trip
  isBridgeAvailable(): boolean;          // false in a browser tab and the editor preview
  isExternalRequestsAllowed(): boolean;  // web: false, mobile: true
  isRangePickerSupported(): boolean;     // web: true, mobile: false
  isPageActionsSupported(): boolean;     // web: false, mobile: true

  // Callbacks, errors, logging, cleanup
  setCallbacks(callbacks: BridgeCallbacks | null): void;   // omitted keys stay; null removes one; null argument removes all
  sendError(message: string): void;                        // message: non-empty
  setOnErrorEnabled(enabled: boolean): void;
  log(message: string): void;
  setLogging(enabled: boolean): void;
  destroy(): void;                                         // later calls reject with bridge_destroyed
}

declare class BlynkBridgeError extends Error {
  name: 'BlynkBridgeError';
  code: string;                       // stable, machine-readable: branch on this
  message: string;                    // human-readable, can change: never branch on it
  details: Record<string, unknown>;   // extra context, e.g. { index, count }
}

interface BridgeCallbacks {
  onValueUpdated?: ((value: ValueObject) => void) | null;
  onThemeUpdated?: ((theme: Theme) => void) | null;
  onHistoricalDataUpdated?: ((result: HistoricalDataResult) => void) | null;  // web only, after a RANGE_PICKER request
  onMapDataUpdated?: ((result: MapDataResult) => void) | null;                // web only, after a RANGE_PICKER request
  onDeviceMetadataUpdated?: ((descriptor: MetadataDescriptor) => void) | null;
  onError?: ((message: string) => void) | null;                               // only while isOnErrorEnabled is true
}

// Datastreams

type DatastreamTarget =
  | number              // 0-based widget datastream index
  | { id: number }      // server-side datastream ID
  | { name: string }    // datastream name (label), not the display alias. 1..255 chars
  | { pin: string };    // virtual pin, e.g. 'V5'. Case-insensitive

type UnitSystem = 'METRIC' | 'IMPERIAL';

interface ValueObject {          // every field is always present
  index: number;                    // 0-based widget datastream index
  id: number | null;                // server-side datastream ID
  value: string | null;             // always a string. null before the first value
  lastUpdated: number | null;       // ms epoch of the last update
  type: string;                     // 'INT' | 'DOUBLE' | 'STRING' | 'ENUM' | 'LOCATION' | …, compare case-insensitively
  label: string;                    // datastream name on the template
  displayName: string;              // display alias. '' when not set
  pinType: string;                  // e.g. 'VIRTUAL', or ''
  color: string;                    // accent color from the widget settings, or ''
  min: number | null;               // null for non-numeric streams
  max: number | null;               // null for non-numeric streams
  unit: string;                     // measurement unit name, or ''
  unitSystem: UnitSystem | null;    // null when the unit has no system
  suffix: string;                   // unit suffix for display, or ''
  decimalFormat: string;            // e.g. '#.##', or ''
  mappings: string[];               // enum option labels. [] for non-enum streams
  enumFallbackValue: string | null; // label for an enum index outside mappings
}

// Historical & map data

type Period =
  | 'ONE_HOUR' | 'SIX_HOURS' | 'DAY' | 'WEEK' | 'MONTH'   // fixed windows ending now
  | 'THREE_MONTHS' | 'SIX_MONTHS' | 'ONE_YEAR'
  | 'CUSTOM'                                             // needs from and to
  | 'RANGE_PICKER';                                      // web only: follows the dashboard's date-range picker

type SourceType = 'RAW_DATA' | 'MIN' | 'MAX' | 'AVG' | 'SUM' | 'COUNT';   // RAW_DATA: recorded points; others: per time bucket

interface HistoricalDataOptions {
  period: Period;
  from?: number;                    // ms epoch. Required for CUSTOM
  to?: number;                      // ms epoch, > from, span up to 365 days. Required for CUSTOM
  offset?: number;                  // points to skip, for RAW_DATA pagination. Default: 0
  dataStreams: Array<{              // 1..10, required for every period
    index: number;                  // 0-based widget datastream index
    sourceType: SourceType;
  }>;
}

interface HistoricalDataResult {
  streams: Array<{
    index: number;                  // 0-based widget datastream index
    granularity: 'MINUTE' | 'FIFTEEN_MINUTES' | 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY' | null;  // null for RAW_DATA
    values: Array<{ x: number; y: number }>;   // x: ms epoch, y: bucket or raw value
  }>;
}

interface MapDataOptions {
  index: number;                    // 0-based widget datastream index, must be a Location datastream
  period: Period;
  from?: number;                    // ms epoch. Required for CUSTOM
  to?: number;                      // ms epoch, > from, no 365-day cap. Required for CUSTOM
}

interface MapDataResult {
  points: Array<{ ts: number; latitude: number; longitude: number }>;   // [] when there are none
}

// Device

interface DeviceInfo {
  id: number | null;                // null when no device is bound
  orgId: number | null;
  name: string;                     // '' when no device is bound
  status: string;                   // 'ONLINE' | 'OFFLINE' | a custom status | ''
  lastReportedAt: number | null;    // ms epoch of the last server activity
  image: string | null;             // absolute http(s) URL of the device image
}

interface Tag {
  id: number;
  name: string;
  color: string;                    // use as an accent (dot or bar), not as a text color
  icon: string;
}

// Device metadata

type MetadataSelector =
  | { id: number }
  | { name: string };               // exact field name, 1..255 chars

interface MetadataReadOptions {
  refresh?: boolean;                // true waits for a fresh server read. Default: false (last snapshot)
}

interface MetadataDescriptor {
  id: number;
  type: string;                     // 'Text' | 'Number' | 'List' | 'Location' | 'Contact' | 'Table' | …
  label: string | null;
  description: string | null;
  icon: string | null;
  mandatory: boolean;
  disabled: boolean;
  editable: boolean;                // can this user change it from a widget right now
  displayValue: string | null;      // host-formatted, for display only
  value: Record<string, unknown>;   // type-specific: what updateDeviceMetadata patches
  schema: Record<string, unknown>;  // type-specific constraints for building controls
}

// Device files & assets

type FileSelector =
  | { id: number }                  // 1..2147483647
  | { fileName: string };           // 1..255 chars

interface UploadFileOptions {
  fileName?: string;                // .png, .jpg, .jpeg or .ico, up to 10 MiB. Default: file.name
}

interface DeviceFile {
  id: number;
  fileName: string;
  [field: string]: unknown;         // read other fields defensively
}

interface Asset {
  id: number;
  fileName: string;
  [field: string]: unknown;         // read other fields defensively
}

// Events

type EventLogId = string;           // positive 64-bit integer as a decimal string. Keep it a string

interface DeviceEventsOptions {
  from?: number;                    // ms epoch, < to. Default: to − 24 h
  to?: number;                      // ms epoch. Default: now
  limit?: number;                   // 1..100. Default: 100
  offset?: number;                  // events to skip. Default: 0
  eventIds?: number[];              // up to 100 product event IDs (DeviceEvent.eventId). Default: []
  search?: string | null;           // up to 255 chars. '' or null: no filter
}

interface EventsPage {
  events: DeviceEvent[];
  offset: number;
  limit: number;
  nextOffset: number;               // offset + events.length
  hasMore: boolean;
}

interface DeviceEvent {
  id: EventLogId;                   // pass this back as logEventId
  eventId: number;                  // product event definition ID
  eventType: string;                // 'ONLINE' | 'OFFLINE' | 'INFORMATION' | 'WARNING' | 'CRITICAL' | 'CONTENT' | 'NOTE' | …
  ts: number;                       // ms epoch
  name: string | null;
  description: string | null;
  icon: string | null;
  color: string | null;
  resolved: boolean;
  resolvedAt: number | null;        // ms epoch
  resolvedBy: string | null;
  resolvedComment: string | null;
  archivedAt: number | null;        // ms epoch
  archivedBy: string | null;
  canResolve: boolean;              // host state at read time, not an authorization grant
  canArchive: boolean;
  commentsCount: number;            // comments are not embedded in the page
  content: null | {                 // content events only
    subtitle: string | null;
    actionTitle: string | null;
    actionUrl: string | null;
    imageUrl: string | null;
  };
  note: null | {                    // note events only
    title: string | null;
    description: string | null;
    imageUrls: string[];
  };
}

interface EventComment {
  id: EventLogId;
  logEventId: EventLogId;
  comment: string;
  email: string | null;
  userId: EventLogId;               // '0' for a system actor
  images: string[];
  createdAt: string | null;         // ISO 8601 with time zone
}

interface EventNote {
  title: string;                    // 1..300 chars
  description: string;              // 1..2000 chars
}

interface EventMutation {
  id: EventLogId | null;            // null only for createDeviceEventNote
  acknowledged: true;               // resolves only after the server acknowledges
}

// Data Engine

interface DataEngineQueryOptions {
  sql: string;                      // 1..5000 chars, not blank
  limit?: number;                   // 0..100000. Default: 0 (the server's row cap)
  offset?: number;                  // rows to skip, 0..2147483647. Default: 0
}

interface DataEngineResult {
  meta: Array<{ name: string }>;    // columns, in result order
  rows: Array<Array<null | boolean | number | string | object | unknown[]>>;
  offset: number;                   // echoes the request
  hasMore: boolean;
}

// Key-value storage, permissions, unit systems

type StorageScope =
  | 'device'                        // current user + the widget's bound device
  | 'org'                           // current user + the current organization
  | 'global';                       // current user, across every organization

type Permission =                   // case-sensitive
  | 'VIEW_EVENTS' | 'EDIT_EVENTS' | 'QUERY_DATA_ENGINE'
  | 'VIEW_DEVICE_INFO' | 'VIEW_AUTOMATIONS' | 'VIEW_DEVICE_TAGS'
  | 'VIEW_DEVICE_FILES' | 'EDIT_DEVICE_FILES' | 'VIEW_ASSETS'
  | 'CONTROL_DEVICE' | 'EDIT_DEVICE_METADATA';   // these two: mobile only, invalid_request on web

interface UnitSystems {
  orgUnitSystem: UnitSystem | null;   // null when the organization never set one
  userUnitSystem: UnitSystem | null;  // null when the user follows the organization default
}

// Theme

interface Theme {                   // CSS color strings, may carry alpha (#rrggbbaa)
  brand: string;                    // primary accent, buttons, focus rings
  primary: string;                  // secondary accent
  positive: string;                 // success, online status
  warning: string;                  // warning badges
  critical: string;                 // errors, offline status
  background: string;               // page and widget background
  textPrimary: string;              // body text
  onPrimary: string;                // text on primary-colored surfaces
  onBrand: string;                  // text on brand-colored surfaces
  neutral: string;                  // muted text, borders
  primaryFont?: string | null;      // font families: present only with custom typography
  secondaryFont?: string | null;
  buttonsFont?: string | null;
  widgetValuesFont?: string | null;
}
```

The host injects the `BlynkBridge` class before your page's own scripts run. Both hosts expose `BlynkBridge` and `BlynkBridgeError` on `window`.

***

### Minimal HTML skeleton

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0,
                 user-scalable=no, viewport-fit=cover">

  <title>My Widget</title>
  <style>/* your styles */</style>
</head>
<body>
  <!-- your markup -->

<script>
(function () {
  'use strict';

  const noBridge = () => Promise.reject(new Error('no bridge'));

  // ① Create the bridge (falls back gracefully in a browser or the editor preview)
  const bridge = (typeof BlynkBridge !== 'undefined')
    ? new BlynkBridge({ logEnabled: true, isOnErrorEnabled: true })
    : {
        isBridgeAvailable: () => false,
        isExternalRequestsAllowed: () => false,
        isRangePickerSupported:    () => false,
        isPageActionsSupported:    () => false,
        sendValue: () => {}, sendError: () => {}, log: () => {},
        setCallbacks: () => {}, setOnErrorEnabled: () => {}, setLogging: () => {},
        destroy: () => {},
        getValue: noBridge, getValues: noBridge,
        getHistoricalData: noBridge, getMapData: noBridge,
        getDeviceInfo: noBridge, getDeviceTags: noBridge,
        getAllDeviceMetadata: noBridge, getDeviceMetadata: noBridge, updateDeviceMetadata: noBridge,
        getDeviceFiles: noBridge, getDeviceFile: noBridge, getDeviceFileBlob: noBridge,
        uploadDeviceFile: noBridge, deleteDeviceFile: noBridge,
        getAssets: noBridge, getAsset: noBridge, getAssetBlob: noBridge,
        getDeviceEventsPermissions: noBridge, getDeviceEvents: noBridge,
        getDeviceEventComments: noBridge, addDeviceEventComment: noBridge,
        resolveDeviceEvent: noBridge, archiveDeviceEvent: noBridge,
        unarchiveDeviceEvent: noBridge, createDeviceEventNote: noBridge,
        executeDataEngineQuery: noBridge,
        getStorageItem: noBridge, setStorageItem: noBridge,
        removeStorageItem: noBridge, clearStorage: noBridge,
        isPermissionAllowed: noBridge, getUnitSystems: noBridge, getTheme: noBridge,
        openDeviceInfo: noBridge, openDeviceEvents: noBridge, openAutomations: noBridge,
      };

  // Dashboard-page navigation exists on mobile only — never call it unguarded.
  const canNavigate = bridge.isPageActionsSupported() &&
                      typeof bridge.showPage === 'function';

  // ② Register callbacks BEFORE the first read
  bridge.setCallbacks({
    onValueUpdated: (v) => {
      // called whenever the host pushes a new value — see "Datastreams" for the full field set
    },
    onError: (message) => {
      bridge.log('onError: ' + message);
    }
  });

  // ③ Boot
  async function init() {
    const theme = await bridge.getTheme().catch(() => null);
    if (theme) applyTheme(theme);

    const values = await bridge.getValues().catch(() => []);
    // render your UI
  }

  init();
})();
</script>
</body>
</html>
```

***

### Create the bridge

> Creates the bridge instance your widget talks through.

```js
new BlynkBridge(options?)
```

**Parameters**

| Name                       | Type      | Required | Description                                                         |
| -------------------------- | --------- | -------- | ------------------------------------------------------------------- |
| `options.logEnabled`       | `boolean` | no       | Default `true`. Forwards `log()` calls to the Blynk platform logger |
| `options.isOnErrorEnabled` | `boolean` | no       | Default `true`. Enables the `onError` callback and `sendError()`    |

The `BlynkBridge` class is **injected by the host before your page scripts run**. Always guard against it being absent, which happens in a browser tab and in the editor preview:

```js
const bridge = (typeof BlynkBridge !== 'undefined')
  ? new BlynkBridge({ logEnabled: true, isOnErrorEnabled: true })
  : { /* stub — see the skeleton above */ };
```

**How each host delivers data to your page**

* **Web.** The widget runs in a sandboxed `iframe`. The bridge posts requests to the dashboard with `window.parent.postMessage` and resolves each Promise when the matching response arrives. There are no `window.blynk*` entry points on web and nothing for your code to keep alive.
* **Mobile.** The bridge installs a few `window.blynk*` functions that the app calls directly to push values, errors, theme and metadata updates. Do not delete or replace them after constructing `BlynkBridge`; `destroy()` removes the ones this instance owns.

**Method types**

* Read and request methods return Promises: the datastream, history and map reads, device info, tags, metadata, files and assets, events, Data Engine, storage, permissions, unit systems, theme, `getPages` and the native-screen methods.
* `sendValue`, `sendError`, `log`, the setters, `setCallbacks`, dashboard-page navigation and `destroy` are **synchronous**. Capability checks return plain booleans.

***

### Boot sequence

The recommended order:

```js
// 1. React to live pushes and errors — register first, so nothing is missed
bridge.setCallbacks({
  onValueUpdated: (v) => applyValue(v.index, v),
  onThemeUpdated: (theme) => applyTheme(theme),
  onError: (message) => showErrorBanner(message)
});

async function init() {
  // 2. Apply the theme first so there's no flash of wrong colors
  const theme = await bridge.getTheme().catch(() => null);
  if (theme) applyTheme(theme);

  // 3. Fetch current datastream values
  let values = [];
  try { values = await bridge.getValues(); } catch (_) {}

  // 4. Show a "waiting" state when nothing came back yet
  if (!Array.isArray(values) || values.length === 0) {
    showNotConfigured();   // keep going: onValueUpdated may still deliver the first values
  }

  // 5. Build the UI and populate initial values
  values.forEach(v => applyValue(v.index, v));

  // 6. Load the device header — name, status and image
  const info = await bridge.getDeviceInfo().catch(() => null);
  if (info && info.id) showDeviceHeader(info);
}

init();
```

> **Important:** Live updates can arrive before or after `init()` finishes. Key rendering on each payload's `index` and make it safe to repeat. Chain `.catch()` on every Promise to handle the no-bridge, validation and timeout cases.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.blynk.io/en/html-widget-developer-guide/getting-started.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
