1.0.2 • Published 3 years ago

nonce-express v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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