Send data from Astro app to Axiom
This page explains how to send logs, traces, and metrics from an Astro app to Axiom.
Astro is a JavaScript web framework for content-driven websites. Astro renders pages to static HTML by default, and renders pages and endpoints on demand when you add a server adapter.
This page explains how to send data from the server side of an Astro app to Axiom:
- Send logs with @axiomhq/logging from middleware, endpoints, and pages. This works with the Node.js, Vercel, Netlify, and Cloudflare adapters.
- Send traces with OpenTelemetry when you run the app with the Node.js adapter. This also sends logs and metrics over OpenTelemetry Protocol (OTLP).
- Optional: Send logs from the browser through an endpoint in your app.
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.
- An Astro app with an on-demand rendering adapter. This page uses Astro 7. Code that only runs at build time, such as prerendered pages, can’t send logs at request time.
Configure environment variables
Use astro:env to declare the Axiom settings as server secrets. Astro keeps secrets out of the client bundle and reads them at runtime from the environment of your adapter.
-
In the
astro.config.mjsfile, add the variables toenv.schema:javascriptKeep your own
outputandadaptersettings. The example uses the Node.js adapter in standalone mode. -
Create a
.envfile in the root of your project:dotenvDon’t commit the
.envfile. On a hosting platform, set the same variables in the platform’s settings.
Send logs with @axiomhq/logging
The @axiomhq/logging library sends structured logs to Axiom through the @axiomhq/js client. It runs on Node.js and on Cloudflare Workers.
Install the libraries
In your terminal, go to the root folder of your Astro app and run the following command:
Create a logger
Create a src/lib/axiom.ts file with the following content:
The edge option sends the logs to the edge deployment where your dataset lives. The following edge domains are available:
| Edge deployment | Base 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 |
ConsoleTransport also prints the logs to the console. Remove it if you don’t need local output.
Log requests in middleware
Astro middleware runs for every request that Astro renders on demand. Use it to log one event per request.
Create a src/middleware.ts file with the following content:
The middleware logs the method, path, route pattern, status code, and duration of each request. If a page or endpoint throws an error, the middleware logs the error message and stack trace, and then rethrows the error so Astro still returns an error response.
await logger.flush() sends the batched logs before the response leaves the middleware. This adds the time of one request to Axiom to each response. On serverless platforms, flush the logs after the response instead. For more information, see Platform notes.
Log from endpoints
In server endpoints, import the logger and add fields to your logs. For example, create a src/pages/api/hello.ts file:
export const prerender = false renders the endpoint on demand. You don’t need it when you set output: 'server'.
The middleware flushes the logs after the endpoint returns, so you don’t need to call flush() in the endpoint.
Log from pages
To log from an on-demand rendered page, call the logger in the component script of an .astro file:
Each log call takes a message and an optional fields object. The logger supports the debug, info, warn, and error levels. By default, AxiomJSTransport only sends info and higher. For more information, see Logging levels.
Send traces with OpenTelemetry
When you run Astro with the Node.js adapter in standalone mode, use the OpenTelemetry SDK for Node.js to send traces, logs, and metrics to Axiom over OTLP/HTTP. Automatic instrumentation creates a span for each incoming request and for outgoing calls from libraries such as database clients.
This setup loads OpenTelemetry before the Astro server starts, so it needs control over the node command. It doesn’t apply to the Vercel, Netlify, and Cloudflare adapters. For more information, see Platform notes.
Install OpenTelemetry packages
Run the following command:
The examples on this page use version 3 of the OpenTelemetry JavaScript SDK (@opentelemetry/sdk-node 0.301 and later). Version 3 changed the processor constructors to take an options object, for example new BatchLogRecordProcessor({ exporter }).
Create the instrumentation file
Create an instrumentation.mjs file in the root folder of your project, outside src. Astro doesn’t bundle this file. Node.js loads it before your app.
The file does the following:
- Registers the OpenTelemetry module hook. Without it, automatic instrumentation can’t patch the ES modules that Astro builds, and incoming requests don’t create spans. For more information, see ESM support in the OpenTelemetry docs.
- Sends traces and logs to
/v1/tracesand/v1/logswith theX-Axiom-Datasetheader. - Sends metrics to
/v1/metricswith theX-Axiom-Metrics-Datasetheader. If you don’t want to send metrics, replace themetricReadersarray withmetricReaders: []. Don’t remove the option: without it, the SDK sends metrics to its default endpoint onlocalhost. - Disables the file system instrumentation, which creates many low-value spans.
- Ignores the outgoing requests of the @axiomhq/js client, so that sending logs doesn’t create spans.
- Flushes the remaining telemetry when the process receives
SIGTERM.
Axiom accepts OTLP over HTTP with Protobuf or JSON encoding. The -proto exporters use Protobuf. Axiom doesn’t accept OTLP over gRPC.
Build and start the app
Build the app, and then start the server with the instrumentation file:
--importloadsinstrumentation.mjsbefore the standalone server entry point of the Node.js adapter.--env-fileloads the variables from the.envfile. Neither Astro nor the Node.js adapter loads environment variables at runtime. In production, set the variables in your environment and remove this flag.
The instrumentation only runs in the built server, not in astro dev.
On Node.js 26 and later, Node.js prints a deprecation warning for module.register(). The hook still works.
Add custom spans and logs
Use the OpenTelemetry API to add spans and logs to your code. For example, update src/pages/api/hello.ts:
The build-greeting span is a child of the span that automatic instrumentation creates for the incoming request. The OTLP log record carries the trace ID and span ID of the active span.
Add trace IDs to @axiomhq/logging logs
To find the trace of a request from its log, add the active trace ID to the log in src/middleware.ts:
The trace_id field matches the trace_id of the spans for the same request.
Platform notes
Serverless platforms can stop a function after it returns the response. To send logs without delaying the response, pass logger.flush() to the platform’s waitUntil function instead of awaiting it. The following examples replace the finally block of the middleware.
Vercel
The @astrojs/vercel adapter runs on-demand routes in Vercel Functions. Use waitUntil from @vercel/functions:
- Install the package with
npm install @vercel/functions. - Set the Axiom environment variables in your Vercel project settings.
- The OpenTelemetry setup on this page doesn’t apply, because Vercel starts the Node.js process.
- To send request logs, function logs, and other platform logs from Vercel, use the Axiom Vercel app.
Netlify
The @astrojs/netlify adapter runs on-demand routes in Netlify Functions and passes the function context in context.locals.netlify.context. Use its waitUntil method:
- Set the Axiom environment variables in your Netlify site settings.
- The OpenTelemetry setup on this page doesn’t apply, because Netlify starts the Node.js process.
- To send platform logs from Netlify, use the Axiom Netlify app.
Cloudflare
The @astrojs/cloudflare adapter runs your app on Cloudflare Workers and passes the Workers execution context in context.locals.cfContext:
- Cloudflare environment variables and secrets work with
astro:env. Store the API token as a secret withnpx wrangler secret put AXIOM_TOKEN. For local development, add the variables to a.dev.varsfile. - The OpenTelemetry Node.js SDK doesn’t run on Cloudflare Workers. For tracing on Workers, see OpenTelemetry using Cloudflare Workers. Integrating that setup with the worker that Astro generates isn’t covered on this page.
- To monitor Workers requests with a prebuilt dashboard, use the Axiom Cloudflare Workers app.
Send logs from the browser
To send logs from client-side scripts without exposing your API token, send them to an endpoint in your Astro app. The endpoint forwards them to Axiom with the server-side client.
-
Create a
src/pages/api/axiom.tsfile with the following content:typescript -
Create a
src/lib/axiom-client.tsfile with a logger that usesProxyTransport:typescriptProxyTransportbatches the logs and sends them to the endpoint as a JSON array. WithautoFlush: true, it sends a batch two seconds after the first log. -
Import the logger in a client-side script. For example:
astro
Logs from the browser have the source field set to browser-log. Logs from the server have server-log.
Limitations
- Prerendered pages and endpoints run at build time, so request logs and traces only cover routes that Astro renders on demand.
- The OpenTelemetry setup requires the Node.js adapter in standalone mode, or another setup where you control the
nodecommand.
What’s next
- Send data from JavaScript app: Options of the @axiomhq/js and @axiomhq/logging libraries.
- OpenTelemetry using Node.js: More OpenTelemetry examples for Node.js.
- Send OpenTelemetry data: Axiom’s OTLP endpoints.
- Explore traces: Analyze the traces you send.