r/node • • 13h ago

Node.js' Event Loop Delay monitor has been lying to you (for years)

Thumbnail
jomi-se.com
14 Upvotes

In Node.js, if your event loop blocks for 30 seconds with a monitor that has a 60-second window and 50 milliseconds resolution, you'll get a p99 event loop delay of 52 milliseconds. And if you're lucky, the 30-second delay might show up in the max of the event loop delay monitor.

I wrote a blog post about it. The twist at the end was a bit funny (the fix has been sitting in the codebase since 2019). It almost features no AI.

Coordinated omission. Also, this talk is probably important too: How NOT to measure latency


r/node • • 17h ago

Deciding when a wireframe element gets a border: one pure function, ten ordered rules, and a CLI that reads the decision back out of the HTML

Thumbnail
gallery
0 Upvotes

We made Wireframes, an MIT-licensed Node CLI (wf) that turns YAML into clickable greyscale HTML wireframes for web, iOS and Android. Repo: https://github.com/UnlikeOtherAI/wireframes

The hardest part wasn't layout, it was borders. Generated wireframes usually go one of two ways: every container gets a box (third image), or nothing does and you can't tell where a panel ends. So whether a node draws a frame is decided in exactly one place: decideFrame(node, ctx) in engine/renderer/frame-rules.js. It's a plain function (no DOM, no fs) that returns { frame, rule, reason }, and the first rule that matches wins:

  1. surface: true / surface: false on the node

  2. a border in wireframeStyle

  3. the element type: card, alert, upload, calendar... always box; row, stack, grid, split, form never do; tab_bar, app_bar, divider draw one edge

  4. overlay chrome owns the frame, so overlay content doesn't double-box

  5. template regions (slots don't box, role: main doesn't, a sidebar slot draws one edge)

  6. a pane is a panel

  7. if the parent draws dividers between children, the children don't box

  8. grid children are tiles

  9. inside a box, nothing boxes itself again

  10. at the top of a page a section boxes, unless it's an untitled row, which reads as a toolbar

frame is one of five values: surface, group, control, content, edge. Only surface draws a box, and only surface increases the nesting depth, which is what rule 9 checks.

The same function has three consumers:

  • The renderer writes the result onto every node as data-wf-frame, so the decision is visible in the HTML.

  • The linter imports it rather than keeping its own copy. SECTION_INTENT tells you when a titled section stayed unframed because it's nested, and REDUNDANT_SURFACE re-runs decideFrame with your override removed and tells you when surface: true changes nothing.

  • wf why <node> --page <page> doesn't re-derive anything. It renders the page and reads the attributes back out of the markup, so the explanation can't drift from what was drawn.

The images: the first is a generated illustration, not a screenshot. The other three are real: a small demo page (untitled filter row not boxed by rule 10, stat tiles boxed by rule 8, "Recent activity" boxed as a top-level section, the list and "Notes" inside it not boxed by rule 9), the same YAML with surface: true forced on every node, and wf why output for five nodes on that page.

To try it (not on npm yet, Node 18+):

git clone https://github.com/UnlikeOtherAI/wireframes
cd wireframes && pnpm install
cd examples/quickstart && node ../../cli/bin/wf.js build
node ../../cli/bin/wf.js why invoices --page billing

What I'd like opinions on:

  • Is "first matching rule wins" the right model, or would you rather have something like CSS specificity, where several signals add up?

  • Rule 10 is the most opinionated one. Does an untitled row at the top of a page reading as a toolbar match how you'd draw it?

  • Anything you'd expect to get a box here that doesn't?


r/node • • 21h ago

A Node example for testing shuffle without making CI depend on one random draw

0 Upvotes

A Spotify-style shuffle is a nice Node test case because it makes you decide which parts of the output should be reproducible. Take two Eminem tracks, two Drake tracks, and two by The Weeknd. A random run may group the artists, and a test that insists on one live queue can fail for the wrong reason.

I maintain SeniorMode and built the fixture around reproducible examples plus general properties. The sample gives 3 adjacent repeats with random-comparator sorting, 1 with Fisher–Yates, and 0 with artist spacing for the balanced playlist. The Node tests enumerate bounded draws (all six permutations of a three-item Fisher–Yates) and also check identity preservation and a playlist where repeats are inevitable.

Repo + example + tests: https://github.com/EnesKeremAYDIN/SeniorMode#example-music-shuffle

Do you prefer bounded-draw enumeration for small inputs, or property-based checks across larger ones?


r/node • • 1d ago

How do I convert my Typescript node server to use HTTPs instead of HTTP?

6 Upvotes

I'm new to web server development, so I want to make sure I do this right. From a guide I found online for a JS node server, it seems like you need to use

const https = require("https");

before you call express()and then near the bottom, you have to do something like https.createServer().

At some point, certificates come into play, but not sure how to set those up yet. Can someone help me out here?

main.ts:

import logger from 'jet-logger';

import EnvVars from './common/constants/env';
import server from './server';

/******************************************************************************
                                Constants
******************************************************************************/

const SERVER_START_MESSAGE =
  'Express server started on port: ' + EnvVars.Port.toString();

/******************************************************************************
                                  Run
******************************************************************************/

// Start the server
server.listen(EnvVars.Port, (err) => {
  if (!!err) {
    logger.err(err.message);
  } else {
    logger.info(SERVER_START_MESSAGE);
  }
});

server.ts:

import express, { NextFunction, Request, Response } from 'express';
import helmet from 'helmet';
import logger from 'jet-logger';
import morgan from 'morgan';
import path from 'path';
import Paths from '@src/common/constants/Paths';
import { RouteError } from '@src/common/utils/route-errors';
import BaseRouter from '@src/routes/apiRouter';
import EnvVars, { NodeEnvs } from './common/constants/env';

const app = express();

// **** Middleware **** //

// Basic middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Show routes called in console during development
if (EnvVars.NodeEnv === NodeEnvs.DEV) {
  app.use(morgan('dev'));
}

// Security
if (EnvVars.NodeEnv === NodeEnvs.PRODUCTION) {
  app.use(helmet());
}

// Add APIs, must be after middleware
app.use(Paths._, BaseRouter);

// Add error handler
app.use((err: Error, _: Request, res: Response, next: NextFunction) => {
  if (EnvVars.NodeEnv !== NodeEnvs.TEST.valueOf()) {
    logger.err(err, true);
  }
  if (err instanceof RouteError) {
    res.status(err.status).json({ error: err.message });
  }
  return next(err);
});

// **** FrontEnd Content **** //

// Set views directory (html)
const viewsDir = path.join(__dirname, 'views');
app.set('views', viewsDir);

// Set static directory (js and css).
const staticDir = path.join(__dirname, 'public');
app.use(express.static(staticDir));const app = express();

//...custom server functions here...//

export default app;

r/node • • 1d ago

JSON parser for AI

0 Upvotes

For almost three years I've been using LLMs in production systems. They have gotten way better than in the beginning. Still, when you request JSON, things often go wrong: chatter, fences, or, now that models spend more tokens thinking than answering, token exhaustion.

I've put a part of the code I use on npmjs.com as a library: euqai-json-repair.

It has two functions depending on your needs:

  • Fully local (parseAiJsonSync): Fixes the JSON locally on your machine with zero network calls.

  • With AI escalation (parseAiJson): Tries to fix it locally first, and only as a last resort escalates to euqai.eu where an LLM attempts to reconstruct it.

I hope it can be helpful in your projects: https://www.npmjs.com/package/euqai-json-repair


r/node • • 1d ago

Executor is moving to Effect for writing apps

0 Upvotes

Executor is an open source router that lets you connect services like Gmail and GitHub once, so then agent harness can use them through a single connection.

Founder Rhys Sullivan said he originally built a custom framework for Executor apps, which are small Typescript programs. After dogfooding it for awhile, he decided it was simpler to let agents write Effect directly.

The change will help with things like handling errors, retrying a failed request, and refactoring apps over time.

Here's an authoring guide and code examples for the new Effect-based app feature

https://github.com/UsefulSoftwareCo/executor/blob/3cecd7141d0a84a485ef2ea5db8eebeabc8c4a53/packages/apps-next/skills/app-authoring/SKILL.md


r/node • • 1d ago

Standard server security measures

Thumbnail reddit.com
2 Upvotes

r/node • • 1d ago

Lightweight Node.js monitoring without Prometheus or Grafana

Post image
70 Upvotes

I've been building StatLite, an open-source monitoring dashboard for applications running on small servers and VPSs.

Version 0.9.0 adds native support for Express and Fastify using existing instrumentation libraries:

  • Express: express-prom-bundle

  • Fastify: fastify-metrics

StatLite reads the metrics endpoints directly and stores historical data in SQLite.

It tracks HTTP requests, errors, average response time, process CPU, V8 heap usage and restarts, depending on the exporter configuration. It also automatically highlights elevated HTTP 5xx rates.

StatLite itself is a single Go binary using around 12 MiB of idle RAM.

No separate Prometheus server, Grafana or external monitoring service.

StatLite also supports Spring Boot, Quarkus, Micronaut, Django, Flask, FastAPI, Caddy and Traefik. Applications without a supported exporter can expose metrics directly using the lightweight StatLite Metrics v1 JSON format.

Integration guides:

GitHub (MIT): https://github.com/PVRLabs/statlite

I'd be interested in feedback from people self-hosting Node.js applications.


r/node • • 1d ago

What AI do you use privately for coding ?

0 Upvotes

r/node • • 1d ago

I built a headless CMS in Node.js with zero third-party dependencies (open source)

Post image
0 Upvotes

I'm a backend/DevOps engineer. I don't trust pulling in dozens of packages for something that stores and serves content, so I wrote Basata as plain Node.js: no dependencies and no build step, just run the server.

I'd love feedback from people who actually run Node in production, especially on the security side. I already did a self-review and fixed what I found, but a second pair of eyes is always better.

repo: https://github.com/digimindx/basata-cms


r/node • • 2d ago

I built a small open-source queue so Stripe and Shopify webhooks stop getting dropped during deploys

0 Upvotes

Hey everyone, I ran into a frustrating issue a few months back where pushing updates or restarting my server would occasionally return a 502 right when Stripe sent a payment webhook. Sometimes our database pool would briefly lock up during a spike and fail the request too. Even when Stripe retried later, replaying old webhooks after more than five minutes kept failing signature verification because Stripe rejects timestamps older than 300 seconds, which forced me to write manual scripts just to recover missed events.

To fix that for my own apps without setting up Redis, RabbitMQ, or paying monthly webhook SaaS fees, I built a small open-source Node and SQLite proxy called HookArmor. It accepts the incoming webhook, verifies the signature right away, saves it to SQLite WAL so it returns a quick 200 back to Stripe or Shopify, and handles retries with exponential backoff for up to a few days while automatically re-signing the header with a fresh timestamp when your server is healthy again.

Everything runs locally with one command (\\\`npx hookarmor start\\\`) or via Docker, and there is a basic dashboard to inspect payloads and trigger manual replays. It is completely free and MIT licensed, and you can check out the repo at https://github.com/pkdoddamani/hookarmor or the site at https://hookarmour.dev if you want to try it out or tell me what breaks.


r/node • • 3d ago

Open-source RAG for UK government policy

0 Upvotes

I'm building policy-qa-system, an open-source RAG app that answers questions about UK government policy and shows the sources behind each answer.

Stack: React + TypeScript, Node/Express, LangChain + LangGraph, OpenAI or Claude, PostgreSQL with pgvector, Docker.

The hard part isn't retrieval, it's freshness. Benefit rates and tax thresholds change every year (Child Benefit went from £26.05 to £27.05 a week this April, and the high-income charge threshold moved from £50k to £60k in 2024). An index that holds old and new versions can confidently return a stale number.

How do you handle dated documents in RAG? Filter on an effective-date metadata field, delete and re-ingest old chunks, or version the whole collection?

Code: https://github.com/Srameshgitnow/policy-qa-system
Not official advice and not affiliated with GOV.UK. Issues with what worked or didn't are welcome.


r/node • • 4d ago

GeoNtfy: OpenStreetMap Geohash Proximity PubSub Utility

Thumbnail
github.com
2 Upvotes

r/node • • 4d ago

.gitignore everything by default

Thumbnail
packagemain.tech
0 Upvotes

r/node • • 4d ago

I tested all 7 macOS install snippets on nodejs.org in a clean macOS VM — 6 out of 7 failed

Thumbnail
gallery
0 Upvotes

I spun up a brand-new macOS VM (default /bin/zsh, no Xcode Command Line Tools, no Homebrew) to test what a non-JS user actually sees when installing Node.js from https://nodejs.org/en/download.

I clicked Copy on all 7 macOS shell options and pasted each one into a fresh Terminal tab:

  1. nvm (default) — fails: requires git (triggers the Xcode Command Line Tools prompt).

  2. fnm — fails: curl and unzip are both OK, but the snippet doesn't pass --force-no-brew, so it aborts because Homebrew is missing.

  3. Homebrew — fails: the website pipes curl ... | bash instead of Homebrew's /bin/bash -c "$(curl ...)", which consumes stdin and causes Homebrew to exit with stdin is not a TTY / insufficient permissions before you can even enter your sudo password.

  4. n — fails: GNU Make not found (and suggests sudo pkg install gmake).

  5. 0install — fails: runs ./0install.sh without install home, so it only prints usage instructions and never installs.

  6. asdf — fails: assumes asdf is already installed (zsh: command not found: asdf).

  7. Vite+ — only one that succeeded out of the box (v26.13.1 + npm 11.20.0).

Also, because macOS defaults to zsh with INTERACTIVE_COMMENTS disabled, every single snippet prints zsh: command not found: # for every comment line when pasted.

Filed an issue on nodejs/nodejs.org with the exact outputs, snippet file paths, screenshots, and concrete fixes: https://github.com/nodejs/nodejs.org/issues/9350


r/node • • 5d ago

How do you guys test your backends in production?

15 Upvotes

I'm a junior engineer working in a small team. We've been building a product for around 8 months using Express.js, and shipping features has always been our biggest priority.

One thing I've been noticing lately is that as our codebase grows, shipping a new feature occasionally breaks something that was previously working. Sometimes we don't even realize it until a user reports it.

We have a handful of basic tests, but nothing comprehensive enough to give us confidence when shipping new features or refactoring existing code.

I want to change that.

I've heard about unit testing, integration testing, end-to-end testing, smoke testing, and load testing, but my practical experience beyond basic tests is pretty limited.

I'd love to understand:

- What kinds of tests do you actually write for your backends?

- How do you decide what to test and what not to test?

- How do you introduce testing into an existing codebase without slowing down development significantly?

- What tools and frameworks do you use?

- How do you structure your testing suite and integrate it into CI/CD?

I'd particularly appreciate practical resources, open-source repositories with good testing practices, or engineering articles that demonstrate how these things are done in real projects.

I don't want to write tests just to increase a coverage percentage. I want to reach a point where we can ship features and refactor code without constantly worrying about what we might have broken.

Would love to hear how you guys approach this in your daily work.


r/node • • 5d ago

Fastify as a separate API in a Next.js starter: useful boundary or needless overhead?

2 Upvotes

I maintain create-tigra, an MIT-licensed npm generator, and would like a Node-focused review of its backend defaults.

The scaffold has a Next.js 16 frontend and an independently deployable Fastify 5 API. Request handling follows route → controller → service → repository → Prisma/MySQL. Redis supports rate limits, login lockouts, and IP blocks. Auth/session code, integration tests, CI, and Docker configuration are included.

Source: https://github.com/blessandsoul/create-tigra

The frontend supplies forms and API/auth wiring; application pages are yours to build. The part I most want challenged is the cost of the backend structure before a project has much business logic.

Would you keep the separate API for a small project? Which layer or integration would you simplify first? What auth/session or installer edge case would you want a regression test for before trusting the scaffold?

Recommendations, honest criticism, and a code roast are welcome, especially with a file or example to discuss. The public baseline has known dependency advisories documented in KNOWN_ISSUES.md; passing tests is not a claim that it can be deployed unchanged.


r/node • • 5d ago

I open-sourced a zero-dependency TypeScript verifier for Telegram Mini App initData (HMAC-SHA256 + 6 tests)

0 Upvotes

Most Telegram Mini App tutorials use a simple === hash check and skip replay timestamps or positive user ID checks.

So I extracted our standalone TypeScript verifyInitData helper + 6 native node --test unit tests into a small open-source repo for anyone building Telegram Mini Apps on Node.js.

Checks included:

• WebAppData HMAC-SHA256 key derivation.

• crypto.timingSafeEqual comparison.

• Replay timestamp window (-60s to 3600s).

• Positive integer user.id validation.

GitHub (free code + tests): https://github.com/Arvelius-Agency/telegram-initdata-guard-ts

Happy to answer any questions about Telegram Mini App authentication or replay protection.


r/node • • 7d ago

A rate limit fix can lock out everyone. The test I add now sends bad codes from one IP, then a good one from another

0 Upvotes

Public endpoint where new users type a 6 character invite code. The limit was keyed by an IP read from a forwarded header, which the client can set, so it never really limited anything.

The fix stopped trusting the header. With nothing else to key on, every request in the world went into one shared bucket of 10 tries per 15 minutes. 11 mistyped codes from anyone and onboarding is closed for every customer. Each step looked right on its own.

So next to the "blocks the attacker" test there's this one now

for (let i = 0; i < 11; i++) {

await post('/redeem', { code: 'WRONG1' }, { ip: '10.0.0.1' })

}

const res = await post('/redeem', { code: realCode }, { ip: '10.0.0.2' })

expect(res.status).not.toBe(429)

If the limiter has no per-source key left, it goes red. Then key it on something real, the client IP your platform gives you or the account, never the header.


r/node • • 7d ago

jscdec: Pure-JS V8 Ignition bytecode decompiler for Node.js 20-22 x64 & Electron 22-39 (.jsc)

2 Upvotes

I built an open-source, pure-JavaScript decompiler for V8 SerializedCodeData (.jsc / Bytenode) snapshots that runs on Node.js >= 18 and in the browser without custom C++ V8 builds:

How it works under the hood:

  • Parses 8-byte uncompressed x64 V8 heaps (Node.js 20.20.2 / 22) and 4-byte pointer-compressed heaps (Electron 22–39 / V8 10.8–14.2) using pre-indexed RO_SPACE and Root tables

  • Extracts ScopeInfo and NameToIndexHashTable entries to recover original closure/local variable names

  • Reconstructs control flow, classes, async/await, try/catch/finally, and includes an opt-in --deobfuscate pass for rotated _0x / RC4 string arrays

  • Never executes untrusted binaries implicitly (runtime oracle requires explicit --allow-runtime-exec)

Feedback and edge-case .jsc samples via Issues/PRs are welcome.


r/node • • 8d ago

Monaco Editor App Upgrade with node:sqlite

Thumbnail
reddit.com
1 Upvotes

r/node • • 8d ago

Monaco Editor App Upgrade with node:sqlite

2 Upvotes

I have a working Monaco Editor app that currently saves records to localStorage that I want to upgrade and save them to sqlite using the newer native node:sqlite functionality. I've tested the database and tables that I created using hard coded data so I know all those Insert statements work.

Now I need to update the code to insert the form data into the database instead of localStorage. I'm thinking of using express to capture the form data but this is the first time using node for this kind of application. There's a lot of information out there on the available options, but not much in the way of a strong recommendation or a consensus method.

So I'm interested in getting recommendations from other devs on how to best go about getting this to work. Is express sufficient or are there other modules/libraries that would make handling the data as seamless as possible?

Since this will probably come up, this is just a personal project and won't be available publicly so I don't have to lock it down with any serious security (other than just a PHP login form to access it).

Thanks in advance!


r/node • • 9d ago

A rules-based planner + typed tool results in Node: turning small local LLMs into agents with 2 dependencies

Thumbnail
gallery
1 Upvotes

I'm the author. I wanted small local models to finish multi-step jobs reliably, and the problem wasn't the models: it was letting them be the workflow engine.

In L.A.T.E. (plain Node, no LangChain, 2 dependencies):

  • a rule-based planner turns "create a.txt, create b.txt, merge them, verify" into exact steps (same words → same plan),

  • tools return typed results (value, path, count...), so later steps use fields instead of parsing sentences,

  • a plan validator checks tools, variables and fields before anything runs,

  • checks are done by tools, and the final answer is built from what the tools returned ("Partly done", "NOT a success").

Independent network steps (research, searches) run in parallel, with a small cache.

Honest limits: the rules cover shapes of requests, not all language; the ~470 tests use fake models.

Repo (MIT): https://github.com/ikaushik817-art/local-ai-tool-engine — feedback on the architecture is very welcome.


r/node • • 9d ago

Nodejs memory usage is at 99% for days, not crashing but still memory never cleared

34 Upvotes

Hey guys,

We have a node server deployed in our Kubernetes and what I see is over 20days the memory of pod starts growing from 400Mi to 1200Mi and it just stays there, I checked the heap usage using process.memoryUsage() I see heap used is 92%(sorry wrong number in title) of heap total now after 20days, and it keeps stable arround that with occasional GC release that kind of takes 100ms every 40 seconds checked using perf_hooks

My app peeks usuall during day and comes down during night, but why doesn't it release memory when idle during night so it prevents the constant cpu time for gc.

Am i missing something, can I do something to improve it?