初始化时从 Vault 中获取秘密 next.js

Fetch secret from Vault when initializing next.js

我正在使用 next.js 和库 https://github.com/auth0/nextjs-auth0/

要初始化该库,我需要使用 async/await 从 Vault 中获取一个秘密,但我得到一个 Promise { <pending> }

我原以为以下方法可行:

// utils/auth0.js

import { initAuth0 } from '@auth0/nextjs-auth0';
const vault = require('./vault');

async function getSecretFromVault() {
  const res = await vault.fetchSecret();
  console.log(res);  // shows my secret correctly
  return res;
}

const secret = getSecretFromVault();
console.log(secret);  // shows Promise { <pending> }

export default initAuth0({
  clientId: "my_ID",
  clientSecret: secret  // this will be invalid: UI shows "client_id is required"
  ....
});

正确的做法是什么?

一个async方法return一个承诺,你应该使用await来获取异步数据。

由于模块导出是一个 sync,因此最好导出一个 async 方法,这将使您调用 Vault 和 return Auth0的初始化。

// utils/auth0.js

import { initAuth0 } from '@auth0/nextjs-auth0';
const vault = require('./vault');

async function getSecretFromVault() {
  const res = await vault.fetchSecret();
  console.log(res); // shows my secret correctly
  return res;
}

let instance;

async function getAuth0() {
  if(instance) {
    return Promise.resolve(instance);
  }
  
  const secret = await getSecretFromVault();
  // -------------^
  instance = initAuth0({
    clientId: 'my_ID',
    clientSecret: secret, // this will be invalid: UI shows "client_id is required"
  });
  
  return instance;
}

export default getAuth0;
// usage

import getAuth0 from './utils/auth0';

export default async function login(req, res) {
  const auth0 = await getAuth0();
  // --------------------^ get instance
  try {
    await auth0.handleLogin(req, res);
  } catch (error) {
    console.error(error);
    res.status(error.status || 400).end(error.message);
  }
}