Description Adds custom interactivity with data binding and expressions.
Required Script
<script async custom-element="amp-bind" src=""></script>
Tutorials Create interactive AMP pages


The amp-bind component allows you to add custom stateful interactivity to your AMP pages via data binding and JS-like expressions.

Watch this video for an introduction to amp-bind.

A simple example

In the following example, tapping the button changes the <p> element's text from "Hello World" to "Hello amp-bind".

<p [text]="'Hello ' + foo">Hello World</p>

<button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp-bind"</button>

How does it work?

amp-bind has three main components:

  1. State: A document-scope, mutable JSON state. In the example above, the state is empty before tapping the button. After tapping the button, the state is {foo: 'amp-bind'}.
  2. Expressions: These are JavaScript-like expressions that can reference the state. The example above has a single expression, 'Hello ' + foo, which concatenates the string literal 'Hello ' and the state variable foo. There is a limit of 100 operands what can be used in an expression.
  3. Bindings: These are special attributes of the form [property] that link an element's property to an expression. The example above has a single binding, [text], which updates the <p> element's text every time the expression's value changes.

amp-bind takes special care to ensure speed, security and performance on AMP pages.

A slightly more complex example

<!-- Store complex nested JSON data in <amp-state> elements. -->
<amp-state id="myAnimals">
  <script type="application/json">
      "dog": {
        "imageUrl": "/img/dog.jpg",
        "style": "greenBackground"
      "cat": {
        "imageUrl": "/img/cat.jpg",
        "style": "redBackground"

<p [text]="'This is a ' + currentAnimal + '.'">This is a dog.</p>

<!-- CSS classes can also be added or removed with [class]. -->
<p class="greenBackground" [class]="myAnimals[currentAnimal].style">
  Each animal has a different background color.

<!-- Or change an image's src with the [src] binding. -->
<amp-img width="300" height="200" src="/img/dog.jpg"

<button on="tap:AMP.setState({currentAnimal: 'cat'})">Set to Cat</button>

When the button is pressed:

  1. State is updated with currentAnimal defined as 'cat'.

  2. Expressions that depend on currentAnimal are evaluated:

    • 'This is a ' + currentAnimal + '.' => 'This is a cat.'
    • myAnimals[currentAnimal].style => 'redBackground'
    • myAnimals[currentAnimal].imageUrl => /img/cat.jpg
  3. Bindings that depend on the changed expressions are updated:

    • The first <p> element's text will read "This is a cat."
    • The second <p> element's class attribute will be "redBackground".
    • The amp-img element will show the image of a cat.



Each AMP document that uses amp-bind has document-scope mutable JSON data, or state.

Initializing state with amp-state

amp-bind's state can be initialized with the amp-state component:

<amp-state id="myState">
  <script type="application/json">
      "foo": "bar"

Expressions can reference state variables via dot syntax. In this example, will evaluate to "bar".

  • An <amp-state> element's child JSON has a maximum size of 100KB.
  • An <amp-state> element can also specify a CORS URL instead of a child JSON script. See the Appendix for details.

Refreshing state

The refresh action is supported by this component and can be used to refresh the state's contents.

<amp-state id="amp-state" ...></amp-state>
<!-- Clicking the button will refresh and refetch the json in amp-state. -->
<button on="tap:amp-state.refresh"></button>

Updating state with AMP.setState()

The AMP.setState() action merges an object literal into the state. For example, when the below button is pressed, AMP.setState() will deep-merge the object literal with the state.

<!-- Like JavaScript, you can reference existing
     variables in the values of the  object literal. -->
<button on="tap:AMP.setState({foo: 'bar', baz: myAmpState.someVariable})"></button>

In general, nested objects will be merged up to a maximum depth of 10. All variables, including those introduced by amp-state, can be overidden.

When triggered by certain events, AMP.setState() also can access event-related data on the event property.

<!-- The "change" event of this <input> element contains
     a "value" variable that can be referenced via "event.value". -->
<input type="range" on="change:AMP.setState({myRangeValue: event.value})">

Modifying history with AMP.pushState()

The AMP.pushState() action is similar to AMP.setState() except it also pushes a new entry onto the browser history stack. Popping this history entry (e.g. by navigating back) restores the previous value of variables set by AMP.pushState().

For example:

<button on="tap:AMP.pushState({foo: '123'})">Set 'foo' to 123</button>
  • Tapping the button will set variable foo to 123 and push a new history entry.
  • Navigating back will restore foo to its previous value, "bar" (equivalent to calling AMP.setState({foo: 'bar'}).


Expressions are similar to JavaScript with some important differences.

Differences from JavaScript

  • Expressions may only access the containing document's state.
  • Expressions do not have access to globals like window or document.
  • Only white-listed functions and operators may be used.
  • Custom functions, classes and loops are generally disallowed. Arrow functions are allowed as parameters, e.g.
  • Undefined variables and array-index-out-of-bounds return null instead of undefined or throwing errors.
  • A single expression is currently capped at 50 operands for performance. Please contact us if this is insufficient for your use case.

The full expression grammar and implementation can be found in bind-expr-impl.jison and bind-expression.js.


The following are all valid expressions:

1 + '1'           // 11
1 + (+'1')        // 2
!0                // true
null || 'default' // 'default'

White-listed functions

Object type Function(s) Example
Array1 concat
sort (not-in-place)
splice (not-in-place)
// Returns [1, 2, 3].
[3, 2, 1].sort()
// Returns [1, 3, 5].
[1, 2, 3].map((x, i) => x + i)
// Returns 6.
[1, 2, 3].reduce((x, y) => x + y)
Number toExponential
// Returns 3.
// Returns '3.14'.
String charAt
// Returns 'abcdef'.
Math2 abs
// Returns 1.
Object2 keys
// Returns ['a', 'b'].
keys({a: 1, b: 2})
// Returns [1, 2].
values({a: 1, b: 2}
Global2 encodeURI
// Returns 'Hello%20world'.
encodeURIComponent('Hello world')

1Single-parameter arrow functions can't have parentheses, e.g. use x => x + 1 instead of (x) => x + 1. Also, sort() and splice() return modified copies instead of operating in-place.
2Static functions are not namespaced, e.g. use abs(-1) instead of Math.abs(-1).

Defining macros with amp-bind-macro

amp-bind expression fragments can be reused by defining an amp-bind-macro. The amp-bind-macro element allows you to define an expression that takes zero or more arguments and references the current state. A macro can be invoked like a function by referencing its id attribute value from anywhere in your doc.

<amp-bind-macro id="circleArea" arguments="radius" expression="3.14 * radius * radius" />

  The circle has an area of <span [text]="circleArea(myCircle.radius)">0</span>.

A macro can also call other macros defined before itself. A macro cannot call itself recursively.


A binding is a special attribute of the form [property] that links an element's property to an expression.

When the state changes, expressions are re-evaluated and the bound elements' properties are updated with the new expression results.

amp-bind supports data bindings on four types of element state:

Type Attribute(s) Details
Node.textContent [text] Supported on most text elements.
CSS classes [class] Expression result must be a space-delimited string.
The hidden attribute [hidden] Should be a boolean expression.
Size of AMP elements [width]
Changes the width and/or height of the AMP element.
Element-specific attributes Various

Notes on Bindings:

  • For security reasons, binding to innerHTML is disallowed.
  • All attribute bindings are sanitized for unsafe values (e.g., javascript:).
  • Boolean expression results toggle boolean attributes. For example: <amp-video [controls]="expr"...>. When expr evaluates to true, the <amp-video> element has the controls attribute. When expr evaluates to false, the controls attribute is removed.

Element-specific attributes

Only binding to the following components and attributes are allowed:

Component Attribute(s) Behavior
<amp-brightcove> [data-account]
Changes the displayed Brightcove video.
<amp-carousel type=slides> [slide]* Changes the currently displayed slide index. See an example.
<amp-date-picker> [min]
Sets the earliest selectable date
Sets the latest selectable date
<amp-google-document-embed> [src]
Displays the document at the updated URL.
Changes the document's title.
<amp-iframe> [src] Changes the iframe's source URL.
<amp-img> [alt]
When binding to [src], make sure you also bind to [srcset] in order to make the binding work on cache.
See corresponding amp-img attributes.
<amp-lightbox> [open]* Toggles display of the lightbox. Tip: Use on="lightboxClose: AMP.setState(...)" to update variables when the lightbox is closed.
<amp-list> [src] If expression is a string, fetches and renders JSON from the string URL. If expression is an object or array, renders the expression data.
<amp-selector> [selected]*
Changes the currently selected children element(s)
identified by their option attribute values. Supports a comma-separated list of values for multiple selection. See an example.
<amp-state> [src] Fetches JSON from the new URL and merges it into the existing state. Note the following update will ignore <amp-state> elements to prevent cycles.
<amp-video> [alt]
See corresponding amp-video attributes.
<amp-youtube> [data-videoid] Changes the displayed YouTube video.
<a> [href] Changes the link.
<button> [disabled]
See corresponding button attributes.
<fieldset> [disabled] Enables or disables the fieldset.
<image> [xlink:href]
See corresponding image attributes.
<input> [accept]
See corresponding input attributes.
<option> [disabled]
See corresponding option attributes.
<optgroup> [disabled]
See corresponding optgroup attributes
<select> [autofocus]
See corresponding select attributes.
<source> [src]
See corresponding source attributes.
<track> [label]
See corresponding track attributes.
<textarea> [autocomplete]
See corresponding textarea attributes.

*Denotes bindable attributes that don't have a non-bindable counterpart.


Test in development mode (with the URL fragment #development=1) to highlight warnings and errors during development and to access special debugging functions.


In development mode, amp-bind will issue a warning when the default value of a bound attribute doesn't match its corresponding expression's initial result. This can help prevent unintended mutations caused by changes in other state variables. For example:

<!-- The element's default class value ('def') doesn't match the expression result for [class] ('abc'),
     so a warning will be issued in development mode. -->
<p [class]="'abc'" class="def"></p>

In development mode, amp-bind will also issue a warning when dereferencing undefined variables or properties. This can also help prevent unintended mutations due to null expression results. For example:

<amp-state id="myAmpState">
  <script type="application/json">
    { "foo": 123 }

<!-- The amp-state#myAmpState does not have a `bar` variable, so a warning
     will be issued in development mode. -->
<p [text]="">Some placeholder text.</p>


There are several types of runtime errors that may be encountered when working with amp-bind.

Type Message Suggestion
Invalid binding Binding to [someBogusAttribute] on <P> is not allowed. Use only white-listed bindings.
Syntax error Expression compilation error in... Verify the expression for typos.
Non-whitelisted functions alert is not a supported function. Use only white-listed functions.
Sanitized result "javascript:alert(1)" is not a valid result for [href]. Avoid banned URL protocols or expressions that would fail the AMP Validator.
CSP violation Refused to create a worker from 'blob:...' because it violates the following Content Security Policy directive... Add default-src blob: to your origin's Content Security Policy. amp-bind delegates expensive work to a dedicated Web Worker to ensure good performance.

Debugging State

Use AMP.printState() to print the current state to the console.


<amp-state> specification

An amp-state element may contain either a child <script> element OR a src attribute containing a CORS URL to a remote JSON endpoint, but not both.

<amp-state id="myLocalState">
  <script type="application/json">
      "foo": "bar"

<amp-state id="myRemoteState" src="">

XHR batching

AMP batches XMLHttpRequests (XHRs) to JSON endpoints, that is, you can use a single JSON data request as a data source for multiple consumers (e.g., multiple amp-state elements) on an AMP page. For example, if your amp-state element makes an XHR to an endpoint, while the XHR is in flight, all subsequent XHRs to the same endpoint won't trigger and will instead return the results from the first XHR.



The URL of the remote endpoint that will return the JSON that will update this amp-state. This must be a CORS HTTP service.

The src attribute allows all standard URL variable substitutions. See the Substitutions Guide for more info.

credentials (optional)

Defines a credentials option as specified by the Fetch API.

  • Supported values: omit, include
  • Default: omit

To send credentials, pass the value of include. If this value is set, the response must follow the AMP CORS security guidelines.

Deep-merge with AMP.setState()

When AMP.setState() is called amp-bind deep-merges the provided object literal with the current state. All variables from the object literal are written to the state directly except for nested objects, which are recursively merged. Primitives and arrays are in the state are always overwritten by variables of the same name in the object literal.

Consider the following example:

<!-- State is empty -->
<button on="tap:AMP.setState({employee: {name: 'John Smith', age: 47, vehicle: 'Car'}})"...></button>
<button on="tap:AMP.setState({employee: {age: 64}})"...></button>

When the first button is pressed, the state changes to:

  employee: {
    name: 'John Smith',
    age: 47,
    vehicle: 'Car',

When the second button is pressed, amp-bind will recursively merge the object literal argument, {employee: {age: 64}}, into the existing state.

  employee: {
    name: 'John Smith',
    age: 64,
    vehicle: 'Car',

employee.age has been updated, however and employee.vehicle keys have not changed.

Please note that amp-bind will throw an error if you call AMP.setState() with an object literal that contains circular references.

Removing a variable

Remove an existing state variable by setting its value to null in AMP.setState(). Starting with the state from the previous example, pressing:

<button on="tap:AMP.setState({employee: {vehicle: null}})"...></button>

Will change the state to:

  employee: {
    name: 'John Smith',
    age: 48,


<button on="tap:AMP.setState({employee: null})"...></button>

Will change the state to:

<!-- State is empty -->

Expression grammar

The BNF-like grammar for amp-bind expressions:

  | invocation
  | member_access
  | '(' expr ')'
  | variable
  | literal

    '!' expr
  | '-' expr
  | '+' expr
  | expr '+' expr
  | expr '-' expr
  | expr '*' expr
  | expr '/' expr
  | expr '%' expr
  | expr '&&' expr
  | expr '||' expr
  | expr '<=' expr
  | expr '<' expr
  | expr '>=' expr
  | expr '>' expr
  | expr '!=' expr
  | expr '==' expr
  | expr '?' expr ':' expr

    expr '.' NAME args

    '(' ')'
  | '(' array ')'

    expr member

    '.' NAME
  | '[' expr ']'


  | TRUE
  | NULL
  | object_literal
  | array_literal

    '[' ']'
  | '[' array ']'

  | array ',' expr

    '{' '}'
  | '{' object '}'

  | object ',' key_value

  expr ':' expr