Rule Engine with Node.js

 

πŸš€ Building a Rule Engine with Node.js

By Sayyed Mohammad Adil


In today’s modern applications, handling complex conditions and business logic directly in the codebase can make systems rigid and hard to maintain. This is where a rule engine comes in handy — allowing us to separate rules from logic and make systems more flexible, scalable, and adaptable.

In this article, I’ll walk you through building a simple rule engine using Node.js, with support for conditional logic, custom actions, and contextual evaluation — all defined in JSON.


🧠 What Is a Rule Engine?

A rule engine is a system that evaluates a set of conditions (rules) against input data and determines which actions to execute. It’s widely used in:

  • πŸ›’ E-commerce (discount rules, cart promotions)

  • 🏦 Banking (loan eligibility, fraud detection)

  • πŸ›‚ Access control systems

  • ⚙️ Workflow automation and approvals

By using a rule engine, you can let non-developers modify system behavior without touching application logic.


πŸ—️ Architecture Overview

Here's how a simple rule engine works:

  1. Rule Definition – Rules written in JSON format.

  2. Rule Parser – Interprets and validates each rule.

  3. Executor – Evaluates conditions using actual input.

  4. Result Handler – Returns decisions or triggers actions.

Let’s build it step by step πŸ‘‡


πŸ› ️ Step 1: Setup Your Node.js Project

bash
mkdir node-rule-engine cd node-rule-engine npm init -y npm install lodash

πŸ“œ Step 2: Define Rules in JSON

json
// rules.json [ { "name": "High Order Discount", "condition": { "field": "orderAmount", "operator": ">", "value": 1000 }, "action": { "type": "DISCOUNT", "value": 10 } }, { "name": "First Time Buyer", "condition": { "field": "user.isNew", "operator": "==", "value": true }, "action": { "type": "DISCOUNT", "value": 5 } } ]

Each rule checks a condition and defines an action if true.


🧠 Step 3: Create the Rule Engine Logic

js
// ruleEngine.js const _ = require('lodash'); const OPERATORS = { '==': (a, b) => a == b, '===': (a, b) => a === b, '!=': (a, b) => a != b, '>': (a, b) => a > b, '<': (a, b) => a < b, '>=': (a, b) => a >= b, '<=': (a, b) => a <= b }; function evaluateCondition(condition, context) { const { field, operator, value } = condition; const data = _.get(context, field); const operation = OPERATORS[operator]; return operation ? operation(data, value) : false; } function runRules(rules, context) { const actions = []; for (const rule of rules) { if (evaluateCondition(rule.condition, context)) { actions.push(rule.action); } } return actions; } module.exports = { runRules };

Here, we use lodash.get to safely access nested fields like user.isNew.


πŸ§ͺ Step 4: Use the Engine in Your App

js
// app.js const fs = require('fs'); const { runRules } = require('./ruleEngine'); const rules = JSON.parse(fs.readFileSync('./rules.json', 'utf8')); const userContext = { orderAmount: 1200, user: { isNew: true } }; const results = runRules(rules, userContext); console.log('Triggered Actions:', results);

✅ Output:

bash
Triggered Actions: [ { type: 'DISCOUNT', value: 10 }, { type: 'DISCOUNT', value: 5 } ]

These can be used to apply dynamic pricing, inform your UI, or log decisions.


🧩 How to Extend This Rule Engine?

To make it more powerful, you can add:

  • Logical grouping: AND, OR, NOT combinations.

  • Rule prioritization (weight/priority field).

  • Database-backed rules (MongoDB/PostgreSQL).

  • Time-based rules (validity periods).

  • UI for business users to manage rules.


🌍 Real-World Applications

IndustryUse Case
E-CommerceDynamic discount engine
BankingLoan eligibility check
HRCandidate filtering
LogisticsRoute optimization
IoT/DevicesRule-based automation triggers

🧠 Final Thoughts

Rule engines provide a clean and scalable way to handle business logic that changes frequently or varies per customer/context. By decoupling rules from code, your application becomes easier to update and maintain.

Using Node.js, we built a lightweight but extendable engine — ready for production or further enhancements.


πŸ™Œ Let’s Connect

If you enjoyed this or want help implementing rule engines in your own projects, let’s connect:

πŸ”— LinkedIn
πŸ’» GitHub



Comments