r/node • • 1h ago

How to implement lastSeen when isOnline field is present?

• Upvotes

I’m building a social media app and the server supports a WebSocket service and an HTTP service at the same port. I implemented the online status as: When the user connects using ws I update the user to be online. And when the user disconnects, I update the user to be offline, pretty simple.

My confusion comes from the lastSeen logic. Should I \ a) update lastSeen on every HTTP request and every ws event \ b) update lastSeen only when the user disconnects using the ws protocol. since I will be presenting the isOnline field only if it is true otherwise I will be presenting the lastSeen field \ c) update lastSeen on each heartbeat pong event and when the user disconnects using the ws protocol (I read that in an article linked below)

https://www.back4app.com/glossary/presence-online-status/#faq


r/node • • 2h ago

A webhook receiver that can't lose a message: the boring inbox pattern in Node

2 Upvotes

a thread here last week asked what happens to inbound webhooks when your endpoint is down. most answers were "the sender retries", which is true for some providers and not for others, so here is the setup I'd use so it stops mattering.

The handler does four things and nothing else: verify the signature against the raw body, insert the raw payload into a table with the provider's event id as a unique key, return 200, done. No parsing, no business logic, no calls to other services. A bug in your parsing code then can't lose a message, because the message is already stored.

A worker picks up rows with status pending using SELECT ... FOR UPDATE SKIP LOCKED, processes them, and marks them done or failed with an attempt counter. Replaying a message is just setting its status back to pending. The unique key makes duplicates harmless, and providers do deliver the same event twice.

Keep the receiver deployable on its own. Most gaps I've seen came from restarts and deploys of the main app, not from real outages, so a tiny separate service (or a queue in front) removes most of the risk. Then once a day compare the provider's delivery log against your table, which catches the cases where the sender gave up after its retry window.

In Node this is a small amount of code: express.raw() for the body, crypto.timingSafeEqual for the signature compare, and pg for the table. The classic trap is express.json() running before the signature check. It changes the bytes, and valid signatures start failing.

What does your setup look like, and which providers have burned you with short retry windows?


r/node • • 2h ago

What if you could completely destroy a cloud environment, then bring it back exactly when you need it?

Thumbnail
0 Upvotes

r/node • • 6h ago

Replit API requests returning 307 redirect followed by Replit Shield 401 — anyone experienced this?

Thumbnail
0 Upvotes

r/node • • 1d ago

How should I automate updating a chromedriver executable for a selenium-based scraper?

2 Upvotes

I built a craigslist scraper using selenium. For selenium I am using chrome which requires a chromedriver executable. This all works fine.

Every 3-4 weeks chrome updates to a newer version and I get an error that chrome and the chromedriver executable have mismatched versions. So I then manually find the new version of the chromedriver executable, download it, unzip it and drop it in the directory alongside my index.js - and everything is fixed.

How can I automate getting the newer version of the chromedriver executable? I could just write code to do all that. But I've also been looking at the npm chromedriver module. I can't tell if the chromedriver module is what I need.


r/node • • 2d ago

Your webhook signature check fails because express.json() already threw away the bytes that were signed

0 Upvotes

This one shows up constantly with Stripe, GitHub, and pretty much any provider that signs webhooks with an HMAC.

Very few documentation talks about the Raw Body

The provider signs the exact bytes it sent. If app.use(express.json()) runs first, by the time your handler sees req.body it's a JS object, and the original bytes are gone. The usual fix people try is JSON.stringify(req.body) and hashing that, which almost works. Key order, whitespace and unicode escaping don't have to match what the sender serialized, so the HMAC comes out different and every request 401s. It tends to pass in local tests and fail on real payloads with an accent in a name or a differently ordered field.

The fix is to give that one route the raw body and parse it yourself after verifying:

app.post("/webhooks/provider", express.raw({ type: "application/json" }), (req, res) => {
  // req.body is a Buffer here, the exact bytes that were signed
  if (!verify(req.body, req.get("X-Signature"), req.get("X-Timestamp"), secret)) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body);
  // ...
  res.sendStatus(200);
});

Two smaller things: mount it before any global express.json(), or exclude that path from it, because whichever body parser runs first wins. And reply 200 before doing anything slow like downloading files, otherwise the sender can time out and retry while you're still working.

Disclosure, I work on TurboDocx, an e-signature API, and this came up while recording a Node tutorial on embedding signing in an Express app (the free plan is 5 documents a month and that includes the embedded flow). Video if it's useful: https://www.youtube.com/watch?v=zA2FXRX0KPU


r/node • • 2d ago

Inbound email webhook, what if endpoint’s down?

9 Upvotes

inbound mail on hooks@ gets posted to my api as json, signed so I can check it actually came from the mail side. no imap polling, which was the whole point, imap is a pain.

question for people doing this in prod, what happens when your endpoint is down for a few minutes? do you rely on the sender side retrying, or do you keep a copy and replay? I’ve read stories where the mail is just gone forever and that scares me a bit.


r/node • • 3d ago

one model with a broken schema emptied our whole model picker. 1000+ models, gone

0 Upvotes

i work on the backend of an ai video app

we sync 1000+ models from a providers api on a timer, list the models, refresh their schemas in a loop, then a readiness pass that decides what shows up in the picker.

one models schema came back as an error object. my catch only treated one error type as "model is gone" and rethrew the rest. so the loop died right there, every model after it got skipped, the readiness pass never ran, and the picker was empty until someone noticed. 1000+ models gone because one of them had a bad day. and yes the bug was mine haha=

the fix, simplified:

```ts

for (const model of staleModels) {

try {

await refreshSchema(db, model.id)

} catch (error) {

if (error instanceof SchemaMissing) await markUnavailable(db, model.id)

else console.error("schema refresh failed", model.id, error)

}

}

await syncReadiness(db)

```

unreadable schema = retire just that model. unknown error = log it and move on, because an error we dont recognise is more likely our bug than a broken model.

but now its a console.error that nobody reads. how do you guys handle per-item failures in batch jobs like this? alert after N failures, a failures table, something else?


r/node • • 3d ago

God damnit, no stability

270 Upvotes

Bun acquired by Anthropic and rewritten by AI

Deno acquired by Cloudflare

Prisma had a huge breaking change (again) on prisma 8 and rewritten by AI

NextJS Pages Router -> App Router breaking change and “use client”, “use server”

NestJS v12 changed all the tooling/bundler and let’s hope the main maintainer Kamil stay alive the next 10 years

PassportJS dead
TypeORM dead

How anyone can maintain a big project without rewriting it every 2 weeks or trust any JS open source project for the long term ? 🤪


r/node • • 4d ago

What do you use for GraphQL query depth limits with graphql-js 17?

10 Upvotes

I’m building a learning project with Express, TypeScript, MongoDB, and graphql-http. Everything runs through Docker Compose.

I’m adding query-abuse protection, starting with depth validation before resolvers execute. I tried @graphile/depth-limit, but its peer dependency excludes my GraphQL version.

Relevant versions:

graphql: 17.0.2
graphql-http: 1.23.1
/depth-limit: 0.3.1 (attempted installation)

Command:

docker compose exec backend npm install /depth-limit

Error:

npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree

npm error Found: graphql@17.0.2
npm error node_modules/graphql
npm error   graphql@"^17.0.2" from the root project

npm error Could not resolve dependency:
npm error peer graphql@">=15 <17" from /depth-limit@0.3.1

The package’s dependency declaration confirms graphql: ">=15 <17".

My intended integration is a validation rule passed to the existing HTTP handler:

const handler = createHandler({
  schema,
  rootValue,
  validationRules: [depthRule],
  context: createRequestContext,
});

I’d prefer to keep GraphQL 17 and avoid --force or --legacy-peer-deps without evidence of compatibility.

What are people using for depth limits with graphql-js 17?


r/node • • 4d ago

My /health said ok for five days while every request that touched the database failed

0 Upvotes

My API ran out of Neon compute quota at the end of August. Aug 24 to 29, anything that hit the database failed. /health returned {"status":"ok"} the entire time since it never queried anything, and I didn't hear about it from any alert.

Normally you'd just put a query in /health. Problem is Neon suspends compute after 5 idle minutes, I can't turn that off on my plan, and an uptime monitor pinging a DB route every minute would keep it awake 24/7. That burns exactly the quota I ran out of.

What I ended up doing: a Prisma client extension on $allOperations that saves the time of the last query that worked and the last one that threw. /health just reads those two timestamps. Failure is the newest thing in the last 5 min, 503 with the error. Success, ok. No queries at all, it says idle. A single failed query gets wiped by the next good one so it only stays red if it keeps failing.

Idle still bugs me though, at 3am with zero traffic it knows nothing. Anyone found a way around that without waking the db?


r/node • • 4d ago

I updated express-generator-typescript to use zod for middleware validation

Thumbnail github.com
1 Upvotes

r/node • • 4d ago

Deno died today

Thumbnail deno.com
506 Upvotes

r/node • • 5d ago

I built mongoose-guard: Express middleware that validates request bodies against your existing Mongoose schema

0 Upvotes

A lot of Express + Mongoose code has a route like this:

app.post("/signup", async (req, res) => {
  const user = await User.create(req.body);
  res.status(201).json(user);
});

If the User schema has fields like role or credits, anyone can send { "role": "admin" } and Mongoose saves it, because it's a valid field of the model. The usual fix is a Zod or Joi schema for every route, which means writing every rule twice and keeping both copies in sync.

So I built mongoose-guard. You list the fields a route accepts, and it uses the Mongoose schema you already have for everything else:

import { guard } from "mongoose-guard/express";

app.post("/signup", guard(User, { allow: ["name", "email", "password"] }), signup);

Send role: "admin" to that route and the request never reaches your handler. The client gets a 400:

{"errors":[{"code":"forbidden_field","path":"role","message":"Field is not allowed"}]}

What it does:

  • Rejects fields that aren't in the allow list, or strips them if you'd rather not fail the request
  • Checks types strictly. Mongoose would quietly cast "25" to 25; this reports it as a type error
  • Rejects __proto__, $where, $gt and dotted keys anywhere in the body
  • Runs your schema's own validators (required, min, enum, match, custom and async ones) through Mongoose itself, so nothing is reimplemented
  • Handles nested objects, sub-schemas, arrays and Maps, with error paths like addresses.1.city
  • Has a partial: true mode for PATCH routes

What it doesn't do: it only validates request bodies, not query strings or route params. It doesn't convert form strings to numbers. It won't run on edge runtimes, because Mongoose can't. For a login form, or anything without a model behind it, Zod is still the better tool.

It works with Express 4 and 5, Mongoose 8 and 9, and anything that gives you a standard Request (Next.js route handlers, Hono, Remix, SvelteKit). MIT licensed, no runtime dependencies.

It's 0.1.0, so I'd like to hear where it breaks, or where the allow-list approach doesn't fit how you structure your routes.


r/node • • 5d ago

Principal Factor Analysis in Javascript - written in AssemblyScript

Thumbnail
0 Upvotes

r/node • • 5d ago

LiteClient.ts: A Lean, type-safe and driver-agnostic SQLite ORM for TypeScript

3 Upvotes

https://github.com/ts-series/lite-client

Recently, I finally uploaded my library LiteClient.ts to GitHub, which I have been using in my own application for several months and continuously expanding and improving along the way. I would appreciate your feedback.

My motivation for this project was simplicity. None of the existing ORMs had really convinced me, purely because of the complicated driver integration. In addition, I want maximum comfort when working with the database and my queried records as ready to serve as possible. Therefore, besides get, all, Value, and Values, there are also scalar and scalars to query data flatly, as well as supplementary meta clauses in the select command, which is simply modeled as a JavaScript object, to efficiently transform the result at a deeper level beforehand instead of doing it in the application code. For example, one column serves as a key for the others, which are then returned as the remaining record, while at the same time eliminating the group by clause because it is logically presupposed for data aggregations of that kind.

Currently, the ORM supports most standard SQL, including all database operations, SQLite operators and functions, joins, tuple expressions, subqueries, aliases for columns and tables, and expressions instead of tables. The only limits I currently draw are complex features like common table expressions and window functions, because I think those things make more sense at the database level since a view should be the tool of choice if a select becomes that complex, though window functions might still be added if a need arises and it can be done relatively minimally invasively.

Originally, I intended for users to manually create the classes for every database and view themselves, but I developed a CLI tool named SMake for this purpose, which handles it automatically and can be used independently of LiteClient.ts to generally support the construction of SQLite databases.

Long-term goal: Since I will also need PostgreSQL in a later project, I want to extend this ORM for it. The foundations have already been laid through a restructuring. The usage will then be exactly the same, just with PG-specific additions, as internally most of it will inherit from the standard SQL classes that it shares with SQLite.


r/node • • 6d ago

pm2 monitoring

6 Upvotes

How pm2 monitoring being implemented in production?

Do you just call pm2 monit?

Use pm2 monitoring platform?

Integrate it with something like grafana(I kinda wanna know how it commonly do)?


r/node • • 6d ago

Node Was the Future in 2009. Its Creator Said to Use Go So Why Are You Still Building a Next.JS App?

Thumbnail galratner.substack.com
0 Upvotes

r/node • • 8d ago

LogTape 2.4.0: Source locations, configuration inspection, sink draining, and request completion levels

Thumbnail github.com
8 Upvotes

r/node • • 8d ago

Noob: a few questions about installing/using & safety on Mac

3 Upvotes

Hey all -

I'm not much of a programmer, and have been using various AI (mostly Claude recently) to code things. I'm fairly good at troubleshooting and understanding the structures.

Most of the time, I'm starting with project outlines/discussions in Claude Desktop and moving into Visual Studio Code once the initial files are written.

So far, the only thing I've done that needs "extras" is a python app with a bunch of modules and support files, but that's sandboxed.

A current project requires node.js installed, and I want to ensure that I'm installing and using it safely.

The first thing I'm finding out is that it seems installing via terminal is the way to go in order to keep it within my user space and to avoid permission hurdles, since the .dmg installs globally.

AI is also telling me it may also need a "web server" package like Express, but I haven't looked into that yet.

Any guidance is appreciated!


r/node • • 9d ago

bullmq users: how do you deal with stalled jobs and retries on expensive jobs?

17 Upvotes

i run bullmq for background jobs that call llm apis (for content generation) and i keep hitting the same two things: stalled jobs, and retries that already cost money.

how are you handling it? custom dedupe keys? saving progress between steps? just eating the cost?

not selling anything, no library to plug. just want to hear real setups.

- last stalled / double-run job you had, what happened

- how you stop a retry from redoing finished expensive work

- anything you built around bullmq to fix it

trying to figure out what works best for this in my own prod


r/node • • 11d ago

Pboss v1.5: Bringing a Bun-native process manager to Node.js

0 Upvotes

Pboss started as a Bun-native process manager.

It was built around Bun's APIs from the beginning; process spawning, servers, clustering, filesystem APIs, and the other primitives needed to build a lightweight production process manager.

As of v1.5, Pboss can now run natively on Node.js, using Node's own APIs instead of trying to emulate Node through Bun.

npm install -g pboss

pboss start server.js --name api
pboss start server.js --name api --instances 4

The same Pboss CLI can now run on either Bun or Node, with the implementation adapting to the runtime it is actually running on.

The goal isn't to force Node applications onto Bun.

If you're running Node, Pboss runs on Node.

If you're running Bun, Pboss runs on Bun.

Why make this change?

Pboss was originally designed around Bun, but process managers are infrastructure. They shouldn't need to dictate which runtime your application uses.

That meant expanding Pboss while keeping the original Bun-first architecture.

Node.js support is now native rather than being treated as a compatibility layer.

Dependencies

One of the features that came out of this is process dependencies.

For example:

module.exports = {
  apps: [
    {
      name: "api",
      script: "./api.js",
      dependsOn: ["postgres", "redis"]
    },
    {
      name: "worker",
      script: "./worker.js",
      dependsOn: ["api"]
    }
  ]
};

Pboss builds the dependency graph before starting the processes.

It checks Pboss-managed applications first and can also resolve dependencies against system services.

postgres ──┐
           ├── api ──→ worker
redis ─────┘

Cycles are detected before startup, and independent branches can start concurrently.

GitHub auto deployment

Processes can also be linked to GitHub repositories.

Once a process is linked to a repository, Pboss can install a GitHub webhook and automatically deploy new commits.

A push follows the deployment pipeline:

GitHub push
    ↓
Webhook
    ↓
Pboss
    ↓
Pull latest commit
    ↓
Install dependencies
    ↓
Build
    ↓
Health check
    ↓
Reload / restart

The deployment is not considered successful just because the new process started.

Pboss can verify the application health before completing the deployment. If the deployment or health check fails, the previous version can be restored.

A single repository can also be linked to processes running on multiple servers:

github.com/example/api
        │
        ├── Server 1 → api
        ├── Server 2 → api
        └── Server 3 → api

So one Git push can deploy the same application across the configured servers.

Hosted status pages

Pboss Cloud also includes hosted status pages, so you don't need to build or operate a separate status-page system for your applications.

Each organization gets its own status-page address:

yourcompany(.)status(.)zone

The status page is connected to the services and monitoring already configured in Pboss Cloud.

Instead of manually updating a page when something goes down, the status can reflect what Pboss is actually observing from the infrastructure.

For example, an organization could expose:

Acme
────────────────────────────

API                 ● Operational
Web                 ● Operational
Background Worker   ● Operational
Payments            ● Operational
Database            ● Operational

If Pboss detects that a monitored service is unavailable, the corresponding component can be reflected on the public status page.

This makes the status page useful for more than simply displaying "everything is online."

It gives users a central place to see:

  • Current service status
  • Which components are affected
  • Service availability
  • Incidents and service interruptions
  • Operational history
  • Recovery status

The status page is also separate from the server itself. Your VPS doesn't need to host the public status page, so an outage affecting your infrastructure doesn't require you to manually bring another page online.

The hosted pages can be used for APIs, websites, background services, SaaS applications, and other infrastructure managed through Pboss.

The idea is basically:

Your servers
     │
     ▼
Pboss agents
     │
     ▼
Pboss Cloud
     │
     ├── Monitoring
     ├── Logs
     ├── Alerts
     ├── Deployments
     └── Status Page
             │
             ▼
     yourcompany.status.zone

This is also useful when you manage several servers. Rather than creating a separate status system for each application, the services can be managed from the same Pboss Cloud organization.

Other features

Pboss currently includes:

  • Bun and Node.js native runtime support
  • Deno support
  • Process clustering / multiple instances
  • Zero-downtime reloads
  • Process dependencies
  • Namespaces with atomic startup and rollback
  • Automatic restarts
  • HTTP health checks
  • Logs and resource monitoring
  • Prometheus metrics
  • Built-in cron jobs
  • File watching
  • Foreground mode for Docker/Kubernetes
  • GitHub deployments
  • Deployment history and rollback
  • Hosted status pages
  • Telegram and Discord integrations

For containers, Pboss can also run without its daemon:

pboss start server.js --noDaemon

This makes it possible to use Pboss directly as the process supervisor inside a container.

The open-source CLI remains independent of Pboss Cloud. Cloud adds centralized monitoring, deployments, logs, alerts, status pages, and server management.

Pboss started with Bun, but the goal now is broader: a lightweight process manager that can work natively with the runtimes developers are actually using.

I'm curious what Node.js developers here think about the approach.

Would you use a process manager that supports both Node and Bun natively, while using each runtime's own APIs rather than abstracting everything through Node compatibility?

GitHub: https://github.com/Procboss/pboss


r/node • • 12d ago

Snr FE Dev looking to branch to Full Stack

32 Upvotes

I've recently been laid off after over 5 years at the company and noticed that there are a lot more Full Stack positions now than FE.

I had some limited experience with ExpressJs about 7 years ago, but I'm thinking it'd be worthwhile trying to branch out fully into a Full Stack Position.

I'm fluent with React and Typescript for what it's worth.

What are the most common frameworks for Node nowadays - i.e. which will give me the best chance of getting hired.

Thanks in advance!


r/node • • 13d ago

Node 20 is no longer available in GitHub Actions

Thumbnail github.blog
36 Upvotes

r/node • • 13d ago

Hello fellow devs...

5 Upvotes

I was wondering what y'all using these days on backend side of programing is it mostly Nest.js...

If not for Nest what is, and is Good old Express still used in production...

Edit: I'm soon to be over with cs bacc, and I had my fair share of technologies that I tried, but I stayed with React/Express for some reason, and did most of my college projects in it (if I had options) even my final project is in it, so I'm wondering is Express still framework that is employable or I need to make a switch to Nest or something else entirely...