Docs
DocumentationQuery ReferenceAPI Reference
Open Console→→
DocumentationQuery ReferenceAPI Reference

Platform overview

What is Axiom?QuickstartArchitectureFeatures
Fundamentals
Datasets
Edge deployments
Limits
Performance
Optimize usage
Requirements
Semantic conventions
Glossary
Tour
SecurityRoadmap

Send data

Reference architecturesMethods

Understand data

Console
Query
Builder
Editor
Query results
Visualize
Traces
Metrics
Correlations
Save queries
Stream
Dashboard
Create
Elements
Create
Configure
Element types
Gauge
Heatmap
Log stream
Monitor list
Note
Pie chart
Scatter plot
Statistic
Table
Time series
Sections
Configure
Filter
Monitor
Overview
View status
Configure
Examples
Monitor types
Anomaly
Match
New values
Threshold
Alerting
Overview
Configure
Notifier types
Amp
ChatGPT Workspace Agent
Claude Code
Cursor
Custom Webhook
Discord
Email
incident.io
Jira Service Management
Microsoft Teams
Opsgenie
PagerDuty
Slack
Annotations
Command Menu
Manage
Datasets
Overview
Views
Virtual fields
Access
RBAC
Tokens
CLI
Organization
Labels
Audit log
Settings
Usage and billing
Profile
Extend
Overview
AWS Lambda
AWS PrivateLink
Cloudflare Workers
Cloudflare Logpush
Convex
Grafana
Hex
Netlify
Supabase
Supabase metrics
Tailscale
Terraform
Unkey
Vercel
Intelligence
Overview
Spotlight
AI agents
Overview
MCP Server
Overview
Tools
Query cost limits
Agent-created orgs
Skills
Overview
Axiom alerting
Build dashboards
Control costs
SRE
Translate SPL to APL
Splunk
Overview
Splunk app
Install and configure
Commands
Traces
Examples
Portal
How it works
Set up standard mode
Set up transparent mode
Observability Cloud
OCSF data
OCSF as CIM
SPL command support
Examples
Monitor and troubleshoot

Use cases

ObservabilityProduct analytics
OCSF security data
Overview
Send data
Query data
LLM observability
Overview
Use Vercel AI SDK
Manual instrumentation
OpenAI Agents SDK
GenAI attributes
Redaction policies

Miscellaneous

LLMs
Overview
List of docs pages
Full docs
Query reference
FAQs
Legal
Acceptable use policy
Axiom for Startups terms
Committed use terms
Cookies
Data processing
HIPAA
Partner agreement
Partner program guide
Privacy policy
SLA
Terms of service
Terms of use

Send data from JavaScript app to Axiom

This page explains how to send data from a JavaScript app to Axiom.

JavaScript is a versatile, high-level programming language primarily used for creating dynamic and interactive web content.

To send data from a JavaScript app to Axiom, use one of the following libraries of the Axiom JavaScript SDK:

  • @axiomhq/js
  • @axiomhq/logging

The choice between these options depends on your individual requirements:

Capabilities@axiomhq/js@axiomhq/logging
Send data to AxiomYesYes
Query dataYesNo
Capture errorsYesNo
Create annotationsYesNo
TransportsNoYes
Structured logging by defaultNoYes
Send data to multiple places from a single functionNoYes

The @axiomhq/logging library is a logging solution that also serves as the base for other libraries like @axiomhq/react and @axiomhq/nextjs.

Info

The @axiomhq/js and the @axiomhq/logging libraries are part of the Axiom JavaScript SDK, an open-source project and welcomes your contributions. For more information, see the GitHub repository.

Prerequisites

  • Create an Axiom account.
  • Create a dataset in Axiom where you send your data.
  • Create an API token in Axiom with permissions to ingest data to the dataset you have created.

Use @axiomhq/js

Install @axiomhq/js

In your terminal, go to the root folder of your JavaScript app and run the following command:

shell
npm install @axiomhq/js

Configure authentication

Pass token to the Axiom constructor. @axiomhq/js doesn’t read environment variables automatically. To keep the token out of your source code, export AXIOM_TOKEN (for example, with eval $(axiom config export -f) using the Axiom CLI) and pass token: process.env.AXIOM_TOKEN:

typescript
import { Axiom } from '@axiomhq/js';

const axiom = new Axiom({
  token: process.env.AXIOM_TOKEN,
});

Configure region

By default, the client sends data to api.axiom.co. To target a specific edge region, set the edge option to the edge domain that matches the region your dataset lives in:

typescript
import { Axiom } from '@axiomhq/js';

const axiom = new Axiom({
  token: process.env.AXIOM_TOKEN,
  edge: 'eu-central-1.aws.edge.axiom.co',
});
typescript
import { Axiom } from '@axiomhq/js';

const axiom = new Axiom({
  token: process.env.AXIOM_TOKEN,
  edge: 'us-east-1.aws.edge.axiom.co',
});

The following edge domains are available:

Edge deploymentBase domain for ingest and query
US East 1 (AWS)us-east-1.aws.edge.axiom.co
EU Central 1 (AWS)eu-central-1.aws.edge.axiom.co

For more information about edge deployments, see Edge deployments.

Warning

Always use the edge option to target a region. Don't put a regional hostname in url — url is reserved for non-ingest API operations and won't route ingest correctly.

Info

Edge ingestion requires an API token (xaat-). Edge queries also accept a personal token (xapt-) with orgId. Personal tokens are deprecated.

Client options

OptionRequiredDescription
tokenyesAn Axiom API token with permissions for the operations you use.
orgIdnoOrganization ID. Required when using a personal token.
edgenoEdge domain for ingest and query, without scheme. Example: eu-central-1.aws.edge.axiom.co. Use this to target a region.
edgeUrlnoFull edge URL with scheme. Takes precedence over edge if both are set. Useful for self-hosted or proxy setups.
urlnoBase URL for non-ingest API operations. Only needed if you call other Axiom APIs from the same client.
onErrornoCallback invoked when sending data fails. Defaults to console.error.
fetchnoCustom fetch implementation used for all HTTP requests. Useful for routing through a proxy such as undici.ProxyAgent.
axiomClientnoAdditional space-separated product/version tokens appended to the X-Axiom-Client header.

The client also exposes service namespaces for Axiom resources: datasets (including metrics metadata), dashboards, savedQueries, and users for read operations, monitors for full CRUD operations, and annotations.

Send data to Axiom

The following example sends data to Axiom:

typescript
axiom.ingest('DATASET_NAME', [{ foo: 'bar' }]);
await axiom.flush();
Info

Replace DATASET_NAME with the name of the Axiom dataset where you send your data.

The client automatically batches events in the background. In most cases, call flush() only before your app exits.

Query data

The following example queries data from Axiom:

typescript
const res = await axiom.query(`['DATASET_NAME'] | where foo == 'bar' | limit 100`);
for (const event of res.tables[0]?.events() ?? []) {
  console.log(event);
}
Info

Replace DATASET_NAME with the name of the Axiom dataset where you send your data.

Starting in @axiomhq/js 2.0.0, APL queries return tabular results by default. Iterate rows with res.tables[0].events(), or pass { format: 'legacy' } as the second argument to axiom.query for the previous response shape.

For more examples, see the examples in GitHub.

Query metrics

To query metrics, set type to mpl and specify a time range. The following example queries the go.memory.used metric over the last hour. Set edge to the region for your dataset.

typescript
const res = await axiom.query('`DATASET_NAME`:`go.memory.used`', {
  type: 'mpl',
  startTime: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
  endTime: new Date().toISOString(),
  edge: 'us-east-1.aws.edge.axiom.co',
});
console.log(res);

Capture errors

To capture errors, pass a method onError to the client:

typescript
let client = new Axiom({
  token: '',
  ...,
  onError: (err) => {
    console.error('ERROR:', err);
  }
});

By default, onError is set to console.error.

Create annotations

The following example creates an annotation:

typescript
import { annotations } from '@axiomhq/js';

const client = new annotations.Service({ token: process.env.AXIOM_TOKEN || '' });

await client.create({
  type: 'deployment',
  datasets: ['DATASET_NAME'],
  title: 'New deployment',
  description: 'Deployed version 1.0.0',
});

Use @axiomhq/logging

Install @axiomhq/logging

In your terminal, go to the root folder of your JavaScript app and run the following command:

shell
npm install @axiomhq/logging

Send data to Axiom

The following example sends data to Axiom:

typescript
import { Logger, AxiomJSTransport, ConsoleTransport } from "@axiomhq/logging";
import { Axiom } from "@axiomhq/js";

const axiom = new Axiom({
  token: process.env.AXIOM_TOKEN,
});

const logger = new Logger(
  {
    transports: [
      new AxiomJSTransport({ 
        axiom,
        dataset: process.env.AXIOM_DATASET,
      }),
      new ConsoleTransport(),
    ],
  }
);

logger.info("Hello, world!");

Because AxiomJSTransport sends data through the @axiomhq/js client, set the region by passing the edge option to the Axiom constructor. For the full list of edge domains, see Configure region.

Transports

The @axiomhq/logging library includes the following transports:

  • ConsoleTransport: Logs to the console.

    typescript
    import { ConsoleTransport } from "@axiomhq/logging";
    
    const transport = new ConsoleTransport({
      logLevel: "warn",
      prettyPrint: true,
    });
  • AxiomJSTransport: Sends logs to Axiom using the @axiomhq/js library.

    typescript
    import { Axiom } from "@axiomhq/js";
    import { AxiomJSTransport } from "@axiomhq/logging";
    
    const axiom = new Axiom({
      token: process.env.AXIOM_TOKEN,
    });
    
    const transport = new AxiomJSTransport({
      axiom,
      dataset: process.env.AXIOM_DATASET,
      logLevel: "warn",
    });
  • ProxyTransport: Sends logs to the proxy server function that acts as a proxy between your app and Axiom. It’s particularly useful when your app runs on top of a server-enabled framework like Next.js or Remix.

    typescript
    import { ProxyTransport } from "@axiomhq/logging";
    
    const transport = new ProxyTransport({
      url: "/proxy",
      logLevel: "warn",
      autoFlush: { durationMs: 1000 },
    });
  • SimpleFetchTransport: Sends batched JSON log payloads to any HTTP endpoint using fetch. It holds up to 1,000 queued events and retries on HTTP 429 and 5xx responses.

    typescript
    import { SimpleFetchTransport } from "@axiomhq/logging";
    
    const transport = new SimpleFetchTransport({
      input: "https://example.com/logs",
      init: { method: "POST", headers: { "Content-Type": "application/json" } },
      autoFlush: { durationMs: 1000 },
      logLevel: "info",
    });

Alternatively, create your own transports by implementing the Transport interface:

typescript
import { Transport } from "@axiomhq/logging";

class MyTransport implements Transport {
  log(log: Transport['log']) {
    console.log(log);
  }

  flush() {
    console.log("Flushing logs");
  }
}

Logging levels

The @axiomhq/logging library includes the following logging levels:

  • debug: Debug-level logs.
  • info: Informational logs. Default for logLevel.
  • warn: Warning logs.
  • error: Error logs.
  • off: Disables logging.

Set logLevel on new Logger({ transports: [...], logLevel: 'warn' }) to filter logs before they reach transports.

Formatters

Formatters change the content of a log before sending it to a transport. Set overrideDefaultFormatters: true on the Logger config to replace the built-in formatters instead of running after them. For example:

typescript
import { ConsoleTransport, Logger, LogEvent } from "@axiomhq/logging";

const myCustomFormatter = (event: LogEvent) => {
  const upperCaseKeys = {
    ...event,
    fields: Object.fromEntries(
      Object.entries(event.fields).map(([key, value]) => [key.toUpperCase(), value])
    ),
  };

  return upperCaseKeys;
};

const logger = new Logger({
  transports: [new ConsoleTransport()],
  formatters: [myCustomFormatter],
});

logger.info("Hello, world!");

Schema validation

Validate structured log fields with any Standard Schema library (such as Zod, Valibot, or ArkType) using schema, outputSchema, and onValidationError in Logger:

typescript
import { ConsoleTransport, Logger } from "@axiomhq/logging";
import { z } from "zod";

const logger = new Logger({
  transports: [new ConsoleTransport()],
  schema: z.object({ userId: z.string() }),
  onValidationError: (context) => {
    console.error("Invalid log fields:", context.reason, context.issues);
  },
});

logger.info("User signed in", { userId: "user_123" });

Related logging options

Send data from JavaScript libraries and frameworks

To send data to Axiom from JavaScript libraries and frameworks, see the following:

  • Send data from React app
  • Send data from Next.js app
  • TanStack Start integration

Send data from Node.js

While the Axiom JavaScript SDK works on both the backend and the browsers, Axiom provides transports for some of the popular loggers:

  • Pino
  • Winston
Was this page helpful?
Suggest edits on GitHub
On this page
Use @axiomhq/jsInstall @axiomhq/jsConfigure authenticationConfigure regionClient optionsSend data to AxiomQuery dataQuery metricsCapture errorsCreate annotationsUse @axiomhq/loggingInstall @axiomhq/loggingSend data to AxiomTransportsLogging levelsFormattersSchema validationRelated logging optionsSend data from JavaScript libraries and frameworksSend data from Node.js