New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@layers/node

Package Overview
Dependencies
Maintainers
4
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@layers/node

Layers Analytics Node.js SDK — thin wrapper over Rust core via WASM

Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
165
-10.33%
Maintainers
4
Weekly downloads
 
Created
Source

@layers/node

Server-side Node.js SDK for Layers Analytics. Designed for multi-tenant server environments where each request may come from a different user.

Install

npm install @layers/node
# or
pnpm add @layers/node

Requires Node.js >= 18.

Quick Start

import { LayersNode } from '@layers/node';

const layers = new LayersNode({
  apiKey: 'your-api-key',
  appId: 'your-app-id',
  environment: 'production'
});

// Every call requires a distinctId (the user who triggered the event)
layers.track('user-123', 'api_call', { endpoint: '/users', method: 'GET' });

// Graceful shutdown (flushes remaining events)
await layers.shutdown();

Configuration

All fields for LayersNodeConfig:

FieldTypeDefaultDescription
apiKeystringrequiredLayers API key
appIdstringrequiredApplication identifier
environment'development' | 'staging' | 'production'requiredDeployment environment
enableDebugbooleanfalseVerbose console logging
baseUrlstringhttps://in.layers.comOverride the ingest endpoint
flushIntervalMsnumber10000Periodic flush interval (ms)
flushThresholdnumber20Queue depth that triggers auto-flush
maxQueueSizenumber10000Max events in queue before dropping
maxBatchSizenumber1000Max events per HTTP batch
shutdownFlushTimeoutMsnumber5000Max wait time for final flush
handleSignalsbooleantrueRegister SIGTERM/SIGINT handlers

Express Middleware

Automatically track HTTP requests as events:

import { LayersNode } from '@layers/node';
import { layersExpressMiddleware } from '@layers/node/express';
import express from 'express';

const app = express();
const layers = new LayersNode({
  apiKey: 'your-api-key',
  appId: 'your-app-id',
  environment: 'production'
});

app.use(layersExpressMiddleware(layers));

// Middleware tracks `http_request` events with:
//   - method, path, status_code, response_time_ms
//   - distinctId resolved from X-User-Id or X-App-User-Id headers

Middleware Options

app.use(
  layersExpressMiddleware(layers, {
    trackRequests: true, // default: true
    trackResponseTime: true, // default: true
    ignorePaths: ['/health'] // default: ['/health', '/healthz', '/ready', '/favicon.ico']
  })
);

Next.js Integration

App Router (Server Components / Server Actions)

Use AsyncLocalStorage-based request context to thread the user ID through server-side code:

import { LayersNode } from '@layers/node';
import {
  getLayersContext,
  trackServerAction,
  trackServerPageView,
  withLayersContext
} from '@layers/node/nextjs';

const layers = new LayersNode({
  apiKey: 'your-api-key',
  appId: 'your-app-id',
  environment: 'production'
});

// In middleware.ts — set the request context
export function middleware(request: NextRequest) {
  const userId = request.headers.get('x-user-id') ?? 'anonymous';
  return withLayersContext(
    { distinctId: userId, properties: { path: request.nextUrl.pathname } },
    () => NextResponse.next()
  );
}

// In a Server Component or Server Action
trackServerPageView(layers, '/dashboard');
trackServerAction(layers, 'createPost', { category: 'blog' });

// Or read context manually
const ctx = getLayersContext();
if (ctx) {
  layers.track(ctx.distinctId, 'custom_event', ctx.properties);
}

Error Handling

The Node SDK never throws from track(), screen(), or flush(). Instead, register error listeners:

layers.on('error', (err) => {
  console.error('Layers SDK error:', err.message);
  // Forward to Sentry, Datadog, etc.
});

// Remove a listener
layers.off('error', myListener);

When enableDebug is true and no error listeners are registered, errors are logged to console.warn.

Signal Handling (Graceful Shutdown)

By default, the SDK registers SIGTERM and SIGINT handlers that flush all queued events before the process exits. This ensures no events are lost during deployments or container restarts.

To disable this (e.g. if you manage signals yourself):

const layers = new LayersNode({
  ...config,
  handleSignals: false
});

// Manual shutdown in your own signal handler
process.on('SIGTERM', async () => {
  await layers.shutdown();
  process.exit(0);
});

Flush and Shutdown

// Manual flush (async, with retry)
await layers.flush();

// Check queue depth
console.log(layers.queueDepth());

// Graceful shutdown: flushes remaining events, then stops
// Waits up to shutdownFlushTimeoutMs (default 5s)
await layers.shutdown();

After shutdown(), all subsequent track()/screen() calls are silently dropped.

Debug Mode

Enable enableDebug: true for detailed logging:

[Layers] track("api_call", 2 properties, distinctId="user-123")
[Layers] screen("dashboard", 0 properties, distinctId="user-123")
[Layers] setUserProperties(3 properties, distinctId="user-123")

License

MIT

Keywords

layers

FAQs

Package last updated on 08 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts