Search code examples
node.jstwiliorequiresendgrid

Node/Twilio multiple config variables in require function


I was wondering if any other people have managed to find a way to use multiple account sids and auth tokens when using Twilio for Node. The documentation is pretty straight forward, and I am able to use Twilio with my own credentials.

However, while using subusers on Twilio, I want to be able to use their credentials in the process of purchasing a phone number. I currently have a app.post route which first fetches the sid and auth token of the specific user.

let twilioSid = process.env.REACT_APP_TWILIO_ACCOUNT_SID;
let twilioAuthToken = process.env.REACT_APP_TWILIO_AUTH_TOKEN;

let twilioClient = require('twilio')(twilioSid, twilioAuthToken);

Before doing the actual "purchase" of that number, I retrieve the subuser sid and auth token and update my variable before I call the function, like so:

const user = await admin.firestore().collection("users").doc(userId).get()
                
twilioSid = user.data().sid;
twilioAuthToken = user.data().authToken;

const purchase = await twilioClient.incomingPhoneNumbers.create({phoneNumber: number})

The purchase works, but only for my main (parent) account with the credentials stored in .env. It seems that the top variables never actually gets updated before the incomiingPhoneNumbers.create gets called. Can anyone point me in the right direction on how I would be able to use the subuser credentials to run this function?


Solution

  • Updating the variables only won't do the job here because you already initialized the client. It should work when you reinitialize the client (or just init another client):

    const user = await admin.firestore().collection("users").doc(userId).get()
                    
    twilioSid = user.data().sid;
    twilioAuthToken = user.data().authToken;
    
    twilioClient = require('twilio')(twilioSid, twilioAuthToken);
    
    const purchase = await twilioClient.incomingPhoneNumbers.create({phoneNumber: number})
    

    or

    const user = await admin.firestore().collection("users").doc(userId).get()
                    
    twilioSid = user.data().sid;
    twilioAuthToken = user.data().authToken;
    
    const userClient = require('twilio')(twilioSid, twilioAuthToken);
    
    const purchase = await userClient.incomingPhoneNumbers.create({phoneNumber: number})