【发布时间】:2019-10-15 09:44:20
【问题描述】:
所以,我尝试在我的 next.js 项目中使用 nounce 属性填充样式组件,但没有成功。正在设置 CSP 的 style-src,但由于未在样式中设置 nounce,因此会引发错误。我还需要做什么才能完成这项工作?
我目前的情况如下:
server.js
server.use((req, res, next) => {
// nonce should be base64 encoded
res.locals.styleNonce = Buffer.from(uuidv4()).toString('base64')
next()
});
server.use('*', (req, res, next) => {
global.__webpack_nonce__ = res.locals.styleNonce;
next()
});
server.use(helmet.contentSecurityPolicy({
directives: {
styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.styleNonce}'`],
}
}));
_document.js
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet();
const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));
const styleTags = sheet.getStyleElement();
return { ...page, styleTags };
}
render() {
return (
<Html lang="en">
<Head>{this.props.styleTags}</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
【问题讨论】:
-
你让它工作了吗?
-
@TheLearner 不,很遗憾。
-
也在为此苦苦挣扎,不知道除了完全删除我的 CSP 或替换样式组件之外还能做什么......
标签: javascript reactjs next.js