Search code examples
javascriptnode.jshapi

Set Hapi plugin option to value from async function call in Node.js


I have a Hapi web application running on Node.js that requires a plugin to handle session using yar. This all works OK except that I need to call an async function the get the cookie password from an Azure Key Vault. I can't see a way to call an async function in this scenario. A cut down version of my index.js looks like this:

async function createServer () {
  const server = hapi.server({
    port: config.port,
    cache: [{
      name: 'session',
      provider: {
        constructor: catbox,
        options: cacheConfig.catboxOptions
      }
    }],
  })

  await server.register(require('./plugins/yar'))

  return server
}

module.exports = createServer

And the yar.js file looks like this:

module.exports = {
  plugin: require('@hapi/yar'),
  options: {
    maxCookieSize: 0,
    storeBlank: true,
    cache: {
      cache: 'session',
      expiresIn: cacheConfig.expiresIn
    },
    cookieOptions: {
      password: (await readSecret('COOKIE-PASSWORD').value),//This line fails
      isSecure: config.cookieOptions.isSecure,
      ttl: cacheConfig.expiresIn
    }    
  }
}

The call to readSecret is the one that is causing me issues as readSecret returns a Promise. How can I fix this ideally without changing the index.js file?


Solution

  • Well I think I've found a solution although I'm not sure it's the best way of doing it. I've created a plugin to register the yar plugin.

    This is my code that is now in the yar.js file:

    module.exports = {
      name: 'yar',
      register: async function (server, options) {
    
        const cookiePassword = (await readSecret('COOKIE-PASSWORD')).value
    
        server.register({
          plugin: require('@hapi/yar'),
    
          options: {
            maxCookieSize: 0,
            storeBlank: true,
            cache: {
              cache: 'session',
              expiresIn: cacheConfig.expiresIn
            },
            cookieOptions: {
              password: cookiePassword,
              isSecure: config.cookieOptions.isSecure,
              ttl: cacheConfig.expiresIn
            }
          }
        })
      },
    }