Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 61 ยท Performance and Quality

Security in Themes

Secure your Shopify theme: stop XSS with the escape filter, output data safely into HTML, attributes and scripts, handle customer data and judge third-party scripts and app embeds.

A Shopify theme is code that runs in your visitors' browsers, on a page that also holds their cart, their account links and often their payment intent. Shopify secures the platform itself: hosting, checkout, payments and the customer account system. What it cannot secure for you is the way your theme prints data. If your Liquid writes a value from the address bar into the page without escaping it, an attacker can run JavaScript in a shopper's browser. That is cross-site scripting (XSS), and it is the main security risk in theme code.

This lesson explains where untrusted data comes from, which output context needs which encoding, how to treat customer data and third-party scripts, and what a Content Security Policy can and cannot do on a theme. Liquid examples target current Online Store 2.0 themes. Details of platform behavior change, so check the current Shopify documentation for security-sensitive features before relying on them.

Liquid cannot run on this site, so the theme snippets are read-only. The runnable examples are stand-ins: a JavaScript version of the escape filter and a small scanner that flags risky output. The real escape filter is built into Shopify's Liquid engine; the stand-in only imitates its basic behavior so you can see an attack succeed and fail.

Liquid does not escape for you

In many template engines, printing a value escapes HTML by default. Shopify's Liquid does not. {{ search.terms }} prints the raw text of whatever the visitor typed. If the visitor's text is <img src=x onerror=alert(1)>, the browser receives a working tag.

The fix is the escape filter, which turns the characters & < > " ' into HTML entities so the browser shows them as text:

LIQUID
<h1>Results for "{{ search.terms | escape }}"</h1>

A rule you can apply without thinking: every value that a shopper, or anyone but you, can influence is escaped when printed into HTML, unless you have a specific reason it is already safe. That includes search.terms, customer.first_name, cart.note, line item properties, form fields posted back to the page, query parameters read with JavaScript, and metafield values of the single-line text type.

Which values are safe without escaping? Content that merchants write with Shopify's own rich text and description editors, such as product.description or a richtext setting, is HTML on purpose; merchants and their staff are trusted (and Shopify sanitizes rich text settings). Printing them with escape would show visible tags. The line to draw is between merchant content and visitor input.

flowchart TD
    V["Who controls the value?"] --> M["Merchant or staff<br/>(descriptions, richtext, settings)"]
    V --> S["Shopper or any visitor<br/>(search terms, notes, names, URL, properties)"]
    M --> MH["HTML output is intended<br/>do not escape rich text"]
    S --> SE["Escape it every time<br/>or avoid printing it"]

Trust follows the author of the value, not the Liquid object it comes from.

Context decides the encoding

HTML escaping protects text between tags. The same value used in other places needs more care.

Where the value lands What to do
Between tags: <p>{{ x }}</p> {{ x | escape }}
In a quoted attribute: <input value="{{ x }}"> {{ x | escape }}, and always use quotes around the attribute
In a URL: href="{{ x }}" Never output visitor input as a whole URL; a javascript: link runs code. Build URLs from known routes and | url_encode parts
In inline JavaScript: var q = "{{ x }}"; Do not do this with visitor input. Pass data through an attribute or a JSON script block instead
In CSS or a style attribute Do not output visitor input here

Inline JavaScript is the dangerous case, because escaping HTML entities does not make a string safe inside a script. Instead of building JavaScript strings from Liquid, put the value into a data- attribute (escaped as an attribute) and read it with element.dataset:

LIQUID
<div id="results" data-terms="{{ search.terms | escape }}"></div>
<script>
  const terms = document.getElementById('results').dataset.terms;
</script>

For whole objects, use the json filter inside a JSON script block, which the browser never runs as code, and read it with JSON.parse:

LIQUID
<script type="application/json" id="ProductJson-{{ section.id }}">
  {{ product | json }}
</script>

The json filter is the right tool for merchant data such as products. Do not assume it neutralizes every dangerous character in a string you paste into an executable <script> body, and never print visitor input into script code. When you must handle visitor input in JavaScript, treat it as text: set textContent, never innerHTML.

A stand-in escape filter

To feel the difference, run the stand-in below. It renders the same template twice with an attack string as the search term: once without escaping (what the browser would execute) and once with the filter. It imitates escape's basic behavior; it is not Shopify's code.

JS Escaping an attack string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first term is harmless either way. The other three are classic payloads: a tag with an error handler, a closing quote that escapes the attribute and injects a script, and an attribute injection. With the filter, each one prints as plain text. The detector here is a rough regular expression written for the demo, so do not use it as a real security tool.

Find unescaped output in your own theme

Code review should look for visitor-controlled objects printed bare. The scanner below walks a few template lines and flags output of known risky sources that is not piped through escape. It is a teaching aid with a short list; real review is also about context.

JS Scan a template for unescaped input

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Line 6 shows the point of the context table: the value was escaped, but it still sits inside script code, which is why it is flagged. Moving it into a data- attribute removes the risk.

Customer data in Liquid

Customer information is personal data. Keep three habits:

  • Do not dump objects into the page. {{ customer | json }} writes the customer record into the HTML source, where every script on the page, including third-party scripts, can read it. Print only the fields a visitor needs to see, and only when customer exists.
  • Keep private data off public pages. Account pages require sign-in; do not copy their data into pages that are shared or cached. See Customer Accounts and Account Pages.
  • Use Shopify's forms. The {% form %} tag adds hidden fields, including a token that ties the submission to the page it came from. A hand-written <form> that posts to a Shopify endpoint can lose that protection. See Forms: Contact, Newsletter and Custom Forms.

Payment, address entry for orders and card data are handled by Shopify's checkout, which is outside your theme. Your theme should never ask for card numbers. The security side of the shop as a whole (CSRF, session handling, rate limits) is covered in Shop Security.

Third-party scripts and app embeds

Every script on the page runs with the same power as your own code: it can read the DOM, see what customers type into your forms, and add more scripts. A chat widget, a review app and a tag manager are all trusted code you did not write. Treat them accordingly:

  • Add only what you need and remove what you stopped using. Old script tags often remain in theme.liquid long after an app is uninstalled.
  • Prefer apps that use app blocks and app embeds, which merchants can switch off in the editor and which are cleaned up when the app is removed (App Blocks and App Embeds).
  • Load scripts from the vendor's HTTPS URL only, never from an HTTP page, and be wary of unknown domains in content_for_header output.
  • If a vendor publishes a hash for a file, integrity (Subresource Integrity) can pin the exact bytes, but it breaks when the vendor updates the file, so it suits fixed versions only.
  • Do not paste a script from an email or a chat message into your theme without reading it.

What a Content Security Policy can do here

A Content Security Policy (CSP) tells the browser which sources of scripts it may run. On a custom server you would send it as an HTTP header. A Shopify theme does not control the response headers of the storefront, and the platform itself injects inline scripts through content_for_header, as do many apps. A strict policy that forbids inline scripts therefore tends to break the page, the theme editor or apps. In practice, themes rely on escaping and on limiting third-party code rather than on a CSP. Some policy features may exist through a <meta> tag, but it cannot cover everything a header can, so test carefully if you try one and do not count it as your main defense.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A visitor opens /search?q=<script>x()</script>. Your template prints {{ search.terms }}. What happens?

    Shopify's Liquid does not escape output by default. Without the escape filter, the visitor's text becomes real HTML in the page.
  2. 2. Which value should you normally NOT pass through the escape filter?

    Merchant-authored rich content is meant to be HTML, so escaping it would show tags as text. Visitor-controlled values are the ones to escape.
  3. 3. Why is {{ search.terms | escape }} inside a script block still a problem?

    Escaping protects HTML contexts. Inside script code the value is parsed as JavaScript, so pass it through a data attribute or a JSON script block and read it as text.
  4. 4. Why is a strict Content Security Policy hard to rely on in a Shopify theme?

    Because inline scripts come in through content_for_header and apps, a policy that bans them breaks pages, so escaping and limiting third-party code are the practical defenses.

Summary

  • Liquid output is not escaped by default; use | escape for every visitor-controlled value printed into HTML text or attributes.
  • Trust follows the author: merchant rich text is HTML on purpose, visitor input never is.
  • Escaping is context-specific. Never put visitor input into inline JavaScript, CSS or whole URLs; use data- attributes, JSON script blocks and textContent.
  • Do not dump customer objects into the page, and use the {% form %} tag so forms carry their protection fields.
  • Treat third-party scripts and app embeds as trusted code you must audit, limit and remove when unused.
  • A CSP is a weak fit for themes; the escape habit and script hygiene do the real work.

Next: App Blocks and App Embeds