惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
P
Privacy International News Feed
T
Tenable Blog
L
Lohrmann on Cybersecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
S
Securelist
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Vercel News
Vercel News
Cyberwarzone
Cyberwarzone
月光博客
月光博客
T
The Blog of Author Tim Ferriss
Scott Helme
Scott Helme
爱范儿
爱范儿
Stack Overflow Blog
Stack Overflow Blog
C
Cisco Blogs
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
阮一峰的网络日志
阮一峰的网络日志
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Security Latest
Security Latest
Blog — PlanetScale
Blog — PlanetScale
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
博客园 - 三生石上(FineUI控件)
I
InfoQ
Spread Privacy
Spread Privacy
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
C
CERT Recently Published Vulnerability Notes
A
About on SuperTechFans
博客园_首页
Engineering at Meta
Engineering at Meta
Project Zero
Project Zero
Latest news
Latest news

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Feature Flags in Node.js: Express and Fastify Guide
Domenico Gio · 2026-04-23 · via DEV Community

This was originally published on rollgate.io/blog/feature-flags-nodejs.

Why Feature Flags in Node.js?

Node.js powers a huge slice of production backends — REST APIs, GraphQL gateways, background workers, BFF layers, real-time services. All of them share the same release problem: you want to ship code continuously, but you do not want every deploy to be a product change.

Feature flags in Node.js decouple deployment from release. You push code to production behind a flag and decide later who sees the new behavior, when, and under what conditions. If something breaks, you flip the flag off in the dashboard — no redeploy, no rollback PR, no pager at 3am.

This guide covers the practical side: how to wire feature flags into Express and Fastify applications, how to target specific users, how to roll out gradually, and the production gotchas that every team hits sooner or later.

Quick Start: Feature Flags in Node.js

Let us get a flag running end-to-end. Install the SDK:

npm install @rollgate/sdk-node

Enter fullscreen mode Exit fullscreen mode

Then wire it up:

import { RollgateClient } from '@rollgate/sdk-node';

const rollgate = new RollgateClient({
  apiKey: process.env.ROLLGATE_API_KEY!,
  enableStreaming: true, // real-time updates over SSE
});

await rollgate.init();

if (rollgate.isEnabled('new-checkout', false)) {
  console.log('New checkout flow enabled');
} else {
  console.log('Legacy checkout');
}

Enter fullscreen mode Exit fullscreen mode

That is the whole setup. The SDK pulls rules from the API, caches them in memory, and keeps them fresh in the background. With enableStreaming: true the client keeps a Server-Sent Events connection open and applies changes within ~50ms of a flag flip. The second argument to isEnabled is the default value returned if the client is not yet initialized or the flag does not exist.

Evaluation is local, in-process. No network hop per flag check — the rules are already in memory, so you can evaluate thousands of flags per request without adding latency to the hot path.

The DIY Approach (and Its Limitations)

Before reaching for a dedicated platform, most teams start with environment variables:

const flags = {
  newCheckout: process.env.NEW_CHECKOUT === 'true',
  darkMode: process.env.DARK_MODE === 'true',
};

if (flags.newCheckout) {
  // ...
}

Enter fullscreen mode Exit fullscreen mode

This works, for exactly one week. Then you hit the limitations:

  • Every flag change requires a redeploy — the whole point of flags is to avoid that
  • No gradual rollouts — it is all-or-nothing for every user
  • No targeting — you cannot enable a feature for beta testers, enterprise plans, or a specific region
  • No kill switch — if the new code breaks, rolling back means another deploy cycle
  • No audit trail — you do not know who flipped what, when, or why

The next evolution is usually a config file or a database table. You solve the redeploy problem but inherit a new one: keeping the config in sync across every instance of your Node.js service, and refreshing it without restarts. That is where a purpose-built feature flag platform earns its keep.

Using Rollgate with Express

Express is still the workhorse of the Node.js backend ecosystem. Here is a clean pattern: attach the Rollgate client to the request via middleware, then evaluate flags inside route handlers with the user context from the request.

import express from 'express';
import { RollgateClient } from '@rollgate/sdk-node';

const app = express();
const rollgate = new RollgateClient({
  apiKey: process.env.ROLLGATE_API_KEY!,
  enableStreaming: true,
});

await rollgate.init();

app.use((req, res, next) => {
  const userId = req.headers['x-user-id'] as string | undefined;
  req.flags = {
    isEnabled: (key: string, fallback = false) =>
      rollgate.isEnabled(key, fallback, userId ? { userId } : undefined),
  };
  next();
});

app.get('/checkout', (req, res) => {
  if (req.flags.isEnabled('new-checkout')) {
    return res.json({ version: 'v2', flow: 'stripe-elements' });
  }
  return res.json({ version: 'v1', flow: 'legacy-form' });
});

app.listen(3000);

Enter fullscreen mode Exit fullscreen mode

The EvalContext you pass as the third argument lets you evaluate a flag for a specific user without mutating client-level state. Each request gets its own targeting evaluation based on userId and any attributes you forward (plan, region, role, anything your targeting rules reference).

Remember to shut the client down cleanly on SIGTERM so the SSE connection and telemetry buffers drain properly:

process.on('SIGTERM', async () => {
  await rollgate.close();
  process.exit(0);
});

Enter fullscreen mode Exit fullscreen mode

Using Rollgate with Fastify

Fastify is the faster, more opinionated alternative. The pattern is the same — a plugin that decorates the request — but with Fastify's decorator API:

import Fastify from 'fastify';
import { RollgateClient } from '@rollgate/sdk-node';

const fastify = Fastify({ logger: true });
const rollgate = new RollgateClient({
  apiKey: process.env.ROLLGATE_API_KEY!,
  enableStreaming: true,
});

await rollgate.init();

fastify.decorateRequest('flags', null);

fastify.addHook('onRequest', async (request) => {
  const userId = request.headers['x-user-id'] as string | undefined;
  request.flags = {
    isEnabled: (key: string, fallback = false) =>
      rollgate.isEnabled(key, fallback, userId ? { userId } : undefined),
  };
});

fastify.get('/api/experiments', async (request) => {
  return {
    pricing: request.flags.isEnabled('new-pricing-ui'),
    search: request.flags.isEnabled('semantic-search'),
  };
});

fastify.addHook('onClose', async () => {
  await rollgate.close();
});

await fastify.listen({ port: 3000 });

Enter fullscreen mode Exit fullscreen mode

One thing to watch: if you are running Fastify with logger: true and want the flag value in every log line, add it to the request context with request.log.child({ flags: [...] }) inside the onRequest hook. Observability on which flags evaluated for which request is the kind of detail that saves you hours in an incident.

Gradual Rollouts and User Targeting

Once flags are wired, the real value kicks in: turning a feature on for 1% of traffic, watching error rates for an hour, then bumping it to 10% the next day. Rollgate handles this with sticky, deterministic bucketing — the same user always lands in the same bucket, so a user who sees the new feature at 5% keeps seeing it when you move to 50%.

You do not need to change your Node.js code when you change the rollout percentage. The rules live in the dashboard; your SDK pulls the new rules and evaluates them locally.

const showNewFlow = rollgate.isEnabled('checkout-v2', false, {
  userId: user.id,
  attributes: {
    plan: user.plan,
    region: user.region,
    signupDate: user.signupDate,
  },
});

Enter fullscreen mode Exit fullscreen mode

The attributes you pass feed into targeting rules. A common pattern for B2B SaaS: enable a feature for all plan = "enterprise" users plus 10% of plan = "pro" users, with no rollout for free-tier. That is three rules in the dashboard, zero code changes.

If you are using flags for experimentation rather than safe releases, pair them with event tracking. The Node SDK exposes client.track() for conversion events, which plugs into A/B testing workflows.

Production Considerations

A flag system sits in the hot path of every request. That changes how you think about it.

Caching and evaluation mode. The SDK evaluates locally by default — rules are cached in memory and refreshed via SSE or polling. There is no network call on each isEnabled(). In a Node.js process with a hot path that evaluates flags thousands of times per second, this matters: network-dependent flag checks would wreck your P99.

Resilience. The SDK ships with a circuit breaker, retry-with-backoff, and a stale cache fallback. If the Rollgate API becomes unreachable, your service keeps serving flag evaluations using the last known rules — it does not hard-fail. You can subscribe to circuit-open and flags-stale events to surface this in your own monitoring:

rollgate.on('circuit-open', () => {
  metrics.increment('rollgate.circuit.open');
});
rollgate.on('flags-stale', () => {
  metrics.increment('rollgate.flags.stale');
});

Enter fullscreen mode Exit fullscreen mode

Kill switches in production. Wrap risky code paths — a new payment provider, a rewritten algorithm, an external API integration — in a flag you can flip instantly. When something breaks, you want the shortest possible path from "we are paging" to "traffic is back on the old code." A flag flip takes under a second; a rollback deploy takes tens of minutes.

Process lifecycle. Always call rollgate.close() on shutdown. It closes the SSE connection, flushes pending telemetry, and lets Kubernetes or your PaaS roll pods cleanly. Skipping this leaks file descriptors and loses the last batch of evaluation analytics.

One client per process, not per request. The SDK is thread-safe and reusable. Do not instantiate a new RollgateClient per request — you will hit the API hard, leak connections, and lose the benefit of local caching. One long-lived client at app start, shut down on SIGTERM.

Best Practices

  • Name flags by feature, not by team. new-checkout ages better than backend-team-q2-project. Future you will thank present you.
  • Always pass a sensible default. rollgate.isEnabled('feature', false) — false is usually the safe default (do not ship the new thing if we cannot decide). Explicit is better than surprising.
  • Retire flags. Once a rollout hits 100% and has been stable for a week, remove the flag from code. Zombie flags are a maintenance tax.
  • Log the evaluated value for high-stakes flags. If isEnabled('new-payment-provider') returned true for a user whose transaction failed, you want that in the log line, not inferred from the timestamp.
  • Separate experimentation flags from release flags. A kill switch for production should not expire when an experiment wraps up. Use different naming prefixes so they are easy to tell apart.

Next Steps

Feature flags in Node.js are a small change with an outsized impact. You stop shipping features and start shipping code, which means faster deploys, safer releases, and a rollback story that takes seconds instead of a pager rotation.

The Rollgate Node.js SDK is open source, 2KB gzipped, and works identically in Express, Fastify, Koa, NestJS, and any other Node.js framework. Local evaluation, SSE streaming, circuit breaker, and kill switches come in the box.

Read the full version with internal links to related guides on rollgate.io/blog/feature-flags-nodejs.