Skip to content

Add Support for Easily Configuring a Nonce. #4258

Closed

Description

@ekramer-taulia

With the widespread adoption of the Content Security Policy header and the known security risks associated with using unsafe-inline, Styled Components should provide an easier way to apply a nonce to its inline styles so unsafe-inline is not required.

I have examined some of the suggested workarounds, but none of them are straight forward or applicable to my use case, and I think a simple way to configure a nonce at runtime with a value provided from any server would provide much better nonce support in Styled Components.

Use Case

In my case I am not using Styled Components directly in my app, but it is being used by another library that I am using (Looker), so the solutions suggested here are not easily implemented.

Suggested Solution

I suggest a way to globally configure the nonce that Styled Components uses for all style tags appended to the document. In my use case a unique nonce value from the server is assigned to a variable on the window object on every request. When the React application initializes, that nonce variable could be assigned to a nonce configuration object that Styled Components uses for all subsequent style tags.

I have looked at the nonce support using the webpack_nonce variable, but this has some problems

  • not all applications will be using the webpack bundler (Vite for example)
  • I don't think webpack_nonce is intended to be part of webpack's public api (it is intended to be used internally by its own loaders), so it is probably not stable for use, which could be related to the next point
  • It does not work as intended (I was able to get it to work with this work around)

I think it would be relatively easy to add a nonce API that builds off of this util, but allows the nonce to defined at runtime, something like this:

// index.js

import nonceConfig from 'styled-components'

// ...

nonceConfig.setNonce(window.myNonce)

// nonce.ts

+ import nonceConfig from 'styleComponents'

declare let __webpack_nonce__: string;

export default function getNonce() {
  + const configuredNonce = nonceConfig.getNonce()
  + if (configuredNonce) {
  +   return configuredNonce
  + }
  return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
}

I would be happy to make a PR to implement this if the maintainers agree.

Thank for you consideration

Activity

  1. Varnius commented on Mar 8, 2024

    @Varnius

    Voting this up!
    The proposed solution would work, though our use case is a bit different - it's a library that our clients add to their page in order to render a UI widget. The library uses styled-components and some of the clients want to add a nonce value to the style block in order to apply proper CSP. We currently use a patched version of styled-components but it's a hassle when we want to update the version in use.

  2. barbalex commented on Mar 15, 2024

    @barbalex

    I just ran into this building an electron app. Electron wants devs to define a csp (https://www.electronjs.org/docs/latest/tutorial/security#7-define-a-content-security-policy).

    Which failed in my case because the app is using styled-components and thus this error occurs:

    Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.
    
    index-BHPOJIUy.js:40 Error: An error occurred. See https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#17 for more information.
        at Eh (index-BHPOJIUy.js:68:4015)
        at index-BHPOJIUy.js:68:6579
        at new e (index-BHPOJIUy.js:68:6586)
        at index-BHPOJIUy.js:68:8976
        at e.getTag (index-BHPOJIUy.js:68:8996)
        at e.insertRules (index-BHPOJIUy.js:68:9330)
        at e.generateAndInjectStyles (index-BHPOJIUy.js:68:13004)
        at index-BHPOJIUy.js:68:14927
        at index-BHPOJIUy.js:68:14985
        at b (index-BHPOJIUy.js:68:15128)
  3. bayasdev commented on Sep 16, 2024

    @bayasdev

    +1

  4. gregtalarico commented on Oct 9, 2024

    @gregtalarico

    +1

  5. omatviiv commented on Oct 24, 2024

    @omatviiv

    But webpack only bundles once, its not a runtime tool. And nonce has to be highly dynamic and random value, it has to be used only once and thrown away. I don't understand how webpack could help to solve this issue.

  6. ccreighton-apptio commented on Oct 30, 2024

    @ccreighton-apptio

    @omatviiv this is the current implementation of getNonce:

    export default function getNonce() {
      return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
    }

    so styled-components is already looking for a value to set, but doesn't provide any way to properly configure this value.

  7. omatviiv commented on Oct 31, 2024

    @omatviiv

    @ccreighton-apptio thank you I successfully managed to configure styled-components with __webpack_nonce__.
    It was quite confusing, I tried to set __webpack_nonce__ in different ways so that nonce is guaranteed to be random on every subsequent request to the server but styled-components didn't see it.

    The only way that worked for me was to set webpack_nonce into ejs template:

      <script type="text/javascript" nonce="<%-nonce%>">
        window.nonce = '<%-nonce%>';
      </script>

    and then at the very top of react application on ui to do the following:

      __webpack_nonce__ = window.nonce || '';

    Actually thats what webpack documentation actually says to set it in the entry file.

    I suspect its so confusing because of the nature of these webpack special variables - they are not really a variable in any javascript scope but an instruction to webpack to set or inject some value and then to do with that value whatever webpack does... (something similar to webpack's __filename).

    So I definitelly vode +1 to make it more strait forward.

  8. added 6 commits that reference this issue on Mar 19, 2026
    40cf8bf
    b5c7867
    f608c01
    a37e67f
    dd6af1e
    86b74fd
  9. added a commit that references this issue on Mar 19, 2026
    79cc7b4
  10. quantizor commented on Mar 19, 2026

    @quantizor
    Contributor

    This fix is available in [email protected]. Please try it and report any issues:

    npm install [email protected]
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions