DEV Community

Pavel Kostromin
Pavel Kostromin

Posted on

Choosing Between EJS and Eta for Non-Next.js Node.js SSR: Familiarity vs. Performance and Features

Context and Architectural Scope: SSR Without Next.js

Skipping full-stack meta-frameworks like Next.js for a server-rendered Node.js application removes two heavy layers of machinery: a client-side hydration runtime and an opinionated routing or build bundler. When a request hits an HTTP server directly and renders HTML strings on the server, memory stays predictable and cold starts remain brief because V8 does not compile or serialize large client-side component trees before sending bytes over the socket.

That lean architecture shifts the bottleneck from bundle orchestration to three concrete engineering dimensions: developer velocity, runtime speed, and maintainability. Developer velocity depends on how fast an engineer writes, composes, and debugs templates without fighting missing primitives. Runtime speed depends on how templates compile into JavaScript functions, how compiled functions stay cached in memory, and how much string concatenation or helper overhead runs per request. Maintainability depends on how cleanly layouts, partials, and data contracts survive refactoring over months rather than days.

In a direct Node.js SSR setup, Eta is the stronger default choice over EJS for a new codebase because its compiled function output, native layout/partial support, and type ergonomics reduce friction without abandoning familiar tag syntax. EJS remains effective only when immediate team fluency or existing template conventions carry higher cost than manual layout wiring and looser typing.

Option Primary Mechanism Optimal Condition Failure Mode
Eta Compiles templates directly into lean JS functions with built-in layout/partial resolution New lean Node.js SSR app needing speed, layouts, and clean typing Team unfamiliarity slows early debugging or edge-case configuration
EJS Compiles tags into string-appending JS code with minimal built-in composition Rapid delivery with team already fluent in EJS and existing snippets Repetitive include/layout boilerplate causes drift and markup bugs

Choosing EJS by habit in a brand-new project creates a predictable choice error: engineers treat prior syntax familiarity as proof of long-term low cost, ignoring how missing native layout composition forces copy-pasted wrapper markup across views. Once a header wrapper or script tag changes in twelve files instead of one layout slot, stale tags and unclosed HTML elements slip into production responses. Conversely, choosing Eta without checking team readiness creates minor early friction when an engineer misreads a compile error or configuration option before building a mental model of how Eta compiles blocks.

Eta stops being the right choice when strict deadline pressure meets zero prior exposure on a small team, or when a project must share templates with an existing EJS codebase. Under those conditions, template syntax mistakes and lookup delays outweigh Eta's faster string rendering and cleaner layout primitives.

  • If starting a new lean Node.js SSR project and the team can absorb minor early learning -> use Eta for better rendering efficiency, built-in layouts, and maintainability.
  • If shipping immediately with a team already fluent in EJS or integrating existing EJS views -> use EJS to avoid onboarding drag and syntax translation errors.

Familiarity vs. Modernization: EJS, Handlebars Mental Models, and Eta

Switching to a direct Node.js server-side rendering stack without Next.js strips away client-side hydration bundles and framework routing layers, moving system bottlenecks into template compilation, layout composition, and maintainability. If you already know EJS and Handlebars, Eta is the stronger default choice for a new project because its tag grammar mirrors EJS while fixing parser edge cases, adding native layout composition, and shipping TypeScript definitions out of the box.

Coming from Handlebars requires a mental shift away from helper-driven indirection toward inline JavaScript expressions. Handlebars isolates template logic inside registered helpers and block expressions, which prevents arbitrary JavaScript inside views but forces you to register custom helpers for simple conditionals or array transforms. In Eta, control flow and expressions execute directly inside compiled JavaScript functions, so missing a helper registration no longer stalls rendering, though placing complex business logic inside templates can bloat generated function bodies and make view bugs harder to trace.

With prior EJS experience, the core syntax transfers immediately, but specific tag mechanics behave differently under the hood:

  • Raw output markers: EJS uses <%- expr %> for unescaped output, whereas Eta reserves the hyphen for whitespace control and uses <%~ expr %> for raw interpolation. Reusing EJS raw tags in Eta changes tag parsing behavior rather than bypassing HTML escaping, risking literal tag text or broken markup in the rendered response.
  • Whitespace trimming asymmetry: Eta supports leading and trailing whitespace trimming markers (- and _) on both sides of a tag, whereas EJS ties leading - on output tags to unescaped output. When template whitespace is not trimmed cleanly, extra newline and space tokens remain in string concatenation steps, inflating response payload size and slightly increasing V8 string allocation work on high-throughput routes.
  • String and delimiter parsing: Naive regex or index-based tag scanners break when a closing delimiter appears inside a string literal or comment (such as %> inside quotes). Eta's parser tracks string and comment boundaries more reliably than EJS's scanner, preventing premature tag termination and cryptic syntax errors during template compilation.
  • TypeScript ergonomics: Eta is written in TypeScript and exposes native type definitions, letting your editor and compiler check configuration options and template data contracts before runtime. Relying on loosely typed view locals in EJS leaves mismatched property names or undefined fields undetected until V8 executes the compiled template function and throws a runtime property-access error.

Between the two options, Eta is more effective for a new lean Node.js SSR codebase because it pairs familiar EJS-like tags with faster template execution, built-in layouts and partials, and native TypeScript support. EJS remains more effective only when an existing EJS view library must be reused directly or a tight deadline leaves zero margin for learning new tag conventions and configuration defaults.

Eta stops working well when a team adopts it without accounting for unfamiliar configuration defaults or when legacy EJS templates already encode project-specific conventions. A common choice error is assuming EJS familiarity has zero maintenance cost: copying header, footer, and script wrappers across templates instead of using native layout composition causes markup drift and unclosed tags during refactors. The opposite error is forcing Eta onto a rush project with zero team exposure, where unfamiliar error messages or whitespace settings slow early debugging.

Use this decision rule when starting your service: if you are building a new non-Next.js Node.js SSR project and can absorb brief initial ramp-up, choose Eta for cleaner layout composition, TypeScript support, and rendering efficiency; if you must ship immediately with an EJS-fluent team or reuse existing EJS templates, choose EJS to avoid syntax translation errors and onboarding drag. Signing in to a Google Account is also helpful if you want to save this thread and return to your architecture notes later.

Performance, Bundle Footprint, and Edge/Server Characteristics

In a lean Node.js SSR service that skips Next.js client hydration bundles, rendering speed is rarely bottlenecked by the difference between Eta and EJS on a single route. Instead, real performance differences emerge at scale from how each engine compiles tags into JavaScript functions, caches those compiled functions in memory, retains whitespace or layout wrappers in output buffers, and behaves across constrained server or edge runtimes.

Compilation Mechanics and Caching Behavior

Both Eta and EJS avoid interpreting template tags line by line on every request by translating template markup into executable JavaScript functions. Once a template is compiled, caching stores the resulting function reference in memory so subsequent requests execute the compiled function directly rather than re-scanning delimiters, re-emitting code strings, and re-evaluating dynamic code constructors.

Where their compilation pipelines diverge is in code generation precision and whitespace control. When a template leaves raw newlines, indentation, or redundant wrapper partials in the compiled output, the generated function executes extra string-concatenation operations and allocates larger HTML strings in V8 heap memory on every request. Eta trims leading and trailing whitespace cleanly around tags without overloading the raw-output marker, reducing unnecessary string literals inside the compiled function body and keeping per-request V8 allocation lighter under sustained traffic.

Empirical rendering benchmarks generally place Eta ahead of EJS and Handlebars in requests per second and tail latency, but two practical realities govern when that gap matters:

  • Caching dominates raw engine speed: Enabling template caching (or precompiling templates ahead of traffic) removes repeated parse-and-compile work in both engines. If caching is left off in production, disk reads and repeated function compilation swamp minor execution differences between Eta and EJS.
  • I/O and data assembly dwarf template execution: On typical SSR pages, database queries, external API calls, and network serialization consume orders of magnitude more time than string rendering inside a cached template function.
  • High-frequency micro-renders expose overhead: Rendering thousands of small fragments, emails, or reports per second makes Eta's leaner compiled code and tighter string output measurable—though hand-written JavaScript template literals still outperform general-purpose template engines when logic is trivial.

Package Size and Bundle Footprint

Eta ships with zero dependencies and a compact footprint (roughly 2 KB to 3.5 KB minzipped/gzipped), whereas EJS carries a larger distribution footprint (around 4.4 KB gzipped for core builds and roughly 8 KB gzipped for minified browser builds).

On a standard long-lived Node.js server, saving a few kilobytes of package weight has negligible impact on steady-state RSS memory. The physical effect shows up during cold starts, container or serverless bundle uploads, and dual-environment setups where the same template engine runs on the server and in client code. Fewer bytes to download, parse, and evaluate mean less V8 startup work before the first request is served, and Eta's native ES Module and UMD outputs integrate cleanly into modern bundlers without pulling in extra transitive packages.

Edge, Serverless, and Restricted Runtime Characteristics

Moving from a persistent Node.js process to serverless functions, edge isolates, or browser contexts changes the failure modes of string-based template engines:

  • Dynamic code generation limits: Compiling templates at runtime into executable JavaScript functions relies on dynamic code evaluation. In strict Content Security Policy (CSP) environments or locked-down edge sandboxes that block runtime code synthesis, on-the-fly compilation throws runtime errors unless templates are precompiled into static functions during the build step.
  • Filesystem assumptions: File-based view resolution expects access to a template directory on disk. In edge or bundled environments where source files are not laid out as loose runtime files, passing template strings or precompiled template maps avoids missing-file errors at request time.
  • Runtime version alignment: Modern Eta releases target current runtimes (such as Node 20 and above, alongside Deno and browsers), while EJS maintains broad backward compatibility across much older Node versions. Running a newer runtime baseline favors Eta's TypeScript-first codebase, whereas pinning to an aging legacy Node runtime can make EJS's older compatibility envelope safer.

Decision Rule and Typical Selection Errors

Optimal choice: For a new non-Next.js Node.js SSR project on a modern runtime, choose Eta. It pairs familiar EJS-style tags with zero dependencies, a smaller bundle footprint, stronger benchmark throughput, cleaner whitespace control, and built-in layouts and TypeScript support.

When Eta stops working well: Eta loses its advantage when a team is under an immediate deadline with zero prior Eta exposure and templates contain complex embedded JavaScript that slows early debugging, or when the target deployment environment prohibits runtime dynamic code evaluation and you have not set up precompilation.

Typical choice errors and their mechanisms:

  • If a team sticks with EJS purely out of habit on a greenfield SSR app, they often hand-copy headers, footers, and script tags across views instead of using native layout composition. Duplicated markup drifts over time and leaves unclosed tags or stale assets during refactors.
  • If a team adopts Eta without enabling template caching or checking runtime CSP/compilation rules, repeated compilation or blocked dynamic code execution degrades throughput or breaks rendering in production.

Decision rule: If you are starting a new non-Next.js Node.js SSR service on a modern runtime and can absorb brief syntax ramp-up -> use Eta; if you must reuse existing EJS templates or ship immediately with an EJS-fluent team where onboarding drag outweighs long-term layout maintenance -> use EJS.

Five Real-World Node.js SSR Scenarios

Dropping Next.js removes client hydration bundles and framework routing layers, shifting bottlenecks onto template compilation, layout composition, and view maintainability. When compiling templates into executable JavaScript functions and caching those functions in memory, both EJS and Eta eliminate per-request lexing and dynamic code synthesis on warm routes. Where they diverge is in how they emit string-building instructions, track string and comment boundaries inside tags, handle layouts natively, and expose TypeScript definitions. For a new Node.js SSR service without Next.js, Eta is the stronger default choice whenever your team can absorb a short syntax ramp-up, while EJS is optimal only when immediate delivery with an EJS-fluent team or direct reuse of existing EJS templates outweighs structural maintenance costs.

1. High-Throughput Public SSR Pages

Winner: Eta (provided template caching is enabled and database/API I/O is not the sole bottleneck).

On high-traffic public pages, rendering cost shows up in CPU cycles spent concatenating strings, heap allocations inside V8, and wire bytes sent over the network. Eta compiles templates into leaner JavaScript functions and supports dedicated whitespace control markers on tag boundaries without overloading raw-output syntax—whereas EJS uses a leading hyphen for unescaped output. When redundant newlines and indentation remain inside template bodies, the compiled function emits extra string literal appends, expanding V8 heap allocations and increasing payload size across thousands of requests per second.

  • Risk formation mechanism: Leaving template caching disabled in production forces repeated filesystem reads and dynamic function compilation per request, which stalls event-loop throughput and masks any engine-level execution gap between Eta and EJS.
  • When Eta stops working here: If your route spends 95% of its latency waiting on external database queries or upstream APIs, switching from EJS to Eta yields negligible end-to-end latency gains; conversely, if you render tiny fragments or flat lists at extreme scale, plain JavaScript template literals avoid engine wrapper overhead altogether.
  • Choice rule: If you serve high-volume public SSR pages with cached templates and want leaner compiled output and tighter payload control, use Eta.

2. Internal Dashboards and Admin Tools

Winner: Eta for multi-view maintainability; EJS only for quick one-off internal screens built by an EJS-fluent developer.

Internal tools accumulate dozens of tables, filter bars, modals, and navigation shells quickly. Because EJS lacks built-in layout composition out of the box, teams frequently copy and paste header wrappers, script tags, and closing tags across views. That duplication creates a mechanical failure mode: editing a shared wrapper in one view leaves stale markup or unclosed HTML elements in another, causing broken DOM nesting and layout shifts in the browser. Eta provides native layout and partial resolution, letting a child view declare its layout and inject its rendered body cleanly.

  • Typical choice error: Assuming prior EJS familiarity makes multi-page admin UIs cheap to maintain—copy-pasted shells silently diverge during refactors, turning minor UI tweaks into multi-file cleanup chores.
  • When Eta stops working here: On a single-engineer internal utility with a tight deadline and zero prior Eta exposure, debugging unfamiliar configuration or block behavior can slow initial delivery more than manual partials would.
  • Choice rule: If the internal tool spans multiple views sharing chrome and navigation, use Eta; if it is a small, short-lived internal tool built rapidly by an EJS-fluent engineer, EJS is acceptable.

3. TypeScript-Heavy Services

Winner: Eta.

In a TypeScript codebase, type mismatches only catch bugs early when types flow across module boundaries into view rendering and configuration. Eta ships native TypeScript types and a zero-dependency footprint, allowing compile-time checking of configuration options and template data contracts before code runs. Loosely typed locals in EJS push missing or renamed properties into runtime execution inside V8, where undefined values degrade into empty strings or unexpected rendering branches long after compilation succeeds.

  • Risk formation mechanism: Embedding heavy business logic or complex mutations directly inside template tags bypasses strict service-layer boundaries and bloats compiled function bodies, making stack traces harder to read when a template expression throws.
  • When Eta stops working here: If your team strictly prefers component-driven UI trees with per-component prop types and client interactivity rather than string templates, a non-Next.js SSR setup may outgrow string templating entirely.
  • Choice rule: If your Node.js service is written in TypeScript and you want compile-time ergonomics alongside lightweight SSR, use Eta.

4. Teams Migrating from EJS or Handlebars

Winner: Eta for greenfield or gradually modernized SSR; EJS when lifting and shifting legacy EJS templates intact under a hard deadline.

Developers coming from EJS or Handlebars face two distinct mental-model shifts. Handlebars isolates templates behind registered helpers and block expressions, requiring helper registration for basic conditionals or array operations; both EJS and Eta execute JavaScript directly, removing missing-helper failures while requiring discipline to keep business logic out of views. Between EJS and Eta, Eta keeps familiar EJS-style delimiters while tracking string literals and comments more accurately during compilation. In EJS, naive delimiter matching can break when a closing sequence appears inside a quoted string or comment; Eta handles string and comment boundaries more reliably and uses <~ for unescaped raw output.

  • Typical choice error: Carrying EJS muscle memory straight into Eta without adjusting raw-output syntax—writing <%- in Eta alters tag parsing rather than simply unescaping output, which can cause malformed output or unexpected tag behavior.
  • When Eta stops working here: If a project must reuse an existing library of EJS templates verbatim on a strict deadline with no time to verify tag differences or edge cases, forcing a migration introduces unnecessary risk.
  • Choice rule: If you are starting a fresh Node.js SSR service with EJS/Handlebars experience and can spend an afternoon learning Eta's layout and raw-output tags, use Eta; if you must reuse existing EJS templates immediately, use EJS.

5. Multi-Surface HTML, Email, and XML Generation

Winner: Eta for modern multi-surface output; EJS only when legacy templates or older Node runtimes dictate compatibility.

Generating HTML pages, transactional emails, XML feeds, or sitemaps from one Node.js service magnifies whitespace and escaping subtleties. In XML feeds and tightly formatted email HTML, stray newlines or unescaped characters corrupt document structure or inflate message byte counts. Eta's whitespace trimming markers, native layouts, zero dependencies, and small footprint (~2–3.5 KB gzipped) fit multi-surface generation cleanly on modern runtimes like Node 20+, whereas EJS (~4.4 KB gzipped core) carries older compatibility assumptions and lacks built-in layout composition.

  • Risk formation mechanism: Both engines rely on dynamic code evaluation (such as function construction) when compiling templates at runtime, and file-based template lookup assumes disk access. In locked-down environments with strict Content Security Policies (CSP) that block runtime code evaluation, or on edge/bundled runtimes without loose view directories, uncached runtime compilation fails at execution time unless templates are precompiled or passed as strings/functions.
  • When Eta stops working here: If your deployment target locks down runtime code generation or omits filesystem view paths and you have not set up precompiled templates or string-based rendering, neither runtime compilation nor file-based resolution will behave as expected.
  • Choice rule: If you generate HTML, emails, and XML on modern Node.js and want built-in layouts with tight whitespace control, use Eta; if you are bound to a legacy Node runtime or existing EJS templates, use EJS.

Security, Edge Cases, and Long-Term Maintenance Risks

Choosing between Eta and EJS for a lightweight Node.js server-side rendering (SSR) stack without Next.js is not just a question of raw throughput or template syntax. Both engines compile text templates into executable JavaScript functions that append strings to an output buffer, which means a single weak spot in escaping, tag parsing, layout composition, or runtime evaluation turns a clean SSR route into a security hole or a multi-hour production outage.

Template Injection and Escaping Pitfalls

Neither Eta nor EJS sandboxes the JavaScript code placed inside scriptlet tags. Both compile template blocks directly into a JavaScript function body and invoke it with a locals object. If an application passes untrusted user input into a template string or allows user-supplied template fragments to reach the compiler, arbitrary code executes inside the Node.js process with full access to environment variables, memory, and internal modules. Even when template source files are trusted, rendering untrusted data values through unescaped output tags mutates the document structure directly.

Escaping mechanics differ between the two engines in ways that create subtle failure modes during migrations:

  • Unescaped output tag divergence: In EJS, <%- expr %> outputs raw, unescaped values, while leading hyphens on trim tags behave differently depending on context. In Eta, <%= expr %> escapes HTML entities by default and <~ expr %> emits raw output without HTML escaping. A developer migrating from EJS who writes <%- userBio %> in Eta or misreads tag modifiers can either leave untrusted HTML unescaped—allowing stored cross-site scripting (XSS) when an attacker injects a <script> tag or event handler into a profile field—or accidentally escape intentional markup such as pre-sanitized SVG fragments or JSON-LD blocks.
  • Context-blind HTML escaping: Standard HTML entity escaping converts characters like <, >, &, ", and ' to keep text inside normal element bodies from opening new tags. It does not protect values interpolated inside unquoted HTML attributes, inline <script> blocks, or CSS style attributes. When an unquoted attribute receives a value containing whitespace and an event handler payload, the HTML parser splits the attribute token and attaches an executable handler to the DOM element.
  • Dynamic code synthesis under strict CSP or locked-down runtimes: Compiling templates on the fly via function constructors requires dynamic code evaluation. In environments enforcing a strict Content Security Policy (CSP) with unsafe-eval disabled, or in locked-down edge isolates that forbid runtime code generation, uncompiled template compilation throws a runtime evaluation error before a single byte of HTML is returned.

Mechanism of risk formation: Untrusted data enters an unescaped or context-mismatched output slot -> the HTML or script parser interprets injected characters as structural delimiters or executable tokens rather than literal text -> attacker-controlled script runs in the victim browser session or crashes the server renderer.

String-Parsing Quirks and Whitespace Edge Cases

Template compilers scan source text using a lexer/parser that separates static literal segments from dynamic tags. When a template contains JavaScript string literals, regexes, or comments that include characters resembling closing tags, a naive scanner loses track of syntax boundaries.

Eta tracks quoted strings and comments inside tags more carefully than older EJS parsing paths, reducing cases where a closing delimiter inside a string literal prematurely terminates a tag and dumps raw JavaScript expressions into the rendered output. Still, edge cases remain in both engines:

  • Quotes and escapes inside interpolated expressions: Complex inline JavaScript expressions inside tags—such as ternary chains with nested quotes, template literals, or regex literals containing slashes—increase parser ambiguity and hurt readability. Moving non-trivial formatting out of templates into typed view helpers prevents parser edge cases and keeps compiled function bodies compact.
  • Whitespace trimming vs. structural markup: Aggressive whitespace pruning strips newlines and indentation to shrink V8 string allocations and wire bytes. In HTML, collapsing whitespace between inline elements can join adjacent words or alter inline-block spacing; in XML feeds, sitemaps, or plain-text transactional emails, stray newlines or missing line breaks can corrupt tag structure or break mail clients.
  • Filesystem coupling in bundled and serverless builds: File-based view resolution assumes loose template files exist on disk at runtime. When bundlers package a Node.js service into a single artifact or deploy to an environment without those view directories on disk, file-path lookups fail with missing-file errors at request time.

Layouts, Partials, and Long-Term Maintenance Risks

Long-term maintenance cost in non-Next.js SSR comes down to how cleanly shared page chrome and data contracts scale as routes multiply. Without a component tree or native layout system, structural changes spread across files.

EJS lacks built-in layout inheritance, pushing teams toward manual duplication of outer document shells, stylesheets, and script tags across views or ad-hoc include patterns. Over time, two failure modes compound:

  • Markup drift and unclosed tags: When a developer updates a header or script tag in one view or partial and misses another, HTML documents diverge across routes. Missing closing tags or mismatched wrappers force the browser HTML parser to perform error recovery, causing layout shifts, broken styles, or hydration mismatches if small client islands are mounted later.
  • Weak type contracts across template boundaries: Passing loosely typed or untyped locals objects into templates defers renamed or missing properties until runtime execution. A renamed field in a service layer may silently evaluate to undefined inside a template, collapsing a conditional block or rendering empty output without a compile-time error.
  • Ecosystem longevity and maintenance trade-offs: EJS has broad historical familiarity and backward compatibility with older Node.js runtimes, which makes it easy to staff for quick maintenance, but its older design assumptions and lack of native layouts place more structural discipline on the team. Eta is smaller, zero-dependency, TypeScript-first, and built for modern runtimes (such as Node 20+), giving a cleaner long-term trajectory for new builds—at the cost of a smaller community footprint and fewer off-the-shelf third-party plugins than a long-established legacy tool.

Typical Choice Errors and Decision Rules

Teams routinely make two opposite mistakes when picking between Eta and EJS for a new Node.js SSR app:

  • Defaulting to EJS out of habit on a multi-page app: Familiarity lowers day-one friction, but copying page shells across dozens of views creates repeated edits during layout changes and leaves type mismatches undetected until runtime.
  • Adopting Eta without production caching or precompilation discipline: Switching to Eta does not automatically eliminate per-request file reads, dynamic compilation overhead, or missing-file errors in bundled deployments if view caching is left off or templates are not precompiled where required.

Optimal choice and boundary conditions: For a new Node.js SSR project without Next.js on modern runtimes (Node 20+), Eta is the optimal default because its native layouts and partials prevent template duplication, its TypeScript support catches data-contract drift earlier, and its lean compilation and whitespace control keep rendering overhead low. Eta stops being the right choice when a deployment environment blocks runtime dynamic code evaluation without precompiled templates, when a project depends on existing EJS templates under a strict deadline, or when a short-lived single-view utility is built by developers who know EJS cold and cannot afford any ramp-up time.

Selection rules:

  • If starting a new non-Next.js Node.js SSR project with multiple views or TypeScript on Node 20+ -> use Eta with template caching enabled and raw output (<~) restricted to verified, sanitized content.
  • If maintaining an existing EJS codebase, reusing legacy EJS templates verbatim under a tight deadline, or supporting older Node.js runtimes -> use EJS, while centralizing shared fragments and validating escaping at every output boundary.
  • If deploying to a strict CSP or locked-down runtime that forbids dynamic code synthesis or loose disk views -> precompile templates or pass precompiled functions/strings rather than relying on uncompiled file lookups at request time.

Decision Framework and Actionable Recommendation

For a new non-Next.js Node.js server-side rendering (SSR) project where you already know EJS and Handlebars, Eta is the optimal default choice. Both engines compile templates into JavaScript functions that append strings to an output buffer, so your existing JavaScript mental model transfers immediately without Handlebars' helper-registration overhead. Eta adds native layouts, built-in TypeScript types, zero dependencies, a smaller footprint (~2–3.5 KB gzipped vs. EJS around 4.4 KB), and stronger tag/string lexing, reducing template boilerplate and runtime string-allocation overhead across multi-view applications.

Choose EJS only when legacy template reuse, strict immediate delivery deadlines with EJS-fluent staff, or older runtime/tooling constraints outweigh layout and type ergonomics.

Selection Matrix: EJS vs. Eta for Node.js SSR

Decision Dimension EJS Eta Winner & Mechanism
Layouts & Shared Chrome No native layout blocks; relies on manual header/footer includes or wrapper partials. Built-in layout() support with rendered child body injection. Eta — eliminates duplicated outer HTML shells and prevents unclosed-tag drift across routes.
TypeScript & Data Contracts Untyped locals objects defer missing or renamed fields until V8 execution. Written in TypeScript with native type definitions for config and template data. Eta — catches mismatched view payloads at compile time instead of letting undefined silently alter branches.
Syntax & Raw Output <%= %> escapes; <%- %> outputs raw HTML. <%= %> escapes; <%~ %> (or <~ %>) outputs raw content. Eta — frees - for left-side whitespace control while isolating raw output under ~.
Lexer & Delimiter Handling Simpler tag scanning can trip when closing sequences appear inside string literals. Tracks strings and comments more accurately during parsing. Eta — prevents premature tag termination and leaked raw scriptlet code inside string expressions.
Familiarity & Ecosystem High historical familiarity and massive weekly npm download volume. Smaller community footprint, though syntax closely mirrors EJS. EJS — lowers first-day onboarding friction when teams already maintain EJS templates.

Explicit Selection Rules

  • If you are starting a greenfield multi-page Node.js SSR app (especially with TypeScript or shared page shells) and want fast rendering without heavy frameworks, then use Eta: native layouts centralize document shells while static types catch prop mismatches before runtime.
  • If you are migrating existing Handlebars views in a new Node.js service, then use Eta: you drop helper boilerplate while gaining built-in layouts and cleaner whitespace control.
  • If you must lift-and-shift an existing library of EJS templates under a tight deadline or support an older Node.js runtime or legacy plugin chain, then use EJS: preserving existing template syntax avoids immediate rewrite risk.
  • If your deployment enforces a strict Content Security Policy blocking dynamic code evaluation (unsafe-eval) or runs in a diskless/single-file bundle without runtime filesystem access, then precompile templates at build time regardless of whether you pick Eta or EJS.

Typical Choice Errors and Their Mechanisms

  • Copying EJS raw-output syntax (<%- %>) blindly into Eta: Because Eta assigns - to whitespace trimming rather than unescaped output, muscle memory triggers parse errors or unintended tag behavior instead of emitting raw markup.
  • Duplicating outer layout markup across EJS views: Without native layout inheritance, updating a head tag or navigation bar across dozens of files causes partial drift; mismatched opening and closing tags force the browser HTML parser to guess tag boundaries, causing layout shifts or broken styles.
  • Passing unvalidated or context-mismatched data into raw/unquoted slots: Neither engine sandboxes embedded JavaScript. Unescaped or context-blind interpolation inside HTML attributes, inline scripts, or URLs allows untrusted input characters to split tokens or execute scripts in the browser, while untrusted template compilation allows remote code execution in Node.js.
  • Over-trimming whitespace in sensitive output formats: Aggressive whitespace pruning reduces string allocations and payload bytes, but stripping spaces between inline elements alters spacing, and missing or stray line breaks can break XML feeds, sitemaps, or plain-text emails.

When Eta Stops Being the Right Choice

Eta stops working well when your UI grows into fine-grained, interactive client components with per-component state and hydration—at that point, string-based SSR templates become awkward and a component framework or island architecture fits better. It is also a poor fit when a strict deadline requires running legacy EJS templates verbatim without time to verify syntax edge cases, or when runtime code compilation and disk view lookups are blocked by locked-down sandboxes without a precompilation step.

Actionable Adoption Checklist

  • Lock in the engine and caching mode: Install eta (or ejs for legacy lift-and-shift) and enable template caching in production so templates compile once rather than re-parsing and recompiling on every request.
  • Define typed view contracts: In TypeScript projects, define explicit interfaces for every route's template locals and helper functions so missing or renamed fields fail type-checking during build.
  • Standardize layout and partial boundaries: Create a base layout template for shared chrome and extract repeated UI fragments into partials; keep business logic and database calls out of template tags.
  • Audit escaping and whitespace rules: Keep default escaped output on by default, restrict raw output tags strictly to trusted or sanitized markup, quote HTML attributes properly, and test whitespace trimming on HTML, email, and XML outputs.
  • Verify build and security constraints: If deploying with strict CSP (no dynamic code evaluation) or bundled/diskless artifacts, add a template precompilation step to your build pipeline and verify error stack traces in staging.

Top comments (0)