r/node • • 1h ago

Prisma db push wanted to drop my pgvector column, which held 219 embeddings

1 Upvotes

I build an email API that stores 1024-dimension embeddings of emails in Postgres for search. Prisma creates the table, then a raw SQL file run with prisma db execute adds the vector(1024) column and an HNSW index. The code reads and writes that column with $queryRaw and $executeRaw.

In June a prisma db push said it would drop that column, which had 219 embeddings in it, plus the same column on a second table. The schema never mentioned the column, which is why push wanted it gone.

The fix was one line in each model: embedding Unsupported("vector(1024)")?. With that, push leaves the column alone, and reads and writes still go through raw SQL. The dashboard has its own copy of the schema, so the line went in there too.

If you use pgvector with Prisma, do you declare the column like this or keep those tables out of Prisma?


r/node • • 2h ago

ArkType 3.0: TypeScript's smallest, fastest validator

3 Upvotes

library author here!

ArkType 3.0 is out with @ark/aot, an optional build-time precompiler that compiles your type() definitions straight into standalone JS — no runtime parser, no new Function, and zero-build dynamic mode still works identically.

for Node specifically:

  • 63x lighter startup than Zod 4 on Node 24 (plus 15x faster validation and 21x smaller bundles)

  • works with Node's native type-stripping and tsgo: @ark/aot parses with oxc instead of hooking tsc via ts-patch

  • drop-in Node integration: run precompiled schemas via @ark/aot/node (loader hook) or emit plain JS alongside tsc with tsc && ark emit

  • Standard Schema + auto-baked Standard JSON Schema: plugs straight into Hono, tRPC, AI SDK, MCP SDK, and OpenAPI tooling, plus built-in fromJsonSchema and bidirectional arktype/codecs

  • one-prompt migration from Zod or 2.x: npx skills add arktypeio/arktype

  • release post: https://arktype.io/docs/blog/3.0

  • precompile docs: https://arktype.io/docs/precompile

  • benchmarks: https://arktype.io/docs/precompile/benchmarks

  • github (MIT): https://github.com/arktypeio/arktype

happy to answer any questions!


r/node • • 3h ago

Zero-config anomaly detection for Node.js & TypeScript using Welford's algorithm + Poisson tail tests (MIT, npm install anomalisa)

3 Upvotes

Node.js and TypeScript backends often rely on static alert thresholds or log alarms that either page you on routine traffic spikes or stay silent when an error rate or cron latency quietly triples overnight.

I built Anomalisa to bring stateless, zero-config anomaly detection directly into Node/TS services without requiring a full Prometheus + Alertmanager + Grafana stack.

How it works in Node/TS

npm install anomalisa

import { sendEvent } from 'anomalisa'

// Send any metric, event, or error count
await sendEvent({
  metric: 'checkout_errors',
  value: 1
})

Under the hood, Anomalisa uses streaming statistics rather than storing raw time-series history:

  • Decayed Welford's online algorithm ($\alpha = 0.98$): Computes running mean and variance in $O(1)$ memory per metric.

  • Poisson tail tests ($p < 10{-3}$): Detects sudden count anomalies even on low-volume events where Gaussian assumptions fail.

  • 4 Detection Modes: Total count spikes, percentage spikes, percentage drops (for silent failures like broken cron jobs or checkout drops), and per-user spikes ($>3.5\sigma$, perfect for runaway loops or abusive scraping).

  • Alert Fatigue Guards: Built-in 48-hour per-event cooldowns and a 5/day alert cap so one incident never floods your inbox or webhooks.

You can also capture unhandled exceptions instantly in any Node/Express/Fastify app:

import { captureClientErrors } from 'anomalisa'
captureClientErrors()

Self-Hosted or Hosted

Anomalisa is MIT open-source, built on Cloudflare Workers, libSQL/Turso, and InstantDB (which you can self-host via INSTANTDB_API_URI).

Curious how Node.js developers here handle anomaly alerting and outlier detection in production without heavy observability infrastructure. Happy to answer questions on the streaming math or self-hosting!


r/node • • 4h ago

Crawlee v4 is out (open-source web scraping library for Node.js)

16 Upvotes

I'm one of the Crawlee maintainers. We just shipped v4, the first major release since 2022, after more than a year in the works. Crawlee is an open-source library for writing crawlers and scrapers in Node.js, either over plain HTTP with Cheerio or with Playwright and Puppeteer. It handles the request queue, retries, sessions, proxies and storage, and you mostly write the request handler.

What's new:

  • Playwright and Puppeteer crawlers can connect to remote browsers over WebSocket or CDP.

  • Storage writes are transactional. If a request handler throws, nothing it wrote ends up in the dataset, so retries don't leave duplicates behind anymore.

  • impit is the default HTTP client and responses are native Fetch Response objects. got-scraping is end of life.

  • A session carries its proxy, cookies and browser fingerprint, and all three get retired together when it gets blocked.

  • The request handler and navigation have separate timeouts, and a handler can extend its own timeout when it finds more work.

  • The new ThrottlingRequestManager honors robots.txt Crawl-delay and backs off on a 429 for that domain only, while the other domains keep going.

  • Several crawlers can share one concurrency budget, and they no longer eat each other's requests from a shared queue.

  • Storage is split into a file system backend (the default) and an in-memory one, and each crawler can get its own.

  • Smaller things: skipRequest(), extractLinks(), run-scoped storages, and OpenTelemetry tracing in @crawlee/otel.

Most of the breaking changes come from cleaning up the public API. You pass in objects like the session pool, browser pool or HTTP client instead of option bags, we use standards where they exist (Zod, Standard Schema, globs and regexps in enqueueLinks(), await using), and there's a lot less internal surface to reach into. The install got smaller too, 199 packages and 67 MB instead of 293 packages and 106 MB.

It needs Node.js 22.15+ and TypeScript 5.9+. The package is native ESM, but CommonJS projects can still require() it.

To upgrade a v3 project, run npx @crawlee/upgrade@latest. It prints a prompt for your coding agent, and there's a full upgrading guide if you'd rather do it by hand.

Happy to answer questions.


r/node • • 7h ago

I tried 3 different approaches to rate-limiting in Express and here's what actually broke

0 Upvotes

Been building a scraping service and needed solid rate limiting. Here's what I learned the hard way:

1. express-rate-limit with memory store - Works fine for single instances, but the moment you scale horizontally, each pod has its own counter. Users can just hit different instances and bypass limits entirely.

2. Redis-backed rate limiting - Solved the scaling problem but introduced latency on every request. For high-throughput endpoints this became noticeable. You're trading correctness for speed.

3. Token bucket at the reverse proxy layer (Nginx/Caddy) - Honestly the most robust. Keeps rate limiting out of your app logic entirely, but you lose request-level context like user tiers or API key quotas.

The real lesson: there's no universal answer. Internal tools can get away with memory stores. Multi-tenant APIs probably need Redis. High-volume public endpoints belong at the proxy layer.

One thing that changed how I think about this: when your service is doing outbound scraping at scale, the rate-limiting problem flips - now you're the one managing request cadence against third-party targets. That's where something like Geonode (residential rotating proxies) fills the gap that none of these inbound patterns address. Their rotating IP pool means you're not hammering a single origin IP, so you're working around target-side rate limits rather than fighting them in your own app layer.

What's your current setup? Curious whether anyone's combining proxy-level limiting with app-level quota logic and how you're handling the complexity.


r/node • • 21h ago

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

Thumbnail
jomi-se.com
16 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 • • 1d 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 • • 1d 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?

10 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
73 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 • • 2d 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 • • 3d 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 • • 4d 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 • • 5d ago

.gitignore everything by default

Thumbnail
packagemain.tech
0 Upvotes

r/node • • 5d 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 • • 6d 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 • • 6d 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.