In my rich client, I escape user-provided data before rendering to prevent XSS.

The data comes from the server unescaped. That is necessary for application logic, e.g., avoiding situations where I mistakenly check "O&Donnell"==="O'Donnell"

Yet an attacker can send the user a link to direct GET access to the underlying JSON API; or the user might stumble upon it. This enables XSS.

How do I prevent this? CSRF tokens? Setting content-type to plaintext or JSON and not HTML? Some other approach?

  • how would a link to a json file enable XSS? text pages don't execute anything...
    – dandavis
    Feb 23, 2018 at 20:27

3 Answers 3


Setting content-type to plaintext or JSON and not HTML?

If the API returns JSON, then you should the content type to application/json. Apart from just being correct, this will also stop any XSS issues. If a user navigates directly to an API endpoint in their browser, the browser will just show the raw JSON and not try to render any HTML or run any scripts.


You might send the data from the API base64 encoded, then base64 decode it in the client before processing. Anyway I strongly recommend properly checking and validating untrusted data on server side too:



As Andres mentioned, if the application communicates over JSON, make sure the Content-type is set to application/json and not text/html.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .