diff --git a/README.md b/README.md index bd0ef68..126f8e5 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ var engine = require('react-engine').server.create({ * In development mode, views are automatically reloaded before render. So there is no need to restart the server for seeing the changes. * You can use `js` as the engine if you decide not to write your react views in `jsx`. * [Blog on react-engine](https://www.paypal-engineering.com/2015/04/27/isomorphic-react-apps-with-react-engine/) +* You can add [nonce](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#Unsafe_inline_script) in `_locals`, which will be added in `script` tag that gets injected into the server rendered pages, like `res.locals.nonce = 'nonce value'` ### License [Apache Software License v2.0](http://www.apache.org/licenses/LICENSE-2.0) diff --git a/lib/server.js b/lib/server.js index 109519f..cb08a45 100644 --- a/lib/server.js +++ b/lib/server.js @@ -35,6 +35,11 @@ var TEMPLATE = ['' ].join(''); +var TEMPLATE_WITH_NONCE = ['' + ].join(''); + exports.create = function create(createOptions) { createOptions = createOptions || {}; @@ -123,7 +128,16 @@ exports.create = function create(createOptions) { html += React.renderToString(componentInstance); // state (script) injection - var script = format(TEMPLATE, Config.client.markupId, JSON.stringify(data)); + //add nonce to the script tag for unsafe-inline; + var script; + + if (options.nonce) { + script = format(TEMPLATE_WITH_NONCE, Config.client.markupId, + options.nonce, JSON.stringify(data)); + } else { + script = format(TEMPLATE, Config.client.markupId, JSON.stringify(data)); + } + html = html.replace('', script + ''); return done(null, html);