AI 资讯
Event Loop - Entendendo uma das bases do Node
O Event Loop é o mecanismo responsável por decidir quando callbacks e continuidades de operações assíncronas devem ser executados. Ele não executa operações de I/O diretamente, mas organiza a ordem em que elas retornam para o JavaScript. Essa arquitetura permite que o Node.js mantenha uma única thread de execução para JavaScript, enquanto delega operações de rede, disco e sistema operacional para componentes especializados do runtime e do próprio sistema operacional. Início Quando iniciamos um processo Node.js, o runtime carrega o arquivo de entrada da aplicação e executa todo o código síncrono disponível na Call Stack. Somente após essa etapa o Event Loop passa a assumir o controle do fluxo da aplicação, verificando continuamente quais callbacks estão prontos para execução. │ timers │ └─────────────┬─────────────┘ │ v ┌───────────────────────────┐ ┌─>│ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ close callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ timers │ └───────────────────────────┘ Trecho retirado da documentação principal. Sobre o Event Loop Durante muito tempo tratei o Event Loop como um dos conceitos mais complexos do Node.js. Depois de estudar a documentação oficial com mais calma, percebi que a dificuldade não está no Event Loop em si, mas na quantidade de conceitos diferentes que normalmente são apresentados ao mesmo tempo: libuv, Call Stack, Promises, Microtasks, Sistema Operacional e I/O. Quando isolamos o papel do Event Loop, ele se torna surpreendentemente simples. Definindo os passos e apresentando o iceberg 🧊 O Event Loop não executa trabalho. Ele agenda tr
AI 资讯
Why setTimeout is Lying to Your Retry Logic
You've written retry logic. It probably looks something like this: async function withRetry ( fn , retries = 3 ) { for ( let i = 0 ; i < retries ; i ++ ) { try { return await fn (); } catch ( err ) { if ( i === retries - 1 ) throw err ; await new Promise ( r => setTimeout ( r , 200 * ( i + 1 ))); } } } You test it locally. You simulate a slow dependency like this: const fakeDB = async () => { await new Promise ( r => setTimeout ( r , 200 )); // simulate DB return { id : 1 , name : ' test ' }; }; Your retry logic works. Tests pass. You ship it. Then in production, your app starts dropping requests under load. The problem isn't your retry logic. It's your fake. Real dependencies don't have flat latency Here's what your Postgres instance actually looks like in production: p50: 5ms — half of all queries finish in under 5ms p95: 50ms — 95% finish under 50ms p99: 200ms — 99% finish under 200ms p99.9: 2000ms — that one unlucky query during a GC pause Your setTimeout(fn, 200) simulates the worst case, every single time. That's not how production works. And because it's not how production works, your retry logic has never actually been tested against reality. The bugs hide in the variance — not in the slow case, but in the unpredictability. What the real distribution looks like Latency in distributed systems follows a lognormal distribution . It's right-skewed: most requests are fast, a meaningful minority are slow, and a small tail is very slow. This shape comes from how real systems work: GC pauses — Java, Go, and even Node's garbage collector occasionally stops the world Cold caches — first query after a cache miss is always slower Network jitter — packet routing isn't deterministic Noisy neighbors — other workloads on the same hardware compete for resources Connection pool exhaustion — when all connections are busy, new queries wait None of these are constant. They're random, rare, and multiplicative — which is exactly what produces a lognormal shape. Why this matters fo
AI 资讯
I put my Claude Code sessions on Discord — and now it's a one-line plugin
About 7,000 developers install a little tool of mine every month. It has 7 GitHub stars. I think about that gap a lot — but it also means thousands of these cards are quietly running in Discord right now, which is the whole point. It's called claude-rpc , and as of today you can install it from inside Claude Code itself. What it is claude-rpc is a small Node daemon that takes the lifecycle events Claude Code already fires — session start, each tool call, token counts — and turns them into a live Discord Rich Presence card on your profile: current model, project, what tool is running, plus lifetime stats. Your friends see what you're building; you get a year heatmap of your own work. It's free, open source, and has zero runtime dependencies — the Discord IPC client is hand-rolled, so the entire supply chain fits in a single review. The new part: a Claude Code plugin Two lines, in the editor: /plugin marketplace add rar-file/claude-rpc /plugin install claude-rpc@claude-rpc The card shows up on your next session. That's it. The plugin itself is deliberately thin — one SessionStart hook that runs the same installer you'd run by hand ( npx claude-rpc@latest setup ) once, in the background, then gets out of the way. Claude Code measures it at ~0 tokens of context per session. The real package still does the real work: wiring hooks, holding Discord's local socket, starting at login. It's now the fifth way to install the same tool — npx , a curl one-liner, Homebrew, a Windows exe, and now this — so pick whatever fits your setup. How it actually works No magic: 5 hooks, one small state file, and a daemon that holds Discord's local socket. No polling, no network calls, no telemetry you didn't opt into. If you want to read it, start with src/discord-ipc.js . Try it Site + build log: https://claude-rpc.vercel.app Source: https://github.com/rar-file/claude-rpc Built solo, on weekends. If one of those 7,000 cards ends up being yours, a GitHub star is the cheapest possible way to
AI 资讯
Day 39 of Learning MERN Stack
Hello Dev Community! 👋 It is officially Day 39 of my non-stop run toward full-stack MERN engineering! Yesterday, I mapped out basic HTTP verbs like GET and POST. Today, I advanced into Prashant Sir's (Complete Coding) backend masterclass to tackle one of the most critical core operations: Handling Data Streams and Body Parsing . When a user submits a form or uploads data, the server doesn't receive the file all at once. It arrives as an asynchronous stream of network data chunks. Today, I learned how to collect and decode those packets natively! 🧠 Key Learnings From Node.js Lecture 7 (Streams & Buffers) Node.js is designed to be non-blocking and memory-efficient. Here is the technical breakdown of how it intercepts client payloads: 1. Inbound Streams & Data Chunks I learned that incoming POST data is treated as a Readable Stream . Instead of loading a massive data file into the server memory instantly, Node transmits the payload in tiny pieces called Chunks (hexadecimal binary data). 2. Event Listeners for Requests ( req.on ) Natively, we don't have an instant req.body object. We have to listen to the network events on the incoming request stream: req.on("data", (chunk) => { ... }) : Fires every single time a fresh chunk of binary data arrives at the network interface. We push these raw chunks into a temporary array. req.on("end", () => { ... }) : Fires automatically once the stream concludes and all chunks have arrived safely. javascript if (req.url === "/submit" && req.method === "POST") { let body = []; req.on("data", (chunk) => { body.push(chunk); // Collecting raw binary chunks }); req.on("end", () => { // Concatenating and converting hexadecimal binary buffers into a readable string layout let parsedBody = Buffer.concat(body).toString(); console.log("Received Form Payload:", parsedBody); res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Data received and parsed successfully!"); }); }
AI 资讯
Production RBAC patterns for Go and Node startups
A founder told me last year: "We need admin features shipped by Friday. Can we just hardcode the roles for now?" That was 7 months ago. They're still paying for that decision today. This article is the breakdown I wish I had given them before that Friday — the patterns that separate a quick MVP version of RBAC from one that won't bite you back in six months. If you're a startup CTO, technical founder, or senior engineer about to ship admin/dashboard features for the first time, this is for you. The 4 signs your RBAC is a time bomb I've reviewed this exact pattern in 5+ early-stage codebases. Every one of them eventually hit the wall. Look for these signs: 1. Roles hardcoded in the JWT { "sub" : "user_123" , "role" : "admin" } Simple. Until you need to: Add a new role → migration + token refresh strategy Give one user a temporary elevated permission → "we'll just reissue tokens" Audit who had admin last month → good luck 2. Permission checks scattered across 40+ controllers // In every single handler: if user . Role != "admin" { return c . Status ( 403 ) . JSON ( ... ) } By the time you have 30 endpoints, you've made the same mistake 30 times. Refactoring is a full sprint. 3. One admin superuser that can do everything Until a sales rep accidentally deletes a customer record because they were elevated to admin "just for that one task last week." 4. Zero audit trail When the data goes missing, your only investigative tool is git blame on the source code and a desperate grep through CloudWatch logs. If you've nodded at any of these — keep reading. The real problem: policies-as-code Most teams treat permissions like business logic. They live in source files, gated by if statements, deployed with the rest of the code. This is the original sin. Code changes need deploys. Permissions change daily. When marketing onboards a new role next quarter, when a customer success rep needs view-only access to billing, when legal asks "who could have read this customer's data on Tuesda
AI 资讯
Day 38 of Learning MERN Stack
Hello Dev Community! 👋 It is officially Day 38 of my unbroken streak toward mastering the MERN stack! Yesterday, I learned how to extract query strings from the URL bar. Today, I took a massive step forward into full-stack backend architecture by diving into Prashant Sir's (Complete Coding) roadmap to master HTTP Request Methods . Up until now, our server treated every incoming request the same way. Today, I learned how to make the backend execute completely different actions based on the "intent" (HTTP Verb) of the user! 🧠 Key Learnings From Node.js Lecture 6 (HTTP Verbs) An endpoint is no longer static when you map request methods against it. Here is the technical breakdown of what I locked down today: 1. Cracking req.method I discovered that the incoming Request object holds a crucial property called req.method . This tells the server exactly what action the client wants to perform. 2. The Big Four Core Methods GET: Used when the user simply wants to read or fetch data from the server (e.g., viewing a product page). POST: Used when the user wants to securely send or create new data on the server (e.g., submitting a signup form). PUT/PATCH: Used to update existing data records. DELETE: Used to wipe a specific data entry from the server storage. javascript const http = require("http"); const server = http.createServer((req, res) => { if (req.url === "/api/data") { if (req.method === "GET") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Fetching and reading secure database records..."); } else if (req.method === "POST") { res.writeHead(201, { "Content-Type": "text/plain" }); res.end("Securely creating and injecting new data into the server!"); } } else { res.end("Standard Route"); } }); server.listen(8000);
AI 资讯
Day 37 of Learning MERN Stack
Hello Dev Community! 👋 It is officially Day 37 of my continuous streak toward mastering the MERN stack! Yesterday, I configured clean structural routing to map pages like /about or /contact . Today, I advanced further into Prashant Sir's (Complete Coding) backend roadmap to tackle an essential data communication concept: URL Parsing and Query Parameters . When a user searches for something or filters products on an e-commerce platform, that data is passed directly inside the URL string. Today, I learned how to intercept and decode that data natively! 🧠 Key Learnings From Node.js Lecture 5 (The URL Module) An incoming URL is much more than just a text path; it is a complex structured object. Here is the technical breakdown of how I dissected it today: 1. Ingesting the Native url Module I explored Node's legacy and modern URL parsing engines. By passing the raw req.url string into the parser, Node breaks down the web address into a fully accessible metadata object. 2. Dissecting Pathname vs Query String I learned the difference between the structural endpoint location and the dynamic data payload: Pathname: The core location path (e.g., /search or /api/products ). Query: The actual data key-value strings attached after the question mark ? (e.g., ?name=ali&id=7 ). javascript const http = require("http"); const url = require("url"); const server = http.createServer((req, res) => { // Parsing the URL path and query parameters together cleanly let parsedUrl = url.parse(req.url, true); let pathname = parsedUrl.pathname; let queryData = parsedUrl.query; // Converts query text into a clean JS Object! if (pathname === "/search") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end(`Searching logs for user: ${queryData.name} with ID: ${queryData.id}`); } else { res.end("Standard Endpoint View"); } }); server.listen(8000);
AI 资讯
Headless Browser Detection in 2026: What Still Trips Up Playwright
Playwright is the best browser automation library in 2026. It's also the most fingerprinted, the most detected, and the most patched in anti-bot databases. If you're running default Playwright against any platform with serious anti-bot defenses, you're getting flagged. We learned what's left of the cat-and-mouse game the hard way building HelperX . This article is what still trips up Playwright today — beyond the well-known navigator.webdriver flag, which everyone fixes in week one. The detection surface has shifted dramatically since 2022. The classic tells (PhantomJS, missing plugins, undefined chrome object) are largely solved. The new battleground is more subtle: CDP protocol artifacts, behavioral inconsistencies, and side-effects of the Playwright runtime that aren't part of the public API. What stopped working in 2024-2025 Detection on the platforms we monitor has gotten dramatically better in the last 18 months. A few things that worked in 2023 and stopped working since: Generic navigator.webdriver = undefined patches — detectable via Object.getOwnPropertyDescriptor if you do it naively Patching Notification.permission — modern detection cross-references with Permissions.query() Faking window.chrome — the property structure changed; old fakes are missing newer subkeys Setting a single User-Agent profile — detection now expects Client Hints to match Empty navigator.languages — flagged as suspicious; needs at least 2 entries These were all "set it once, ship it" fixes. The current generation of detection requires ongoing engineering. CDP artifacts: the deepest tell The Chrome DevTools Protocol (CDP) is how Playwright controls the browser. The browser exposes signals that it's being controlled, and modern detection looks for them specifically. Symptom: Runtime.evaluate artifacts When you run await page.evaluate(() => ...) , Playwright uses Runtime.evaluate under the hood. The evaluated script runs in a special isolated world. If the page can detect that an isola
AI 资讯
How to Call Windows Native APIs in Electron
How to Call Windows Native APIs in Electron Calling Windows native APIs in an Electron app feels like wanting to see the ocean but only having a map. After some trial and error, I've found a few paths—writing this article serves as a record and a guide for others who might follow. Background When building Electron desktop applications, you inevitably need to interact with the operating system. On Windows, these requirements are quite common: Calling Windows Store APIs for in-app purchases Handling file system virtualization specific to Windows Store apps Obtaining system-level permissions and resources Interacting with Windows Runtime (WinRT) components Electron is fundamentally a Node.js environment, and Node.js doesn't natively provide direct access to Windows native APIs. A bridge is needed between the two. It's like trying to communicate with a friend who doesn't speak Chinese—you need a translator. Electron is written in JavaScript, Windows APIs in C/C++. The language barrier requires building a bridge. That's the harsh reality of the code world. About HagiCode The solutions shared in this article come from our practical experience with the HagiCode project. HagiCode Desktop needs to call Microsoft Store APIs to handle subscription purchases and license management, which is why we developed a set of technical solutions. After all, necessity drives innovation—that's a truth. Technical Solution Comparison When calling Windows native APIs in Electron, there are several mainstream approaches to choose from. Each has its applicable scenarios—like different tools in a toolbox, they work best when used in the right place, otherwise just add trouble. Solution Applicable Scenarios Pros Cons dynwinrt WinRT APIs (e.g., Store API) Type-safe, auto-generated bindings, modern JavaScript support Only supports WinRT APIs, requires Windows SDK Native Node.js Extensions High performance, any Windows API Complete control, optimal performance Requires C++ development skills, comple
AI 资讯
Agent Accounts Quickstart in Node.js
Provisioning a working email mailbox from Node.js takes less code than the average OAuth callback handler. No consent screen, no token refresh job, no provider SDK — one fetch call returns a grant ID, and from there the mailbox sends, receives, and RSVPs to calendar invites. That's the pitch for Nylas Agent Accounts , hosted email-and-calendar identities you control entirely through the API. They're in beta, and the official quickstart promises a working account in under 5 minutes. The docs show it in curl; here's the same flow in JavaScript. What you need Two things: an API key, and a registered domain for the mailbox to live on. For testing, the zero-DNS path is a *.nylas.email trial subdomain registered from the Dashboard — addresses like test@your-application.nylas.email work immediately. For production you'd register your own domain (the Dashboard generates the MX and TXT records to publish, and verification is automatic once they propagate), but the trial domain is fine for this walkthrough. export NYLAS_API_KEY = "nyk_..." Create the mailbox The endpoint is POST /v3/connect/custom — the same Bring Your Own Auth route used for other providers — with "provider": "nylas" . Unlike OAuth providers, there's no refresh token in the body; just the address: const BASE = " https://api.us.nylas.com " ; const headers = { Authorization : `Bearer ${ process . env . NYLAS_API_KEY } ` , " Content-Type " : " application/json " , }; const res = await fetch ( ` ${ BASE } /v3/connect/custom` , { method : " POST " , headers , body : JSON . stringify ({ provider : " nylas " , settings : { email : " test@your-application.nylas.email " }, }), }); const { data } = await res . json (); const grantId = data . id ; // save this — every later call needs it That grantId is the whole handle. The mailbox behind it is live as soon as the response comes back, and it works with every existing endpoint — messages, drafts, folders, calendars, events, webhooks. One optional field deserves a menti
AI 资讯
Translating 'I missed you' so it doesn't land like a form letter
I was trying to tell someone something real in her first language — not "I missed you" from a dropdown, but the version that sounds like a person said it. Google Translate gave me one answer. No indication whether it was what you'd text at midnight or what you'd write in a letter to someone's grandmother. That's the failure mode of literal translators: one output, no register, no sense of what you're actually choosing between. konid returns 3 options per query, ordered casual to formal, with the register explained and a cultural note on the difference between them. For Mandarin or Japanese, audio plays through your speakers via node-edge-tts — no API key, no browser tab — because reading a pinyin romanization and actually hearing the tone contour are two different things. The vowel length in Korean, the pitch drop in Japanese, the stress pattern in Arabic: you don't internalize those from text. You internalize them from hearing them repeated back while you're still in the context of trying to say something. The setup for Claude Code is one line: claude mcp add konid-ai -- npx -y konid-ai It runs as an MCP server, so it works in Cursor, VS Code Copilot, Windsurf, Zed, JetBrains, and Claude Cowork. Also installs as a ChatGPT app via Developer mode using the endpoint https://konid.fly.dev/mcp . Supports 13+ languages: Mandarin, Japanese, Korean, Spanish, French, German, Portuguese, Italian, Russian, Arabic, Hindi, and more. The name is Farsi — konid (کنید) means "do." MIT licensed. https://github.com/robertnowell/konid-language-learning
AI 资讯
Async APIs: The 202 Accepted + Polling Pattern for Long-Running Operations
Some API requests can't finish in time for a single HTTP response. Generating a report, transcoding a video, running a batch import — these take seconds or minutes, far longer than any client should hold a connection open for. If you try to do this work inside a normal request, you'll hit gateway timeouts, frustrated clients retrying half-finished jobs, and load balancers killing connections at 30 or 60 seconds. The fix is a well-established HTTP pattern: accept the work, hand back a receipt, and let the client poll for the result. Here's how to build it properly. The shape of the pattern The client POST s the job. The server validates it, enqueues it, and immediately returns 202 Accepted with a URL where the status lives. The client polls that status URL until the job is done (or failed ). When complete, the status response points to the finished resource. The key detail most implementations get wrong: 202 does not mean "success." It means "I accepted this and will work on it." The actual outcome arrives later. Step 1: Accept the job import express from " express " ; import { randomUUID } from " crypto " ; const app = express (); app . use ( express . json ()); const jobs = new Map (); // use Redis or a DB in production app . post ( " /v1/reports " , ( req , res ) => { const id = randomUUID (); jobs . set ( id , { status : " pending " , createdAt : Date . now (), result : null }); // Kick off work without blocking the response processReport ( id , req . body ). catch (( err ) => { jobs . set ( id , { status : " failed " , error : err . message }); }); res . status ( 202 ) . location ( `/v1/reports/ ${ id } ` ) . json ({ id , status : " pending " }); }); Notice the Location header. It tells the client exactly where to look — no need to construct the URL itself. Step 2: Expose a status endpoint app . get ( " /v1/reports/:id " , ( req , res ) => { const job = jobs . get ( req . params . id ); if ( ! job ) return res . status ( 404 ). json ({ error : " unknown job " })
开发者
I Spent 30 Days Building a Complete Node.js Learning Path (Free for Everyone)
What This Repository Is A complete, structured, beginner-friendly Node.js learning path. 30 sessions. Each session has Clear learning objectives Step-by-step explanations Working code examples Practice exercises Interview questions Summary of key points No fluff. No assumptions. Just code. The Complete Curriculum Phase 1 - Node.js Fundamentals (Sessions 1-5) Session Topic What You Will Build 01 Introduction to Node.js Your first Node.js program 02 Project Setup and npm package.json, node_modules 03 How Node.js Works Event loop, blocking vs non-blocking 04 Modules and Imports Your first custom module 05 File System Module Read, write, update, delete files Sample code from Session 05 const fs = require ( " fs " ); // Create a file fs . writeFileSync ( " student.txt " , " Welcome To Node.js " ); // Read the file const data = fs . readFileSync ( " student.txt " , " utf8 " ); console . log ( data ); // Welcome To Node.js // Append to file fs . appendFileSync ( " student.txt " , " \n New line added " ); // Delete file fs . unlinkSync ( " student.txt " ); Phase 2 - Core Modules (Sessions 6-10) Session Topic What You Will Build 06 Path Module Cross-platform file paths 07 OS Module System information 08 Events and EventEmitter Custom event handling 09 HTTP Module Create a server 10 Multi-Route Server Multiple routes, JSON responses Sample code from Session 10 const http = require ( " http " ); const server = http . createServer (( req , res ) => { if ( req . url === " / " ) { res . end ( " Home Page " ); } else if ( req . url === " /about " ) { res . end ( " About Page " ); } else if ( req . url === " /products " ) { res . setHeader ( " Content-Type " , " application/json " ); res . end ( JSON . stringify ([{ id : 1 , name : " Laptop " }])); } else { res . statusCode = 404 ; res . end ( " Page Not Found " ); } }); server . listen ( 3000 ); Phase 3 - Building REST APIs (Sessions 11-15) Session Topic What You Will Build 11 CRUD with Dummy Data Complete REST API using array 12
AI 资讯
Reading a Paginated API Without Holding the Whole Thing in Memory
Your API hands out 50 records at a time across 400 pages. You need all of them. You do not need them all at once. Here's a very familiar situation that shows up constantly on the backend. Some API returns data in pages, 50 or 100 records at a time, and you need to walk every page: sync them to your database, export them to a file, run a report. The endpoint gives you a cursor or a page number and you keep asking until there's nothing left. The way most of us write it the first time looks like this: async function getAllRecords () { const all = []; let cursor = 0 ; while ( cursor !== null ) { const { records , nextCursor } = await fetchPage ( cursor ); all . push (... records ); cursor = nextCursor ; } return all ; } const everything = await getAllRecords (); for ( const record of everything ) { process ( record ); } It works. At four hundred records it's fine. The trouble starts when the dataset grows, and it has three separate problems hiding in it. It holds the entire dataset in memory before you touch a single record. It's all or nothing: if page 380 fails, you've thrown away the 19,000 records you already fetched . And it's eager. You can't start processing record one until the very last page has landed , even if all you wanted was the first ten. There's a shape in JavaScript built for exactly this, and if you read the first two posts in this series you already have both halves of it. Two ideas you've already seen In the CSV post , we pulled rows out of a huge file one at a time with a generator, so the file never fully loaded into memory. Lazy. Pull-based. You ask for the next row, you get the next row, nothing more. In the async/await post , we saw that a generator can pause at a yield and resume later.A generator can hold its place across an asynchronous gap. Put those together. A generator that pulls data lazily, and can pause to await something between pulls. That's an async generator, and it's the natural tool for walking a paginated API. You pull records
开发者
Fable 5 Pwned: Inside the First Mythos-Class Leak
The post hit X at some point on June 10, the morning after Anthropic's biggest launch in years. I...
AI 资讯
Validate and Mask Environment Variables in Node.js and TypeScript
Configuring environment variables seems simple, but it frequently leads to two common issues in production-grade applications: Missing Variables: A developer adds a new variable locally but forgets to update the .env.example file. Other team members pull the changes, and their local environments crash. Leaked Credentials: A debug log like console.log(process.env) prints database connection strings or API tokens to the terminal, leaving them visible in plaintext logs. To solve this, we created @novaedgedigitallabs/envkit . It is a zero-dependency (other than Zod) utility that validates, loads, and masks environment variables, and keeps your example configurations updated automatically. Key Features Schema Validation: Define your environment variables with Zod to enforce types and formats. Log Masking: Automatically redact sensitive credentials in console output. Example Syncing: Automatically append missing variables to your .env.example file without overwriting comments or values. Module Support: Runs in ESM and CommonJS. Getting Started Install the package and Zod: npm install @novaedgedigitallabs/envkit zod Initialize your configuration in a file like env.ts : import { createEnv } from ' @novaedgedigitallabs/envkit ' ; import { z } from ' zod ' ; export const env = createEnv ({ schema : { DATABASE_URL : z . string (). url (), JWT_SECRET : z . string (). min ( 32 ), PORT : z . coerce . number (). default ( 3000 ), NODE_ENV : z . enum ([ ' development ' , ' production ' , ' test ' ]). default ( ' development ' ), }, secrets : [ ' JWT_SECRET ' , ' DATABASE_URL ' ], generateExample : true , // Appends new keys to .env.example at runtime }); Because the variables are validated using Zod, your editor will provide full TypeScript autocomplete and type safety: env . PORT ; // Resolved as a number env . JWT_SECRET ; // Resolved as a string Preventing Secret Leaks in Logs Logging environment configs is a common debugging habit. With envkit, any variables listed in the secre
AI 资讯
3 Gotchas I Hit Deploying the Claude Agent SDK to Railway
I deployed a Slack bot app built on the Claude Agent SDK to Railway, and immediately hit a string of landmines around the SDK itself. Every one of them was the "the logs don't tell you what's wrong" kind, and the second one in particular ate a lot of my time. Since other people are likely to get stuck in the same spots, I'm writing it down. This is aimed at junior-to-mid-level devs using @anthropic-ai/claude-agent-sdk ( query() ) in Node.js. TL;DR Gotcha 1 : In a root container, bypassPermissions isn't allowed, and the child process dies with code 1 . Worse, stderr is swallowed, so you can't see why. Gotcha 2 : stdio MCP servers don't wait for connection by default, so on turn 1 the tool list is empty — and the model "acts out" tool calls and fabricates the results. Gotcha 3 : haiku shows up in your API logs, but that's not the model degrading — it's by design. It's used for internal chores. Gotcha 1: bypassPermissions doesn't work in a root container What happened Code that ran fine locally started dying with code 1 the moment I deployed it to Railway — the agent did nothing and just exited. The entire error message was essentially this: Error: Claude Code process exited with code 1 That tells you nothing. The only stack trace was from my app; what the child process (the claude binary) actually said before dying was a complete black box. The cause query() spawns a claude binary internally. That binary refuses --dangerously-skip-permissions (which the SDK calls permissionMode: "bypassPermissions" ) when running as root or under sudo . It's a safety measure — skipping all permission checks as root is far too dangerous. Railway, like many container environments, runs as root by default, so if you've set bypassPermissions you will always hit this. You can't catch it locally if you're running as a normal user. Why there are no logs This is the nasty part. Unless you pass an options.stderr callback, the SDK discards the child process's stderr with "ignore" . In other wor
AI 资讯
Nestjs — Stop burning AI credits to write Swagger docs, let the CLI do it!
Last Sunday I shared nestjs-docfy, a small library to move Swagger decorators out of NestJS controllers into companion *.controller.docs.ts files. The reception was better than I expected, and a lot of the feedback pointed in the same direction: the separation is nice, but writing those docs files by hand is still tedious. So I spent some time on that, and there's quite a bit new in this release. A CLI that writes the boilerplate for you The biggest addition is a generate command that reads your project with static analysis (no code execution, no ts-node overhead) and produces a pre-filled docs file for every controller: npx nestjs-docfy generate The generated file comes with inferred summaries, response types, and common error responses already in place. You edit from there instead of starting from scratch. It's idempotent by default, running it again won't touch files that already exist. When you add a new endpoint and want to merge only the new method block without losing your existing edits: npx nestjs-docfy generate --force The CLI auto-detects your project layout, so monorepos (Nx, Nest CLI, generic packages/ or apps/ structures) work without any configuration. There's also a --dry-run flag if you want to preview output before writing anything to disk. A check command for CI The other side of the workflow is keeping docs in sync as the codebase evolves. The check command exits with code 1 if any controller has undocumented methods or no companion file at all: npx nestjs-docfy check Output looks like this when something is out of sync: ✖ UsersController, undocumented methods: updateProfile, deleteAccount → run nestjs-docfy generate --force to merge new methods ✖ 2 controller(s) out of sync. Drop it into your pipeline and docs drift gets caught before it reaches main. Type-safe method keys The docs() function now enforces that every key in config.methods actually exists on the controller class. Typos are a compile error, not a silent runtime warning: docs ( User
AI 资讯
Diagnose Node.js CommonJS vs ESM Errors with Claude: A Copy-Paste Prompt Kit (ERR_REQUIRE_ESM, ERR_MODULE_NOT_FOUND)
By the end of this article you'll have a small Node.js script that pipes a module-resolution error ( ERR_REQUIRE_ESM , ERR_MODULE_NOT_FOUND , Cannot use import statement outside a module ) plus the surrounding config into Claude and gets back a specific fix — not a Stack Overflow lecture. You'll also have four hardened prompts you can paste straight into claude.ai, and a script that auto-detects whether your project is CJS or ESM before you even ask. Everything below runs on Node 18+. Why "just use ESM" doesn't fix the CommonJS/ESM ERR_REQUIRE_ESM error The reason these errors waste so much time is that the failing line is almost never where the problem lives. You see this: Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/node-fetch/src/index.js from /app/server.js not supported. and your instinct is to edit server.js . But the actual decision is made by four things you can't see from the traceback: the "type" field in your package.json , the "type" (or "exports" map) in the dependency's package.json , your file extension ( .js vs .mjs vs .cjs ), and — if you use TypeScript — the module and moduleResolution fields in tsconfig.json . node-fetch v3 went ESM-only; that's why require('node-fetch') blows up while v2 was fine. The traceback tells you none of that. This is exactly the shape of problem an LLM is good at: lots of small context scattered across files, one correct answer, and a human who keeps pattern-matching on the wrong line. The trick is to feed Claude the config alongside the error, not the error alone. A prompt that only gets the stack trace will confidently tell you to "convert your project to ESM," which is often the most destructive possible fix. Prompt 1 for Claude: force a root-cause classification before any code The failure mode of asking an AI to "fix my module error" is that it jumps to a rewrite. The fix is to make it classify first. Paste this into claude.ai, filling the three blocks: You are debugging a Node.js module resolut
AI 资讯
Architecting a Production-Ready Express + TypeScript Backend: Type Augmentation, Global Errors, and Middleware Factories
When building a personal finance tracker, data integrity and system reliability are non-negotiable. One missing try/catch block can crash your whole server, and weak types can let invalid financial payloads corrupt your database. While building the backend for my personal finance tracker, I decided to move past generic tutorials and build a bulletproof, production-grade API core using Express, TypeScript, and Zod. In this post, I’ll show you how I implemented a type-safe middleware ecosystem, leveraged TypeScript declaration merging to extend the native Request object, and eliminated repetitive try/catch boilerplate across the entire codebase. 1. The Weapon Against Boilerplate: The asyncHandler HOC Writing try/catch blocks in every single controller handler clutters code and introduces human error—it’s easy to forget to pass an error to next() . To solve this, I engineered a Higher-Order Function (HOC) factory that wraps asynchronous request handlers and automatically catches rejected promises, safely routing them into the global error handler. import { Request , Response , NextFunction , RequestHandler } from ' express ' ; export const asyncHandler = ( fn : RequestHandler ): RequestHandler => { return ( req : Request , res : Response , next : NextFunction ) => { Promise . resolve ( fn ( req , res , next )). catch ( next ); }; }; Why this matters: Reliability: Async errors always reach the centralized error middleware. Readability: Route controllers stay beautifully clean, focusing only on business logic rather than async control flow wiring. 2. TypeScript Magic: Declaration Merging & Type Augmentation When dealing with authentication tokens, request tracing ( requestId ), or custom validated payloads, developers frequently resort to casting the request as any (e.g., (req as any).userId ). This completely destroys Type Safety. Instead of fighting the compiler, I leveraged TypeScript Declaration Merging to reopen Express's internal Request interface and merge my cust