---
title: Output Encoding For Dynamic JS/JSON
impact: HIGH
impactDescription: prevents injection in JavaScript contexts
tags: xss, javascript, json, encoding, security
---

## Output Encoding For Dynamic JS/JSON

Embedding user data in JavaScript or JSON requires proper encoding to prevent code injection.

**Incorrect (unescaped data in JS):**

```go
// XSS in inline script
func ProfileHandler(w http.ResponseWriter, r *http.Request) {
    username := r.Context().Value("username").(string) // "</script><script>alert('xss')"
    fmt.Fprintf(w, "<script>var user = '%s';</script>", username)
}
```

**Correct (proper JSON encoding):**

```go
func ProfileHandler(w http.ResponseWriter, r *http.Request) {
    user := struct {
        Name string `json:"name"`
    }{
        Name: "User Name",
    }
    
    // json.Marshal properly escapes special characters
    safeData, _ := json.Marshal(user)
    
    fmt.Fprintf(w, `
        <script>
            var user = %s;
        </script>
    `, safeData)
}

// Using html/template (SAFE)
tmpl := template.Must(template.New("profile").Parse(`
    <script>
        var user = {{.}};
    </script>
`))
tmpl.Execute(w, user) // Automically encodes as JSON for JS context
```

**Tools:** `html/template`, `json.Marshal`
