Skip to content
This repository was archived by the owner on Jan 22, 2020. It is now read-only.

[v1.x] add nonce to the script tag for unsafe-inline #196

Open
wants to merge 5 commits into
base: v1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
16 changes: 15 additions & 1 deletion lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ var TEMPLATE = ['<script id="%s" type="application/javascript">var ',
' = %s;</script>'
].join('');

var TEMPLATE_WITH_NONCE = ['<script id="%s" nonce="%s" type="application/javascript">var ',
Config.client.variableName,
' = %s;</script>'
].join('');

exports.create = function create(createOptions) {

createOptions = createOptions || {};
Expand Down Expand Up @@ -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('</body>', script + '</body>');

return done(null, html);
Expand Down