JS fetch in Google Docs add-on throws 401 error

Hey everyone, I’m stuck with a problem in my Google Docs add-on. I’m trying to get some data from an external API in a custom dialog, but it’s not working.

When I try to fetch an SVG element after the user inputs some data, I keep getting a 401 Unauthorized error. Here’s a simplified version of my code:

async function getData() {
  const userInput = 'some_value';
  const secretKey = 'my_secret_key';
  const requestBody = {
    input: userInput,
    key: secretKey,
    mode: 'dark'
  };

  try {
    const result = await fetch('https://api.example.com', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    });
    // Handle response
  } catch (error) {
    console.error('Error:', error);
  }
}

The weird thing is, when I use curl outside of Google, it works fine. I’ve looked around, but most answers are about calling Google Apps Script instead of making external calls.

I prefer not to use UrlFetchApp on the server since it might slow down the UI, especially when data is already being displayed in the open dialog.

Does anyone know if there are special security rules for external API calls in Google add-ons? Any help would be awesome!

I encountered a similar issue when developing a Google Docs add-on. The 401 error you’re getting is likely due to Google’s security restrictions on client-side API calls from add-ons.

Here’s what worked for me: instead of making the fetch call directly from the client-side JavaScript, I created a server-side Apps Script function to handle the API request. Then, I used google.script.run to call this function from the client-side.

It might look something like this:

// In your Apps Script file
function makeApiCall(userInput, secretKey) {
  var url = 'https://api.example.com';
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify({
      input: userInput,
      key: secretKey,
      mode: 'dark'
    })
  };
  var response = UrlFetchApp.fetch(url, options);
  return response.getContentText();
}

// In your client-side JavaScript
function getData() {
  const userInput = 'some_value';
  const secretKey = 'my_secret_key';

  google.script.run.withSuccessHandler(function(result) {
    // Handle the API response here
  }).makeApiCall(userInput, secretKey);
}

This approach bypasses the client-side restrictions and should resolve your 401 error. Although it adds an extra step, it provides a reliable workaround when dealing with external API calls in Google Docs add-ons.

yo, i had similar probs with my add-on. google’s pretty strict bout client-side calls. have u tried using a proxy server? it could handle the api requests and send back results to ur add-on. might solve the 401 issue without messing with ur UI speed. just an idea, lemme know if u need more details on settin it up!

Having worked on several Google Docs add-ons, I can confirm that client-side API calls are indeed restricted. The 401 error you’re encountering is a result of these security measures.

While using UrlFetchApp on the server side is a common solution, I understand your concerns about potential UI slowdowns. An alternative approach you might consider is implementing a caching mechanism in your Apps Script backend.

You could set up a function that fetches and caches the API data at regular intervals, then have your client-side code retrieve this cached data instead of making direct API calls. This way, you maintain the responsiveness of your UI while still adhering to Google’s security policies.

Remember to handle potential cache misses and implement appropriate error handling. This method has worked well in my projects, balancing performance and security requirements.