I am running a basic HTML & Javascript app (connecting to Google and Twilio API), and keep getting the reference error that a variable is not defined

I built a basic HTML & Javascript app to translate a few words from the Google Translate API then text them to a number via Twilio. Here is my HTML:

<!DOCTYPE html>
<script type = "text/javascript" src="script.js"></script>
<p>Click the button to receive 3 Hebrew texts</p>  
<input id="clickMe" type="button" value="clickme" onclick="myFunction();" />

And here is script.js:

function myFunction(){

// Imports the Google Cloud client library
const {Translate} =require('@google-cloud/translate').v2;

// Creates a client in Google API
const projectId = 'Xx'
const keyFilename = '/Users/x/Downloads/vocal-lead-306923-b3d8f6749397.json'
const translate = new Translate({projectId, keyFilename});

const lang = "he"

// Creates a client in Twilio API
const accountSid = 'Xx'
const authToken = 'Xx'
const client = require('twilio')(accountSid,authToken);

/** Set variables for input in Google API */
const text = ['One day'];
const target = lang;

async function translateText() {
    // Translates the text into the target language. "text" can be a string for
    // translating a single piece of text, or an array of strings for translating
    // multiple texts.
    let [translations] = await translate.translate(text, target);
    translations = Array.isArray(translations) ? translations : [translations];
    translations.forEach((translation, i) => {
        setTimeout(() => {
     // Sends messages via Twilio  
                body: `${translation}`

    }, i * 10000);


By itself, the script works but it doesn’t work when I run it from my local browser. I hit inspect and I get this error:

Uncaught ReferenceError: require is not defined at myFunction (script.js:5) at HTMLInputElement.onclick (index.html:8)

I took out auth keys/any personal data but I think that is all correct. Any advice would be helpful!


If you’re trying to run the script in browser, it won’t work. This is because require() is a nodejs feature, and so anything that depends on libraries by require needs to be done in a nodejs backend (you can communicate between html frontend and nodejs backend over http for example; see https://expressjs.com/ and https://nodejs.org/en/ the latter has builtin http but for routing express is recommended).

You mention that you’ve removed private information for this SO post, but keep in mind that when you publish this site and the script.js is visible to the user (i.e. inspect element) it’ll be freely accessible. It is not good practice to put secrets in the frontend code. Consider this: a bad actor uses your API key to send spam SMS on your behalf… not good.

Also see: How to use google translation api with react