Skip to main content
Security guideReviewed

Server-side template injection: pass the text into the template, never build the template from it

Server-side template injection happens when text from a visitor, a customer or a staff member becomes part of a template your server renders, so the template engine reads it as instructions instead of printing it.

This guide explains what a template engine is for, where the flaw comes from, how to tell it from XSS and what the engines' own sandboxes cover. It comes with a Node.js lab, a harmless arithmetic canary and a regression test you can run on your own machine.

Template-rendering lab, arithmetic canary and engine checks

An illustration written for this page, not client code. A deliberately tiny stand-in engine renders an invented shop's email preview through a flawed handler that builds the template from the visitor's text and a fixed handler that passes it as a value, with the real output of each.

How to use it

Tests on Node.js's built-in runner show the stand-in engine rejecting every name it was not given, and a regression test fails on the flawed handler and passes on the fixed one. Engine-specific checks for Jinja, Twig, Handlebars, Mustache and Nunjucks follow, each from that engine's own documentation. For learning and for testing a template path you own.

server-side-template-injection.txt

Introduction6 lines

ILLUSTRATION FOR LEARNING. The hardware shop, its order email and every input below were written for this page. Nothing here is a client's code or a client's result. Run the lab on your own machine to learn, and use what it teaches to test a template path you own. Do not point any part of it at a system you do not own or are not authorised in writing to test. The asset has three parts: Part 1 The template-rendering lab: a stand-in engine, a flawed and a fixed handler, and what each one rendered. Part 2 The tests: one file that checks the stand-in engine rejects everything except supplied values and arithmetic, and a regression test that fails on the flawed handler and passes on the fixed one. Part 3 Engine-specific remediation checks for Jinja, Twig, Handlebars, Mustache and Nunjucks, each answer taken from that engine's own documentation.

What server-side template injection is

Server-side template injection (SSTI) is what happens when a server renders a template that was built, in part, out of someone else's text.

The template engine cannot tell that text apart from the template your developers wrote, so any template syntax inside it runs. MITRE catalogues the weakness as CWE-1336, Improper Neutralization of Special Elements Used in a Template Engine: a product uses a template engine to insert or process externally influenced input, but does not neutralise, or incorrectly neutralises, special elements or syntax that the engine can interpret as template expressions or other code directives.

CWE-1336 gives Server-Side Template Injection (SSTI) as an alternate term for injection into template engines used by a server, and Client-Side Template Injection (CSTI) for engines used by a client.

James Kettle, Director of Research at PortSwigger, set out the technique in a research paper titled "Server-Side Template Injection", published on 5 August 2015 and also presented at Black Hat USA. Its conclusion says template injection had remained relatively unknown up to that point.

The paper calls it a frequently critical vulnerability that is extremely easy to mistake for cross-site scripting, or miss entirely. OWASP's Web Security Testing Guide covers it as WSTG-INPV-18, Testing for Server-side Template Injection, which says these vulnerabilities occur when user input is embedded in a template in an unsafe manner and results in remote code execution on the server.

The standards file it with code injection. CWE-1336 sits beneath CWE-94, Improper Control of Generation of Code, and lists the execution of unauthorised code or commands as a consequence, and the OWASP Top 10:2025 maps CWE-94 to A05 Injection. ASVS 5.0 requirement 1.3.7, at Level 2, asks that an application protects against template injection by not allowing templates to be built from untrusted input, and that where there is no alternative, any untrusted input included dynamically during template creation is sanitised or strictly validated.

What a template engine is for, and the two ways to give it text

An order confirmation, an invoice, a password reset email, a shipping notification and a page listing a customer's bookings all have a fixed shape with a few details that change.

A template is that shape written once, with marked gaps for the details, and a template engine fills the gaps each time an email, document or page is produced. PortSwigger's paper opens on the same point: template engines are widely used by web applications to present dynamic data via web pages and emails.

Engines give a template more than gaps. Jinja's documentation says a template contains variables and/or expressions, which get replaced with values when it is rendered, and tags, which control the logic of the template, and Twig's documentation says much the same.

Both list arithmetic operators: in Jinja's words, {{ 2 * 2 }} would return 4. Nunjucks lists the same kind of operators, with the note that they should be used sparingly because most of your logic should be in code.

That power is useful to the developer who writes a template. It becomes the problem when someone else writes part of it.

There are two ways to put a customer's text into a template. The first passes it in as a value: the template has a gap called giftMessage, and the code fills it with whatever the customer typed. The second builds the template out of the text: the code joins the customer's words into the template source and asks the engine to render the result, so the engine reads those words as part of the template, braces and all.

Kettle's paper uses a marketing application that greets email recipients by name.

Passing the name in to the template works fine; once users are allowed to customise the emails, the user controls the content of the template itself rather than a value passed into it.

Where template injection comes from in practice

Kettle's paper describes two routes in.

Template injection can arise through developer error, and through the intentional exposure of templates to offer rich functionality, which it says is commonly done by wikis, blogs, marketing applications and content management systems. WSTG-INPV-18 names wiki pages, reviews, marketing applications and CMS systems among the features that may be vulnerable. In a business application, these are the shapes to look for:

  • A "customise your email template" setting, where a customer or a staff member edits the wording of emails your system sends. If what they type is saved and later rendered as a template, they are writing template code.
  • A preview feature that joins the visitor's text into the template so the preview looks right, such as the gift message preview in the lab on this page.
  • An error page or a "page not found" message whose template is built from the address that was requested, so whatever was in the address becomes template text.
  • A marketing or newsletter tool that lets staff edit templates in the browser. Twig's documentation is direct about what that hands over: Twig treats templates as trusted code, and rendering a template written by an untrusted author without its sandbox gives that author the same power as your application code.
  • Input that lands inside a template statement rather than in its text, such as a parameter that names which variable to print. WSTG-INPV-18 calls this the code context, and Kettle's paper says this variant is even easier to miss, because it does not result in obvious XSS.

Why the accidental route goes unnoticed

The paper says template injection can also arise by accident, when user input is concatenated directly into a template, and compares it to SQL injection in poorly written prepared statements. It adds that unintentional template injection is extremely easy to miss, as there typically won't be any visible cues.

The first input in the lab shows why: an ordinary message renders identically through the flawed handler and the fixed one, so a feature can pass any test that only checks how real customer text looks on the page, while building its template from that text.

How to tell template injection from cross-site scripting

From the outside the two can look the same, because text a visitor typed changes the page.

The difference is where the text is interpreted. Cross-site scripting is the browser reading text as markup or script, inside one visitor's session, and the XSS guide in this library covers it. Template injection is the server's template engine reading text as template syntax before the page or email is sent, with whatever the engine can reach on the server.

MITRE and PortSwigger both warn about the overlap. CWE-1336 says that in some cases XSS-style attacks can work, which can obscure the root cause if the developer does not closely investigate it, and its notes say XSS is also co-located with template injection. In Kettle's marketing email example the flaw produces an XSS vulnerability that is hard to miss, and the paper calls that XSS just a symptom of a subtler, more serious vulnerability: unlike XSS, it says, template injection can be used to directly attack web servers' internals and often obtain remote code execution.

A canary separates them. Send harmless arithmetic, such as {{ 7*7 }}, through the input, then read the response the server sent, not the page the browser shows. If the response holds 49 where the text should be, the server evaluated it, and that is template injection, whatever the page also does with markup.

If the braces come back as typed, the engine treated the text as data, at least for that syntax. CWE-1336 uses the same arithmetic, written without spaces as {{7*7}}, as its example for some template languages, and WSTG-INPV-18's Flask and Jinja2 example, which writes it the same way, returns Hello 49!.

The lab's flawed handler shows both findings from one root cause: a bold tag passes through as markup, and the canary comes back as 49.

From a number on the page to code on the server

A 49 on the page is where the trouble starts, not where it ends.

WSTG-INPV-18 sets three objectives: detect template injection points, identify the template engine, and build the exploit. Kettle's paper follows the same order. After detection it identifies the engine, then reads the engine's documentation and explores what a template can reach, where it says you can expect to find both default objects provided by the engine and application-specific objects passed in by the developer, and that developer-supplied objects are particularly likely to contain sensitive information.

The consequences match. CWE-1336 lists executing unauthorised code or commands. WSTG-INPV-18 says working through the objects, methods and properties a template can reach could lead to privilege escalation and to disclosure of application passwords, API keys, configuration and environment variables. Kettle's conclusion says that when template injection occurs, regardless of whether it was intentional, it is frequently a critical vulnerability that exposes the web application, the underlying webserver and adjacent network services.

What code can do once it runs on a server depends on the process it runs in, which the remote code execution guide covers.

This page stops at the canary. It describes the rest at the level a defender needs and publishes no expressions that reach an engine's internals, read files or run commands, in any engine's syntax. Proving the flaw does not need them: a computed number where the customer's text should be is enough evidence to fix the code.

Template sandboxing: what the engines' own documentation says

A sandbox is a mode that limits what a template can reach, meant for templates written by people you do not trust.

CWE-1336's mitigations are to choose a template engine that offers a sandbox or restricted mode, or at least limits the power of any available expressions, function calls or commands, and to use the engine's sandbox or restricted mode if available.

Kettle's paper explains why such modes exist: intentional template injection is such a common use-case that many template engines offer a sandboxed mode for that express purpose. Each engine's documentation is careful about the limits of its own.

Jinja: SandboxedEnvironment

Jinja's documentation says its sandbox can be used to render untrusted templates, and that access to attributes, method calls, operators, mutating data structures and string formatting can be intercepted and prohibited. Its security considerations begin with the sentence "The sandbox alone is not a solution for perfect security", then list what remains: templates can still raise errors, a relatively small template can render a very large amount of output, which could mean high CPU or memory use, Jinja only renders text and does not understand, for example, JavaScript code, and you should pass only the data relevant to the template.

Jinja's changelog lists changes to how the sandbox applies its checks in both 3.1.5, released on 21 December 2024, and 3.1.6, released on 5 March 2025, so the installed version matters.

Twig: the Sandbox class

Twig's documentation says its sandbox is the only security boundary for templates written by untrusted authors. A sandboxed template can use only the tags, filters, functions and tests you allow, and only the object methods and properties you allow, under a strict security policy and an environment dedicated to the sandbox, never your application environment.

From Twig 3.29 that is the Sandbox class; the older SandboxExtension is internal, and its methods for switching the sandbox on are deprecated. A section titled What the Sandbox Does Not Protect Against lists six things: data you pass is readable; allowed operations use their arguments freely; objects must behave consistently, because an object that produces different elements on each iteration can give an operation elements the sandbox never checked, and Twig does not consider such bypasses security issues; your own filters, functions and extensions run with full power; template text is output as written, HTML and JavaScript included; and resources are not limited, which it says to contain at the process level.

Handlebars, Mustache and Nunjucks

Handlebars documents no sandbox. Its Security page says not to rely on Handlebars alone as a security sandbox, and to compile and render user-supplied templates in an isolated sandbox, such as a separate process or container with strict CPU, memory, file system and network limits. Nunjucks says it does not sandbox execution, so it is not safe to run user-defined templates or inject user-defined content into template definitions, and that on the server this can expose attack vectors for accessing sensitive data and remote code execution.

The mustache(5) page describes a logic-less language, with no if statements, else clauses or for loops, only tags, and describes no sandbox.

Anyone tempted to build a sandbox for a JavaScript engine out of Node.js should note that its documentation says the node:vm module is not a security mechanism and not to use it to run untrusted code.

SSTI prevention: a fixed template, with the text passed as a value

The fix is the one ASVS 5.0 requirement 1.3.7 asks for: do not build templates from untrusted input.

OWASP's Top 10:2025 says the best means to prevent injection requires keeping data separate from commands and queries. To a template engine, the template source is the command. Load templates from files your developers control, refer to each by a fixed name, and pass every piece of customer text in as a value. In the lab, that is the whole difference between the flawed handler and the fixed one.

  • Find every call that compiles a template from a string: Environment.from_string() or the Template class in Jinja, a template created from a string in Twig, Handlebars.compile() in Handlebars, and renderString() or compile() in Nunjucks. Trace each string back to its origin. A constant in your code is fine. A string holding anything from a request, a record a customer can edit or a setting staff can change is the flaw.
  • Where a template genuinely has to vary with input, such as a choice between two layouts, map the input to one of a fixed set of template names in code. ASVS 1.3.7 falls back to sanitising or strictly validating input only where there is no alternative, and Kettle's paper found that regular expressions are not an effective defence, so prefer a fixed list to a filter.
  • Pass a template only what it prints. Twig's documentation says a template can iterate over every variable it is given, Handlebars says not to give a template access to secrets or privileged application objects unless it genuinely needs them, and Jinja says to pass only the data relevant to the template. Input I4 in the lab shows why: the flawed handler printed a staff-only note it had been handed for no reason.
  • Turn auto-escaping on, and know where it stops. Jinja's default configuration is no automatic escaping, and its documentation encourages configuring it explicitly. Twig and Nunjucks escape by default, and Handlebars and Mustache escape double-brace output but not triple-brace output. Twig's documentation puts the limit plainly: auto-escaping only applies to printed expressions. Text that has become part of the template is not a printed value, which is why the flawed handler's bold tag reached the page, and why escaping does not fix template injection.
  • Treat helpers and filters as code that template input reaches. Handlebars says a helper must validate its arguments and must not turn template input into arbitrary file, network, database or command access. A helper or filter that starts an operating system program is a command injection question, and the command injection guide covers it.
  • Keep engine errors away from template authors and visitors. Kettle's paper notes that engines may identify themselves in error messages, and Twig's documentation says error messages shown to template authors reveal names, such as the class of an object or registered filters with similar names.

When customers or staff need to edit templates

Sometimes editing is the feature: customers write their own invoice wording, or a marketing team changes campaign emails without a developer.

Kettle's paper answers the question directly. If user-supplied templates are a business requirement, the lowest risk approach is to use a trivial template engine such as Mustache, or Python's Template. A fixed list of merge fields, such as the customer's first name and the order number, that your own code swaps for escaped values follows the same idea, and the lab's stand-in engine shows how narrow such a feature can be kept: supplied values and arithmetic, nothing else.

Where a fuller template language is needed, use the engine's sandbox exactly as its documentation describes, and add the limits that the same documentation says the sandbox leaves out. The paper's 2015 verdict explains the caution: it demonstrated escapes from sandboxes whose entire purpose is to handle user-supplied templates, called parser-level sandboxes error prone, and concluded that many of the technologies designed to prevent templates from doing harm were immature and should not be relied on except as a defence in depth measure.

  • Render user templates in an environment kept for them: a SandboxedEnvironment in Jinja, or in Twig the Sandbox class with a strict security policy and a dedicated environment. Allow only the tags, filters and functions the feature needs.
  • Pass a small, documented set of data. Jinja's sandbox page gives the model: users of an internal reporting system create custom emails, the developers document what data is available, and the code passes the report data to the user's sandboxed template. Avoid objects with methods that have side effects; Jinja offers an unsafe() decorator to stop templates calling a method, and an ImmutableSandboxedEnvironment to stop them changing lists and dictionaries.
  • Limit resources. Jinja says to run with limits on CPU and memory. Twig says a template can consume as much CPU, memory or time as it wants even under the strictest policy, and to contain sandboxed renders at the process level. Handlebars calls templates from users untrusted programs for resource-consumption purposes, and lists limits including template size, nesting depth, input and output size, timeouts and rate limits.
  • Isolate the renderer. Handlebars says to compile and render user-supplied templates in an isolated sandbox, such as a separate process or container with strict CPU, memory, file system and network limits, with a minimal data object and no application credentials or host access. Kettle's paper describes a locked-down container as another, complementary approach.
  • Treat template editing as code access. Twig says rendering an untrusted author's template without the sandbox gives that author the same power as your application code. Decide who may edit templates the way you decide who may change code: named people, every change recorded and reviewed, and the permission removed when someone leaves.
  • Check the output where it lands. Jinja notes that it only renders text and does not understand JavaScript, and Twig that a sandboxed template's text is output as written, HTML and JavaScript included. If a customer's template ends up in a page or email other people open, handle it like any other HTML a user supplied.

Server-side template injection testing on a template path you own

WSTG-INPV-18 describes two contexts.

In the plaintext context, the tester sends common template expressions and watches the responses for one the server executed. In the code context, the input lands inside a template statement, such as a variable name, so the tester looks for blank or error responses and then for a way out of the statement.

The guide then moves on to identifying the engine and building an exploit. On a template path you own, the first step is the useful one: you are looking for evidence that the template is built from input, and a computed number is that evidence.

CWE-1336 lists automated static analysis as a detection method that can find some instances of the weakness, typically by modelling data flow and control flow and searching for patterns that connect sources of input with sinks, and rates its effectiveness as High.

OWASP's Top 10:2025 says injection is best detected by combining source code review with automated testing of all parameters, headers, URL, cookies, JSON, SOAP and XML inputs. Test only systems you own or are authorised in writing to test.

  • Start in the code, with the template-from-string calls listed in the prevention section, and trace each string back to its origin.
  • Send the arithmetic canary through every input that ends up in a rendered page, email or document: form fields, URL parameters, profile fields and anything staff edit later. Use a product unlikely to appear by chance.
  • Read the raw response or the source of the generated email, not the browser's rendering. A computed number means the server evaluated the input.
  • Try your own engine's delimiters as well as double braces, and follow stored values: text saved through one form can be rendered later in a different template, such as a staff notification.
  • Stop at the number. It is enough to report and fix, and on a live system there is nothing to gain from going further.
  • Add a regression test like the lab's, which fails while the template source changes with the input.

Running the template lab and reading its output

The lab in the asset is an illustration for learning and for testing a template path you own.

The lab installs no template engine, so it includes a deliberately tiny one written for this page: double-brace placeholders, small arithmetic expressions inside them, and HTML escaping for values. It stands in for a real engine, and nothing it shows about itself carries over to Jinja, Twig, Handlebars, Mustache or Nunjucks. Everything runs with Node.js alone, and every output in the asset was recorded on Node.js v26.0.0 on macOS.

compare.mjs sends six inputs through two handlers for an invented hardware shop's gift message preview, and prints the template source each one gave the engine beside what it rendered. The flawed handler's template source is different for every input, because it is built from the input, while the fixed handler's never changes and the visitor's text arrives as a value called giftMessage.

With the canary, the flawed handler rendered 49 and the fixed handler rendered the braces as typed.

Asked for {{ internalNote }}, the flawed handler printed a staff-only note it had been given, and the fixed handler, which passes only the values its template prints, showed the braces.

Two test files use Node's built-in test runner. engine.test.mjs checks the stand-in engine: arithmetic works, values come out escaped, a value is never read as a template, and every name the code did not supply is rejected, including properties every JavaScript object inherits, such as constructor and toString, and runtime globals such as process and globalThis.

Property access, calls, quotes and assignment are rejected too, and a last check confirms the engine's source contains no call to eval or Function and no import of node:vm.

That proves the property for this engine only. A real engine gives a template far more to work with, so for yours, work through Part 3 of the asset.

preview.test.mjs is the regression test. For each input it checks that the template source does not change and that the message comes back exactly as typed, escaped. Against the fixed handler all twelve checks passed and the process exited with code 0.

Against the flawed handler eleven failed and it exited with code 1: every input changed the template source, the ordinary message included, and five of the six did not come back as typed.

The Node.js documentation says the exit code is set to 1 when any test fails, so the test can sit in a build pipeline and stop a change that brings the flaw back.

Where an outside review fits

The lab checks the template paths you already know about.

A review looks for the ones you do not, such as a preview feature added for one campaign or a template string assembled several calls away from the request. Clever Ops reviews code for custom web applications and their APIs, such as Next.js, React and Node applications, using read-only access to your repository, and the review follows the paths in scope with untrusted input in view.

Code findings are confirmed against a running build where the scope allows, and the report marks any that rest on the code alone. The secure code review guide explains how that review is scoped and what its report records.

A web application and API penetration test exercises the running application, and read-only code access to named areas can be added to confirm how a control is enforced. If your application runs on Next.js, the Next.js guide in this library shows how each of its server entry points is tested.

If Clever Ops built or hosts the application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

If a tender or contract requires a CREST-accredited provider, Clever Ops is not CREST accredited, so we refer that work to a provider that is.

Frequently asked questions

It is what happens when a website builds a template, the pattern it uses for an email, document or page, out of text someone else typed, so the template engine reads that text as instructions instead of printing it. If the engine does arithmetic, {{ 7*7 }} comes back as 49. Depending on the engine and what it can reach, the same mistake can expose data the template was given or let code run on the server. CWE-1336 lists executing unauthorised code or commands as a consequence.

No, although one can look like the other. XSS is a visitor's browser running text as script. Template injection is the server's template engine running text as template syntax before the page is sent. CWE-1336 notes that in some cases XSS-style attacks can work, which can obscure the root cause if the developer does not closely investigate it, and PortSwigger's research calls the XSS just a symptom of the more serious server-side flaw. A canary that comes back as a computed number in the server's response points to the server.

No. Escaping protects the values a template prints, and Twig's documentation says auto-escaping only applies to printed expressions. Once a visitor's text has been joined into the template source it is part of the template, not a value, so it is not escaped. The lab shows both sides: the fixed handler escaped a bold tag, while the flawed handler passed it through and evaluated the canary.

A sandbox narrows what a template can reach, and the engines' own documentation says not to stop there. Jinja says its sandbox alone is not a solution for perfect security. Twig lists what its sandbox does not protect against, including readable data and unlimited resources. Handlebars says not to rely on Handlebars alone as a security sandbox, and Nunjucks says it does not sandbox execution. Pair a sandbox with a small data set, resource limits and an isolated process, or give customers a fixed list of merge fields instead.

Not entirely. The mustache(5) page calls Mustache logic-less, with no if statements, else clauses or for loops, only tags, and PortSwigger's research names a trivial engine such as Mustache as the lowest risk approach when user-supplied templates are a business requirement. A tag still reaches whatever data you pass, so pass only what the template prints. Handlebars also warns that user templates can consume substantial CPU, memory or output space even when they cannot execute arbitrary JavaScript.

On a template path you own, send harmless arithmetic such as {{ 7*7 }} through each input and read the raw response or the generated email. A number where the text should be is the finding, and there is no need to go further. Test only systems you own or are authorised in writing to test, and keep a regression test that fails if the template source ever changes with the input, like the one in the lab.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.