Skip to content

JLarky/react-json-script

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@jlarky/react-json-script

Why

This causes hydration error (see why dangerouslySetInnerHTML in https://blog.logrocket.com/improving-react-seo-structured-data/#adding-structured-data-react-app):

const App = () => {
  const data = {"id":1};

  return <script>{JSON.stringify(data)}</script>
}

This causes XSS (see https://pragmaticwebsecurity.com/articles/spasecurity/json-stringify-xss):

const App = () => {
  const data = {"content":"</script><script>alert('gotcha!')</script>","id":1};

  return <script dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }} />
}

Installation

bunx jsr add @jlarky/react-json-script
# or
npx jsr add @jlarky/react-json-script

Example

import { JsonScript } from "@jlarky/react-json-script";

const data = {
    "@context": "https://schema.org",
    "@type": "Organization",
    "url": "http://www.example.com",
    "name": "Unlimited Ball Bearings Corp.",
    "contactPoint": {
        "@type": "ContactPoint",
        "telephone": "+1-401-555-1212",
        "contactType": "Customer service"
    }
};

const App = () => (
  <JsonScript type="application/ld+json" data={data} />
);

Development

To install dependencies:

bun install

To publish:

bun run publish

About

Safe(r) way to set json content of script tag

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published