Twilio class method not working inside function

I’m running a function trying to obtain a token from twilio. Everything goes well until I call the method token.toJwt() at that point I get the following error {"message":"Value is not an object: undefined","name":"TypeError"}.

Running exactly the same function in my local node works perfectly so I don’t understand what is causing the method to fail. I double checked that all env variables are correct. Any ideas will be greatly appreciated.

The code is basically the same as in Twilio docs: Create Access Tokens for Conversations | Twilio

exports = async function() {
  // Documentation: https://www.twilio.com/docs/conversations/create-tokens
  const twilio = require('twilio');
  const AccessToken = twilio.jwt.AccessToken;
  const ChatGrant = AccessToken.ChatGrant;
  
  // Twilio tokens and keys
  const twilioAccountSid = context.values.get("TWILIO_ACCOUNT_SID_VALUE");
  const twilioApiKey = context.values.get("TWILIO_API_KEY_VALUE");
  const twilioApiSecret = context.values.get("TWILIO_API_SECRET_VALUE");

  // Used specifically for creating Chat tokens
  const serviceSid = context.values.get("TWILIO_CHAT_SERVICE_SID_VALUE");

  // Only application users can request a chat token
  // This can be changed if other services need a token
  if (context.user.type !== "normal") {
    return { error: "Error: Not an application user." }
  }
  
  try {
    // Create a "grant" which enables a client to use Chat as a given user, on a given device
    const chatGrant = new ChatGrant({
      serviceSid: serviceSid,
    });
    
    // Create an access token which we will sign and return to the client,
    // containing the grant we just created
    const token = new AccessToken(
      twilioAccountSid,
      twilioApiKey,
      twilioApiSecret,
      { identity: context.user.data.email }
    );
    
    token.addGrant(chatGrant);
    
    return { token: token.toJwt() };
  } catch (err) {
    console.log(err.stack);
    console.log("Error occurred while getting a chat token:", err.message);
    return { error: err };
  }
};