Edge Logic Engine

Custom Logic
at the Edge

Run scripts inside a secure sandbox to transform HTML and control behavior in real time — between the server and the user.

Core Concept

When Rules Are Not Enough

Rules handle 80% of what you need — declaratively, without code. Scripts handle the rest: complex transformations, dynamic calculations, multi-step logic that rules can't express in a single action.

If rules define what happens — scripts define exactly how.

RULE
↓ triggers
Entry Point
A rule matches the request — URL, headers, geo, device — and decides that a script should run. Scripts are always invoked through rules.
SCRIPT
↓ executes in
Sandbox
Your custom logic runs inside a secure, isolated sandbox at the edge. It reads context, processes data, and decides what transformations to apply.
TRANSFORM
↓ modifies
HTML Output
The script modifies the HTML response — titles, metadata, content blocks, attributes, injected elements — with complete programmatic control.
OUTPUT
↓ delivered to
Browser
The browser receives a fully transformed page. No extra requests, no client-side JS, no backend involvement. Resolved entirely at the edge.
Sandbox

Safe Execution Environment

Every script runs inside a controlled, isolated sandbox. It can transform HTML and read request context — but it cannot access the underlying system, make arbitrary network calls, or affect anything outside the current response.

What the sandbox guarantees

🔒
Controlled Environment
Scripts run in strict isolation. Each execution is scoped to a single request — no shared state, no side effects between requests.
No System Access
Scripts cannot access the filesystem, environment variables, or underlying infrastructure. They operate only on the request and its HTML response.
Predictable Behavior
Execution is deterministic. Given the same input context, a script always produces the same output — no surprises in production.
Safe in Production
The sandbox is designed for live traffic. Scripts are pre-validated and execute within hard time limits — no hanging, no runaway processes.

What a script can access

Request Context
URL, path, query parameters, HTTP method, user agent — the full request picture via ctx.request.
Dataset Variables
All variables resolved from active datasets are available via ctx.variables — ready to use in script logic.
HTML Manipulation API
A safe, structured API for modifying the response: set titles, inject elements, rewrite attributes, remove nodes — via ctx.html.
Response Headers
Read and write HTTP response headers — set cache directives, custom headers, or content-type — via ctx.response.
Capabilities

What Scripts Can Do

Scripts give you full programmatic control over the HTML response — without a backend, without a deploy.

Modify HTML

Set titles, headings, meta tags, and any element's content or attributes programmatically.

  • Set <title> dynamically
  • Rewrite <meta> tags
  • Change element text
  • Modify href, src, data-*

Generate Content

Build HTML strings from data and inject them into any position in the page.

  • Inject before / after elements
  • Build markup from variables
  • Insert banners, notices
  • Generate structured data

Transform Data

Compute, format, and combine values from datasets before injecting them into output.

  • String formatting
  • Number calculations
  • Conditional values
  • Data combination

Control Output Logic

Branch behavior based on runtime context — URL, headers, variables — with full if/else control flow.

  • Conditional transformations
  • Multi-step logic
  • Context-aware output
  • Fallback handling
Context

Access Runtime Context

Every script receives a ctx object — the full runtime context for the current request. It's how your script reads data, reads the request, and writes back to the response.

ctx.request
Request Data

Everything about the incoming HTTP request — URL, path, query params, method, user agent.

ctx.request.url
ctx.request.path
ctx.request.query.get("q")
ctx.request.headers.get("x-city")
ctx.variables
Dataset Variables

All variables resolved from the active dataset for this request, ready to use in script logic.

ctx.variables.get("city")
ctx.variables.get("price")
ctx.variables.get("title")
ctx.variables.get("cta")
ctx.html
HTML Manipulation

A structured API to read and modify the HTML response — titles, meta, elements, attributes.

ctx.html.setTitle(val)
ctx.html.setMeta("desc", val)
ctx.html.setText("#hero h1", val)
ctx.html.inject("head", html)
ctx.response
Response Control

Set or modify HTTP response headers, cache directives, and status codes for the current request.

ctx.response.setHeader(
 "Cache-Control", "max-age=3600"
)
ctx.response.status
ctx.geo
Geo Location

The detected country, region, and city of the requesting user — inferred at the edge from the IP.

ctx.geo.country
ctx.geo.city
ctx.geo.region
ctx.geo.timezone
ctx.device
Device Info

Device type and browser category — use it to deliver different output for mobile vs desktop.

ctx.device.type
ctx.device.isMobile
ctx.device.browser
ctx.device.os
Example

Example Script

A script that generates a dynamic SEO title and meta description from dataset variables and geo context — then injects them into the HTML response before delivery.

seo_titles.js — dynamic SEO generation
// Read variables from the active dataset
var city = ctx.variables.get("city");
var price = ctx.variables.get("price");
var currency = ctx.variables.get("currency");

// Fallback if no dataset match for this city
if (!city) {
  city = ctx.geo.city; // fall back to geo-detected city
}

// Build SEO strings
var title = "Best Clinics in " + city + " — from " + currency + " " + price;
var desc = "Find top-rated clinics in " + city + ". Book from " + currency + " " + price + " per session.";

// Apply to the HTML response
ctx.html.setTitle(title);
ctx.html.setMeta("description", desc);
ctx.html.setText("#hero h1", city + " Clinics");
ctx.html.setText(".price-tag", "From " + currency + " " + price);

// Inject JSON-LD structured data into <head>
ctx.html.inject("head", '<script type="application/ld+json">{"@type":"LocalBusiness","name":"' + city + ' Clinics"}</script>');
Script input — ctx
city = "London"
price = 120
currency = "GBP"
geo.city = "London"
Resolved HTML output
<title>Best Clinics in London — from GBP 120</title>
<meta name="description" content="Find top-rated clinics in London...">
<h1>London Clinics</h1>
<span class="price-tag">From GBP 120</span>
Integration

Scripts Inside Rules

Scripts are not standalone. They're always invoked from within a rule — using the run_script action in the DO block. This means scripts inherit the rule's conditions, matching context, and security scope.

Rule — Dynamic SEO
Active
WHEN
HTML Response — every HTML page served
WHERE
URL matches /city/* AND dataset key exists
DO
run_script seo_titles.js — execute in sandbox
WHY
City pages need computed SEO titles that combine dataset values with geo fallback logic — too complex for a simple rule action.
Rule matches /city/london
seo_titles.js runs in sandbox
HTML modified with computed values
Browser receives rendered page
Use Cases

Real Use Cases

Use Case 01
Dynamic SEO Generation

Compute unique title and meta description per city, product, or segment — combining dataset values with geo context and formatting logic.

var title = "Clinics in " + ctx.variables.get("city");
ctx.html.setTitle(title);
Use Case 02
Complex Personalization

Apply multi-condition logic — device + geo + returning user — to select and inject the right content block for each unique combination.

if (ctx.device.isMobile && ctx.geo.country === "GB") {
  ctx.html.inject("#hero", mobileUK);
}
Use Case 03
Content Transformation

Reformat prices, dates, or text for the target locale — apply number formatting, currency symbols, and language conventions to dataset values.

var p = ctx.variables.get("price");
ctx.html.setText(".price", "£"+p.toFixed(2));
Use Case 04
Conditional UI Logic

Show or hide UI elements — banners, CTAs, notices — based on runtime conditions computed in the script, not in JavaScript on the client.

if (promo === "active") {
  ctx.html.remove(".promo-hidden");
}
Use Case 05
Advanced Experiments

Implement multi-variant logic beyond simple A/B — weighted allocation, holdout groups, and contextual assignment — all computed at the edge.

var v = assignVariant(userId, weights);
ctx.html.setText(".cta", v.cta);
Use Case 06
Structured Data Injection

Generate and inject JSON-LD schema, Open Graph tags, and canonical URLs computed from dataset values — per page, per product, per city.

var ld = buildSchema(city, price);
ctx.html.inject("head", ld);
Comparison

Rules vs Scripts

Rules and scripts are complementary — not competing. Use rules for most things. Add scripts when you need the extra degree of control.

DimensionRulesScripts
Style Declarative — describe what to do Imperative — write how to do it
Complexity Simple, single-step logic Multi-step, conditional, computed logic
Coding required No-code — visual configuration Low-code — lightweight JS-like syntax
Setup time Fast — define and activate immediately Short development cycle — test in sandbox
Flexibility Covers most standard use cases Handles any logic that rules cannot express
Execution Resolved inline by the rule engine Run in isolated sandbox per request
Best for SEO, redirects, header injection, A/B splits Dynamic SEO, complex personalization, data transformation
Value

Unlimited Flexibility

Extend Rules

Add script actions to any existing rule — without changing how it matches or triggers.

Handle Edge Cases

Write the exact logic your use case needs — not a workaround that approximates it.

Build Custom Logic

From simple string formatting to multi-step conditional branching — scripts cover it all.

Adapt to Any Scenario

Products change, sites evolve. Scripts let you adapt delivery logic without touching the origin.

You write the logic. The edge executes it —
between the server and the user.
Edge Logic Engine
Start Writing Edge Logic

Extend your rules with custom scripts. Run logic safely at the edge — no backend changes, no deployment, no risk.

Explore More
Rules Engine
Programmable Rules
The foundation of Ninja — declarative control over web output with the WHEN, WHERE, DO, WHY model.
Explore →
Data Layer
Datasets & Variables
Power your scripts with structured data — variables resolved from datasets at request time, available in every script via ctx.variables.
Explore →
Architecture
How Ninja Works
Understand the infrastructure layer where scripts execute — between origin and browser, at the edge of the web.
Explore →