title: When outputting JSON content via Javascript, should I HTML escape on the server or client side?
body: <p>I have an application that consists of a server-side REST API written in PHP, and some client-side Javascript that consumes this API and uses the JSON it produces to render a page.  So, a pretty typical setup.</p>
  
  <p>The data provided by the REST API is "untrusted", in the sense that it is fetching user-provided content from a database.  So, for example, it might fetch something like:</p>
  
  <pre><code>{
      "message": "&lt;script&gt;alert("Gotcha!")&lt;/script&gt;"
  }
  </code></pre>
  
  <p>Obviously, if my client-side code were to render this directly into the page's DOM, I've created an XSS vulnerability.  So, this content needs to be HTML-escaped first.</p>
  
  <p>The question is, when <strong>outputting</strong> untrusted content, should I escape the content on the server side, or the client side?  I.e., should my API return the raw content, and then make it the client Javascript code's responsibility to escape the special characters, or should my API return "safe" content:</p>
  
  <pre><code>{
      "message": "&amp;lt;script&amp;gt;alert(&amp;#039;Gotcha!&amp;#039;);&amp;lt;\/script&amp;gt;"
  }
  </code></pre>
  
  <p>that has been already escaped?</p>
  
  <p>On one hand, it seems to be that the client should not have to worry about unsafe data from my server.  On the other hand, one could argue that output should always be escaped at the last minute possible, when we know exactly <em>how</em> the data is to be consumed.</p>
  
  <p>Which approach is correct?</p>
  
  <p>Note: There are plenty of questions about handling input and yes, I am aware that client-side code can always be manipulated.  This question is about <em>outputting</em> data <em>from</em> my server which may not be trustable.</p>
  
  <p><strong>Update</strong>: I looked into what other people are doing, and it does seem that some REST APIs tend to send "unsafe" JSON. Gitter's API actually sends both, which is an interesting idea:</p>
  
  <pre><code>[
      {
          "id":"560ab5d0081f3a9c044d709e",
          "text":"testing the API: &lt;script&gt;alert('hey')&lt;/script&gt;",
          "html":"testing the API: &amp;lt;script&amp;gt;alert(&amp;#39;hey&amp;#39;)&amp;lt;/script&amp;gt;",
          "sent":"2015-09-29T16:01:19.999Z",
          "fromUser":{
              ...
          },"unread":false,
          "readBy":0,
          "urls":[],
          "mentions":[],
          "issues":[],
          "meta":[],
          "v":1
      }
  ]
  </code></pre>
  
  <p>Notice that they send the raw content in the <code>text</code> key, and then the HTML-escaped version in the <code>html</code> key.  Not a bad idea, IMO.</p>
  
  <p><strong>I have accepted an answer, but I don't believe this is a cut-and-dry problem.  I would like to encourage further discussion on this topic.</strong></p>