Handling SSR with JSDOM window to work with DOMPurify

This commit is contained in:
Nordine M'LISSA 2018-09-03 23:05:10 +02:00
parent 9fd34eaf80
commit 47ed43ba42
3 changed files with 479 additions and 111 deletions

View File

@ -44,6 +44,7 @@
}, },
"dependencies": { "dependencies": {
"babel-preset-env": "^1.7.0", "babel-preset-env": "^1.7.0",
"dompurify": "^1.0.5" "dompurify": "^1.0.5",
"jsdom": "^12.0.0"
} }
} }

View File

@ -1,16 +1,29 @@
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import DOMPurify from 'dompurify'; import DOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
// for now this icons json is generated via the build script from latest feather // for now this icons json is generated via the build script from latest feather
// TODO: automatically generate this JSON via this repo's build script // TODO: automatically generate this JSON via this repo's build script
import icons from './icons.json'; import icons from './icons.json';
class IconInner extends PureComponent { class IconInner extends PureComponent {
createMarkup(markup) { createMarkup(markup) {
// sanitize markup first: // sanitize markup first:
const sanitizedMarkup = DOMPurify.sanitize(markup); let sanitizedMarkup = DOMPurify.sanitize(markup);
// handling server rendering
if (!window) {
// We create a window out of JSDOM
const window = (new JSDOM('')).window;
// Plug it to DOMPurify
const DOMPurifyServer = DOMPurify(window);
// and then sanitize markup
sanitizedMarkup = DOMPurifyServer.sanitize(markup);
}
// now do the weird thing for dangerouslySetInnerHTML // now do the weird thing for dangerouslySetInnerHTML
return {__html: sanitizedMarkup}; return { __html: sanitizedMarkup };
} }
render() { render() {
// <g> is just a wrapper it does nothing except let me use valid JSX markup // <g> is just a wrapper it does nothing except let me use valid JSX markup

570
yarn.lock

File diff suppressed because it is too large Load Diff