MetriBeacon
Menu

JavaScript with Node.js

Send readings from Node.js while keeping your key outside the source code.

On this page

What you need

A supported Node.js runtime, a numerical series and a private device-key file.

How to do it

  1. Save the example as an .mjs file and replace its series ID with your own.
  2. Read the key from its private file and prepare one payload per reading.
  3. Run the script, check the HTTP status and find the value in your monitor.

Good to know

Use this example in Node.js, not a public browser script. A key embedded in browser JavaScript can be read by visitors. Keep the same payload when retrying temporary failures.

javascript
import { readFile } from "node:fs/promises"
import { homedir } from "node:os"
import { randomUUID } from "node:crypto"

const key = (await readFile(`${homedir()}/.config/metribeacon/device.key`, "utf8")).trim()
const body = JSON.stringify({ batch_id: randomUUID(), points: [{
  id: randomUUID(), series_id: "33333333-3333-4333-8333-333333333333",
  measured_at: new Date().toISOString(), value: 21.5,
}] })
const response = await fetch("https://metribeacon.com/api/v1/ingest/points", {
  method: "POST", signal: AbortSignal.timeout(15000),
  headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body,
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
console.log(await response.json())

If something goes wrong

Check response.ok before treating JSON as an acceptance response. A response parsing error may be caused by an HTTP failure.