nonce-express

1.0.2 • Public • Published

All aboard the nonce-express!

Choo choo/bzfS2qzo/Q==!

nonce-express is a simple low-code express middleware to help generate nonces. It uses the built-in crypto module to generate "cryptographically strong pseudorandom data" to be exposed at res.locals.nonce.

What's also cool, is that you can choose how many bytes of data you want your nonce to be, as well as what variable name you want it to be exposed as!

Everything you need

  1. Install
npm install --save nonce-express
  1. Use the middleware
// ...

const nonce = require("nonce-express");
app.use(nonce({ // These are the defaults
    varName: "nonce",
    size: 16
}));

// ...
  1. Use the generated nonce
// ...

// In helmet
app.use(helmet({
    contentSecurityPolicy: {
        useDefaults: true,
        directives: {
            scriptSrc: [
                "'self'",
                (req, res) => `'nonce-${res.locals["nonce"]}'`,
            ]
        }
    }
}));

// In your app
app.get("/", (req,res) => res.send(`<script nonce="${res.locals.nonce}">alert("Hello, there!")</script>`));

// ...

Final words

Now that this readme is officially longer than the actual nonce.js file, I think it's time to end it here.

MIT License, 2021 Jarod Brennfleck

Package Sidebar

Install

npm i nonce-express

Weekly Downloads

433

Version

1.0.2

License

MIT

Unpacked Size

2.98 kB

Total Files

3

Last publish

Collaborators

  • thebrenny