LogDrop
Sdk

LogDrop Web SDK

The LogDrop Web SDK is a vanilla JavaScript SDK for browsers. It works with plain HTML pages and with frontend frameworks such as React, Vue, Angular, Svelte and Next.js client components.

You initialize LogDrop once when the page loads, and it sends logs, crashes, HTTP activity, events and security signals from the browser to the LogDrop backend.

The SDK runs in the browser. A PHP, Python, Spring or .NET application can include it in the HTML it serves, but logs from the server itself need Backend Tracing.


1. SDK Installation

Add the SDK as an npm package if your site is built with a bundler, or load it with a script tag if it is not. Either way, you then need your project's Web App ID.

1.1. npm

Use the @log-drop/web package when your site is built with a bundler, for example in a React, Vue, Angular, Svelte or Next.js project.

Using npm:
npm install @log-drop/web
or using yarn:
yarn add @log-drop/web

1.2. Script tag (CDN)

Without a bundler, load a pinned version from the LogDrop CDN. The script defines the global LogDrop, LogFlow and LogLevel objects.

<script src="https://cdn.logdrop.io/PUBLIC_FILES/logdrop-web-sdk/release/1.0.0/logdrop.min.js"></script>

1.3. Find your Web App ID

The Web App ID identifies your LogDrop project, so the SDK knows where to send data. In the LogDrop panel, open Project Settings → App ID and copy the Web App ID. The Web SDK uses this ID; the Mobile SDK App ID on the same page is for the iOS and Android SDKs.

1.4. Limit the sites that can use it (optional)

The Web App ID is visible in your website's source. To stop other websites from using it, add your domains under Project Settings → App ID → Allowed domains, for example shop.com, *.shop.com or localhost:3000. Requests from other sites are then rejected. Leave the list empty to allow every site.


2. Initialization

Call LogDrop.init once, as early as possible when the page loads, so that errors and requests made during startup are captured.

import { LogDrop } from '@log-drop/web';

LogDrop.init({
  appId: 'YOUR_WEB_APP_ID',
  release: '1.4.0',         // Your website's version, shown in the panel
  env: 'production',
  // baseUrl: 'YOUR_BASE_URL', // Optional: for self-hosted LogDrop
});
With the script tag:
<script src="https://cdn.logdrop.io/PUBLIC_FILES/logdrop-web-sdk/release/1.0.0/logdrop.min.js"></script>
<script>
  LogDrop.init({ appId: 'YOUR_WEB_APP_ID', release: '1.4.0' });
</script>

A second LogDrop.init call on the same page is ignored. In single-page applications, initialize in the entry file, not in a component that can mount more than once.

If LogDrop cannot be reached

The SDK keeps recording when the LogDrop server is offline or unreachable. Logs, crashes and events are stored in the browser (IndexedDB) and uploaded once the connection is back, including when the browser reports it is online again.


3. LogDropConfig Overview

LogDropConfig is the object you pass to LogDrop.init. Only appId is required. Set the other fields when the defaults do not fit your site, for example to change upload timing, limit which requests are recorded, set up push or react to security actions.

interface LogDropConfig {
  appId: string;                 // Web App ID from the panel (required)
  baseUrl?: string;              // Self-hosted LogDrop URL
  release?: string;              // Your website version
  env?: string;                  // Default "prod"
  debugLogEnabled?: boolean;     // Print SDK diagnostics to the browser console
  flushIntervalMs?: number;      // Log upload interval, default 60000
  maxBatchSize?: number;         // Upload early after this many new logs, default 50
  crashTracking?: boolean;       // Overrides the project setting when set
  network?: {
    enabled?: boolean;           // Default true
    captureFetch?: boolean;      // Default true
    captureXHR?: boolean;        // Default true
    stripQuery?: boolean;        // Remove query strings from recorded URLs, default true
    stripHash?: boolean;         // Remove #fragments from recorded URLs, default true
    sampleRate?: number;         // 0-1, default 1
    onlyErrors?: boolean;        // Record only failed or slow requests
    slowThresholdMs?: number;    // With onlyErrors, also record requests slower than this
    excludeUrls?: Array<string | RegExp>;
  };
  // Push notifications (see section 8)
  vapidPublicKey?: string;
  serviceWorkerUrl?: string;     // Default "/_logdrop/logdrop-sw.js"
  serviceWorkerScope?: string;   // Default "/"
  serviceWorkerRegistration?: ServiceWorkerRegistration;
  manualServiceWorkerRegistration?: boolean;
  onRemoteMessageReceived?: (payload) => void;
  // Security callbacks (see section 12)
  onSessionThreatChanged?: (threat) => void;
  onRiskPolicyActionTaken?: (action) => void;
  onWhitelistActionTaken?: (action) => void;
}

HTTP logging, crash tracking, event tracking, push and the security rules can also be turned on or off for the whole project in the panel under Project Settings → App Config.


4. Crash Tracking

After LogDrop.init, uncaught JavaScript errors (window.onerror) and unhandled promise rejections are reported as crashes automatically. To report an error your code already handled:

try {
  checkout();
} catch (error) {
  LogDrop.saveCustomCrashReport('checkout', error.stack ?? String(error), 'CheckoutError');
}

Stack traces are reported as the browser provides them. If your production bundle is minified, the panel shows the minified file names and positions.


5. Logging Methods

Logging methods record your own messages in LogDrop, so you can see what happened in the browser before a problem.

5.1. Basic logging

Each method sets the level: e for error, w for warning, i for info and d for debug. Pass an optional tag that names the part of your site, the message and, optionally, a LogFlow.

import { LogDrop, LogFlow } from '@log-drop/web';

LogDrop.e('Payment', 'Payment failed');   // Error
LogDrop.w('Network', 'Slow network');     // Warning
LogDrop.i('Auth', 'User logged in');      // Info
LogDrop.d('Parser', 'Parsing response');  // Debug

// The tag is optional; objects are recorded as JSON
LogDrop.i({ step: 'cart', items: 3 });

5.2. Sending logs

Logs are stored in the browser and uploaded every 60 seconds (flushIntervalMs), or earlier when maxBatchSize new logs are waiting. To upload right away:

await LogDrop.sendLogs((success) => {
  console.log('Logs uploaded:', success);
});

Logs that could not be uploaded, for example because the user closed the tab, are sent on the next visit.


6. LogFlow

LogFlow groups related logs into a single business flow or transaction. A flow has a name, an ID and optional attributes. Pass the same flow to every log of one piece of work, such as one checkout, so the panel can show those logs together.

const checkoutFlow = new LogFlow('CartCheckout', checkoutId, {
  itemsCount: String(items.length),
  total: totalPrice.toFixed(2),
  currency: 'TRY',
});

LogDrop.i('Checkout', 'Checkout started.', checkoutFlow);
LogDrop.i('Checkout', 'Checkout completed.', checkoutFlow);

In the LogDrop panel you can filter and analyze logs by flowName and flowId.


7. HTTP Monitoring

When HTTP logging is on for the project, requests made with fetch and XMLHttpRequest are recorded with their method, URL, status, duration, headers and bodies. Requests to LogDrop itself are never recorded. You review them in the panel's HTTP Monitoring, for example to find slow or failing endpoints.

  • The domain and path rules, payload capture rules and sensitive data filters from App Config are applied before anything leaves the browser.
  • Authorization, Cookie, Set-Cookie, X-Api-Key and LogDrop's own headers are always masked.
  • Use network.excludeUrls to skip URLs from the browser side as well:
LogDrop.init({
  appId: 'YOUR_WEB_APP_ID',
  network: {
    excludeUrls: ['https://analytics.example.com', /\/health$/],
    onlyErrors: true,
    slowThresholdMs: 2000,
  },
});

8. Push Notifications

Web push lets you send browser notifications and in-app messages to your site's visitors from the panel. Web push needs HTTPS and a service worker served from your own domain.

8.1. Serve the service worker

A service worker is a script that the browser runs in the background, apart from your page. LogDrop's push handlers run in logdrop-sw.js, so the browser must be able to load that file from your domain.

Copy logdrop-sw.js from the npm package (node_modules/@log-drop/web/dist/logdrop-sw.js) or from the CDN folder to your site's public directory, and tell the SDK where it is:

LogDrop.init({
  appId: 'YOUR_WEB_APP_ID',
  serviceWorkerUrl: '/logdrop-sw.js',
  serviceWorkerScope: '/',
});

If your site already registers its own service worker, register a worker that includes LogDrop's handlers and pass its registration with serviceWorkerRegistration.

8.2. Ask for permission and subscribe

A browser receives LogDrop pushes only after the visitor allows notifications and the page subscribes. LogDrop.push.subscribe() asks the browser for that permission.

Configure Web Push for the project in the panel; the SDK receives the VAPID public key from there. Then subscribe after a user action, such as a button click:

button.addEventListener('click', async () => {
  try {
    await LogDrop.push.subscribe();
  } catch (error) {
    // e.g. permission denied, unsupported browser, page not on HTTPS
    console.warn(error.message);
  }
});

LogDrop.push.getPermissionState(); // 'default' | 'granted' | 'denied' | 'unsupported'
await LogDrop.push.unsubscribe();

Pushes sent from the panel are shown as browser notifications, and in-app messages are shown on the page. Receives and clicks are tracked as events. To react to a push in your own code, pass onRemoteMessageReceived to LogDrop.init.


9. User Identification (UUID Customization)

By default, data is tied to a browser identifier. Set your own user ID, for example after the user signs in, when you want to find that user's data in the panel. You can then search for it as User UUID on the Devices page.

To associate it with your own user ID:

await LogDrop.updateUser('user-1234@example.com');

The ID is remembered across page loads. Call LogDrop.updateUser(null) when the user signs out.


10. Sessions

A session lasts as long as the browser tab, the Web equivalent of an app process on mobile. Reloads and navigations in the same tab continue the session, and app_open is sent once per session. A new tab or a new browser window starts a new session, and so does switching to a different identified user.


11. Custom Events

Use custom events to track application-specific actions that are not covered by LogDrop's built-in events. Send a stable event name together with optional JSON-compatible properties. You do not need to set anything up in the panel first.

11.1. Track a Custom Event

Call trackCustomEvent when the action happens, with the event name and, optionally, an object of properties that describe it.

LogDrop.trackCustomEvent('purchase_completed', {
  coupon_code: 'SUMMER10',
  amount: 49.9,
  item_count: 2,
  is_first_order: true,
  completed_at: new Date(),
});

Properties are optional. Date values are sent as ISO-8601 strings; strings, numbers, booleans, null, nested objects and arrays are sent as they are.

11.2. Naming and Property Types

LogDrop groups custom events by name and records the type of each property. Follow these rules so that one action always arrives as the same event, with the same property types.

  • Event names and property names must start with an ASCII letter (A-Z, a-z) and contain only ASCII letters, digits or underscores (_).

  • Use stable and consistent names. For example, do not alternate between purchase_completed and purchaseCompleted for the same event.

  • Do not put IDs, timestamps or other dynamic values in the event name. Add them as properties instead.

  • Do not use the name of a LogDrop default event for a custom event.

  • Keep each property's type stable. For example, always send amount as a number.

    11.3. Limits and Validation

    The SDK checks every event against these limits before it sends the event.

  • Event names and property names can contain up to 128 characters.

  • One event can contain up to 100 top-level properties.

  • The complete properties JSON can contain up to 16 KB in UTF-8.

  • Property values must be JSON-compatible (no functions, circular references, BigInt or NaN).

If validation fails, the SDK rejects the complete event and prints the reason to the browser console as a warning. Names, properties and payloads are never silently truncated.

11.4. Panel Behavior

No custom event definition is required before tracking. After the first valid event reaches LogDrop, the Events page shows the event, its observed properties and property types.


12. Custom User Attributes

Custom user attributes attach stable profile information to the current user and can be used for segment-based push targeting in the panel. Call them after LogDrop.init.

LogDrop.setCustomAttributes({
  plan_type: 'premium',
  country: 'TR',
});

LogDrop.removeCustomAttribute('plan_type');

LogDrop.getCustomAttributes(); // { country: 'TR' }
  • The update is an additive upsert: omitted attributes stay unchanged.

  • Up to 30 attributes in total.

  • Keys contain only letters, numbers, underscores (_) or hyphens (-), up to 64 characters.

  • Values are non-blank strings up to 256 characters.

  • If one entry is invalid, or the merged result would exceed 30 keys, the complete update is rejected.

  • Attributes belong to the identified user. After updateUser switches to another user, that user's own attributes apply.


13. Security and Risk Signals

When risk detection is enabled for the project, the SDK reports browser risk signals (for example automation tools, headless browsers and open DevTools) and applies the risk policies, IP reputation actions and HTTP whitelist configured in the panel. Actions can show a warning, block the page, or block network requests. To react to these actions in your own code, pass the callbacks below to LogDrop.init.

LogDrop.init({
  appId: 'YOUR_WEB_APP_ID',
  onRiskPolicyActionTaken: (action) => console.log(action.actionNames),
  onWhitelistActionTaken: (action) => console.log(action.domain, action.blocked),
  onSessionThreatChanged: (threat) => console.log(threat),
});

LogDrop.getSessionThreat();

14. Troubleshooting

Check these points when the SDK cannot reach LogDrop, push does not subscribe, or an event or attribute does not appear.

  • Set debugLogEnabled: true to print SDK diagnostics to the browser console.
  • If requests fail with 403 and Origin not allowed, add the site's domain under Allowed domains.
  • Make sure you used the Web App ID, not the Mobile SDK App ID. With an unknown ID the SDK stops calling LogDrop for the rest of the page; with debugLogEnabled: true the console shows App ID invalid or project deleted.
  • If your site has a Content Security Policy, allow https://server.logdrop.io (or your baseUrl) in connect-src, and https://cdn.logdrop.io in script-src when you use the script tag.
  • If push subscribe() fails, check that the page is on HTTPS, Web Push is configured for the project, and the service worker URL returns the logdrop-sw.js file.
  • A custom event or attribute that does not appear was rejected locally; the browser console shows the reason.

On this page