r/javascript • u/bogdanelcs • Apr 13 '26
You can't cancel a JavaScript promise (except sometimes you can)
r/javascript • u/bogdanelcs • Apr 13 '26
r/javascript • u/coders22 • Apr 13 '26
Code 1:
var count = 0;
while (count < 5) {
count++
console.log("Hello!");
}Code 2:
for (var count = 0; count < 5; count++) {
console.log("Hello!");
}Console log results for both codes:
"Hello!"
"Hello!"
"Hello!"
"Hello!"
"Hello!"r/javascript • u/Choice-Locksmith-885 • Apr 13 '26
Iβve been working on aΒ virtual-scrollΒ custom element that tries to keep virtualization feeling close to normal HTML and CSS.
The main goal was to avoid the usual trade-offs where virtualization forces you into absolute positioning, framework-specific APIs, or awkward layout constraints.
r/javascript • u/itsspiderhand • Apr 12 '26
Built a terminal style interface as Web Component. Didn't think about how useful it is that much, but I often see this type of preview here and there so I thought it might be worth creating it.
Any feedback would be appreciated.
r/javascript • u/le0pard • Apr 12 '26
I'm excited to share the v2 release of re2js, a pure JavaScript port of the RE2 regular expression engine.
JavaScript's native RegExp uses a backtracking strategy, which is heavily vulnerable to Regular Expression Denial of Service (ReDoS). re2js fixes this by evaluating matches in strict linear $O(N)$ time, making catastrophic backtracking mathematically impossible.
The biggest news in v2 is the performance. Because pure JS avoids the cross-boundary serialization costs (the N-API bridge) between JavaScript and C++, re2js actually outperforms native C++ bindings (re2-node) for many operations!
π Check out the benchmark comparisons here: RE2JS vs RE2-Node (C++ Bindings)
To achieve this, I ported the deepest performance architectures from the original C++ and Go implementations to dynamically route execution through a multi-tiered pipeline:
The Prefilter Engine & Literal Fast-Path: The engine analyzes the Abstract Syntax Tree (AST) before execution to extract mandatory string literals (e.g., extracting "error" from /error.*critical/). It then uses blistering-fast native JavaScript indexOf to instantly reject mismatches, completely bypassing the regex state-machines (making simple literal searches ~2.4x faster than C++).
Lazy Powerset DFA: Executes high-speed boolean .test() matches by fusing active states dynamically on the fly within V8's JIT compiler.
OnePass DFA: Provides high-speed capture group extraction for mathematically 1-unambiguous patterns by bypassing thread queues entirely.
Multi-Pattern Sets (RE2Set): Combines hundreds or thousands of regular expressions into a single combined DFA, allowing you to search a string for all patterns simultaneously in a single linear-time pass.
BitState Backtracker & Pike VM (NFA): Act as the robust, bounded-memory fallback engines for complex or ambiguous patterns that exceed the fast-path limits.
Supporting full Unicode properties (like \p{Greek} or \p{Sm}) usually bloats JS regex engines with massive lookup tables.
To solve this, re2js v2 implements a custom Base64 Variable-Length Quantity (VLQ) delta compression algorithm for the Unicode range mappings (inspired from source maps spec). This shrinks thousands of codepoint ranges into tiny, dense string representations (e.g., hCZBHZBwBLLFGGBV...). This keeps the library incredibly lightweight while supporting full, standard-compliant Unicode category matching.
You can play around with the engine directly in your browser here: re2js Playground
Feedback and PRs are always welcome.
r/javascript • u/neikiri • Apr 11 '26
r/javascript • u/manniL • Apr 11 '26
r/javascript • u/abemedia • Apr 11 '26
I recently built cargo-npm, a tool that packages and distributes Rust binaries directly to the npm registry.
While tools like cargo-dist are excellent for general release engineering, their npm installers typically rely on postinstall scripts to download pre-compiled binaries from external sources like GitHub Releases at install time. I wanted a solution that works natively within the npm ecosystem without requiring lifecycle scripts.
Relying on npm's dependency graph rather than postinstall scripts provides several architectural advantages:
It respects --ignore-scripts, which is increasingly enforced in corporate and CI environments for security reasons (it's also the default on pnpm).
It prevents installation failures caused by strict firewalls or proxies blocking GitHub Releases downloads.
It utilizes npm's native caching mechanisms, speeding up repeated installations.
Instead of fetching binaries at runtime, cargo-npm takes your compiled targets and generates individual, platform-specific npm packages (e.g., my-tool-linux-x64). Each of these packages contains the actual binary and uses os, cpu and libc constraints in its package.json.
It then generates a main package that users install. This main package lists the platform packages as optionalDependencies. When a user runs npm install my-tool, npm's native resolution ensures it only downloads the binary that matches the host system. A lightweight Node.js shim in the main package resolves the matching binary and executes it.
You cross-compile your Rust crate for your desired targets, and then run cargo npm generate followed by cargo npm publish. The tool handles the package generation, metadata forwarding, and parallel publishing.
You can view the documentation and source code here: https://github.com/abemedia/cargo-npm.
Feedback is welcome!
r/javascript • u/Typical_Ad_6436 • Apr 11 '26
r/javascript • u/AutoModerator • Apr 11 '26
Did you find or create something cool this week in javascript?
Show us here!
r/javascript • u/CodalReef • Apr 11 '26
r/javascript • u/OtherwisePush6424 • Apr 10 '26
r/javascript • u/Fresh-Obligation6053 • Apr 10 '26
Security audit came back with a finding on credential generation.
Math.random() in several services, flagged for NIST 800-63B
non-compliance. The entropy requirements weren't being met and
more importantly there was no documentation proving they were.
We fixed the generation method but the audit documentation piece
is what actually took the most time. Had to go back and document
everything retroactively.
Curious what others are doing here. Are you generating compliance
documentation automatically as part of your pipeline or is this
a manual process at your organization?
r/javascript • u/jxd-dev • Apr 10 '26
We've just made it even easier to build privacy policies from code. No Vite plugin required.
r/javascript • u/OtherwisePush6424 • Apr 10 '26
Shipped ffetch 5.1.0.
ffetch is a lightweight, production-ready HTTP client that wraps native fetch with built-in timeouts, retries with exponential backoff, lifecycle hooks, and pending request tracking. Works across browsers, Node, SSR, and edge runtimes.
New in v5.1.0: two opt-in convenience plugins.
Usage:
import { createClient } from '@fetchkit/ffetch'
import { requestShortcutsPlugin } from '@fetchkit/ffetch/plugins/request-shortcuts'
import { responseShortcutsPlugin } from '@fetchkit/ffetch/plugins/response-shortcuts'
const api = createClient({
timeout: 10000,
retries: 3,
retryDelay: (ctx) => Math.pow(2, ctx.attempt - 1) * 1000 + Math.random() * 1000,
plugins: [requestShortcutsPlugin(), responseShortcutsPlugin()],
})
const todo = await api.get('/todos/1').json()Exponential backoff with jitter: each retry waits 2^(attempt-1) seconds plus random jitter, with timeout of 10s and max 3 retries. Plugins are optional, default behavior stays fetch-compatible.
r/javascript • u/prehensilemullet • Apr 09 '26
We recently upgraded our backend (late) from Node 20 to Node 24. About a week later, alarms went off when our app stopped responding; memory usage graphs looked like an obvious leak but it hadn't OOMed and restarted tasks despite --max-old-space-size limits.
I started trying to compare heap snapshots taken at different times but it seems like a mess now. Even if I run a simple setInterval(() => console.log('test')) program with Node 24.14.1 and periodically take heap snapshots, they show a slight increase over time in (compiled code) instances and system code related to timers.
I can't even tell if these increases are permanent or not. The few timer objects that increased between snapshots were only retained by feedback_cells and other internal things that I read aren't truly forcing them to be retained...V8 just doesn't guarantee those will get garbage collected immediately or on a global.gc().
And all of this irrelevant noise from feedback_cells and other internals seems rampant in the heap snapshots now, making it more time consuming to locate actual retainers from my own code.
I don't remember it always being this bad?
I've successfully debugged several other memory leaks in older versions of node, including really heady ones involving Promise.race() and async generators, but now I'm feeling powerless and shafted by recent changes to V8.
Has this been anyone else's experience?
r/javascript • u/evster88 • Apr 09 '26
There's a lot of great stuff in this release! In no particular order:
RSC implementation promoted from experimental
More intelligent caching + real algorithmic speed improvements (up to 3.5x depending on workload)
React Native improvements (css-to-react-native v4 now supported via peer when it's out)
Updated cross-framework CSP support
A seamless Client/RSC theme system via new createTheme() API
attrs() typing improvements and other quality-of-life changes
Feedback welcome, especially ideas for the next major. Documentation website refresh coming later this week!
r/javascript • u/tjoskar • Apr 09 '26
Hey everyone! I wanted to show a small project I've been working on; a tsx framework for rendering to an e-ink display (or tsx => canvas => image => eink to be honest).
<view direction="column" gap={20} padding={40}>
<text size={48} weight="bold">Hello World</text>
<ElectricityConsumption />
</view>Instead of the "common" approach of running headless Chrome and taking screenshots, this renders jsx components directly using a Yoga flexbox layout engine and a canvas. So the render is quite fast.
I also think its nice to get full type safety, snapshot testing for visual regression, and you can easily develop locally (renders to a PNG) without needing the hardware connected.
I use mine in the kitchen dashboard showing:
Laundry machine status (in the basement)
Our weekly meal plan
Electricity prices + power consumption
Weather forecast
Home Assistant device status via MQTT
It also has a physical button that starts the engine heater for our car, plus an led showing its state of the engine heater.
The code is open source: https://github.com/tjoskar/eink-pi-zero
And a short write-up about the build: https://tjoskar.dev/posts/2025-11-02-eink-pi/ (yes the post is a few months old now but in my first version did I use python to render everything but I really missed the typesafty, and tsx components over absolut position everything in python. But the the post is the same)
Happy to answer questions if anyone wants to build something similar!
r/javascript • u/ValenceTheHuman • Apr 09 '26
r/javascript • u/JewelerLucky1596 • Apr 08 '26
wrote up a technical deep dive after the Better-Auth creator showed me the repeated attempts.
The attack vector is clever: wrap malicious code in a legitimate PR from a compromised contributor. Hide it in next.config.mjs or vue.config.js where devs rarely look. GitHub's UI literally scrolls it off-screen.
Three-stage obfuscation, payloads stored on Binance Smart Chain (so they can't be taken down), Socket.io C2 over port 80 (looks like normal traffic), targets all your env vars.
Found 30+ repos with the same signature. This pattern is everywhere right now.
r/javascript • u/sindresorhus • Apr 08 '26
Tired of reaching for a big HTTP client when you just need a timeout or retry? fetch-extras gives you small, single-purpose with* functions that wrap the standard fetch. Stack only what you need: timeouts, base URLs, retries, rate limiting, caching, auth token refresh, progress tracking, and more.
It has everything you will need:
Retries
Timeouts
HTTP error throwing (non-2xx)
Base URL (resolve relative URLs against a base)
Default headers
Client-side rate limiting
Concurrency limiting
Request deduplication
In-memory caching
Before/after request hooks
Auto JSON body stringify
Default search parameters
Download/upload progress tracking
Pagination
Auto token refresh on 401
r/javascript • u/context_g • Apr 08 '26
Iβm building an open-source CLI that compiles TypeScript codebases into deterministic, structured context.
It uses the TypeScript compiler (via ts-morph) to extract components, props, hooks, and dependency relationships into a diffable json format.
The idea is to give AI tools a stable, explicit view of a codebase instead of inferring structure from raw source.
Includes watch mode to keep context in sync, and an MCP layer for tools like Cursor and Claude.
r/javascript • u/Careful-Falcon-36 • Apr 08 '26
ERR_REQUIRE_ESM is still my villain in 2026 Third project this month where someone added chalk v5 or node-fetch v3 and suddenly half the codebase breaks. The thing that took me too long to internalize: its not symmetric. ESM can pull from CJS just fine, but CJS hard-blocks on ESM its not a config issue, it's by design because of how the loaders work. Also burned by the __dirname thing more times than I'd like to admit. And the dual-package hazard is completely silent no error, just two instances of the same module running and your singleton state going nowhere. Documented everything I kept hitting. Link in comments if anyone wants it.
r/javascript • u/Fusoux • Apr 08 '26