JSX Purify
Installation
- npm
- Yarn
- pnpm
npm install jsx-purify
yarn add jsx-purify
pnpm add jsx-purify
Setup your JSX transpiler
To use JSX Purify, you need to setup your JSX transpiler to use the jsx-purify/react
package as the JSX factory. This is done differently depending on the transpiler you are using.
- Typescript
- Babel
- Vite
- Vite SWC
- Webpack
- Per file
tsconfig.json
{
"compilerOptions": {
"jsxImportSource": "jsx-purify/react"
}
}
.babelrc
{
"plugins": [
[
"@babel/plugin-transform-react-jsx",
{
"importSource": "jsx-purify/react"
}
]
]
}
If you are using Typescript, you can use the Typescript configuration too.
vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
esbuild: {
jsxImportSource: "jsx-purify/react",
},
});
vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
export default defineConfig({
plugins: [
react({
jsxImportSource: "jsx-purify/react",
}),
],
});
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: "babel-loader",
options: {
plugins: [
[
"@babel/plugin-transform-react-jsx",
{
importSource: "jsx-purify/react",
},
],
],
},
},
],
},
],
},
};
Most JSX transpilers allow you to specify the JSX factory per file. This is useful if you want to use JSX Middlewares in only some files.
my-file.jsx
/** @jsxImportSource jsx-purify/react */
export function App() {
return <h1>Hello World</h1>;
}
Usage
After you setup the transpiler, all JSX created with jsx-purify Runtime will be safe to execute in a client browser.
untrusted.jsx
/** @jsxImportSource jsx-purify/react */
export function App() {
return (
<div>
<script>alert('Bad actor')</script>
<h1>Hello World</h1>
<img onerror={() => alert("Bad actor")} src="nonsense" />
<p>This is a paragraph</p>
</div>
);
}