JS fetch in Google Docs add-on causing authentication issues

I’m working on a Google Docs add-on and I’m stuck. I’m trying to get data from an outside API in a custom dialog. When users input data, it’s supposed to fetch an SVG element. But I keep getting a 401 error (Unauthorized).\n\nHere’s a simplified version of my code:\n\njavascript\nasync function fetchData() {\n const userInput = 'some_value';\n const secretKey = 'my_secret_key';\n const requestBody = {\n 'input': userInput,\n 'key': secretKey,\n 'mode': 'dark'\n };\n\n try {\n const result = await fetch('https://api.example.com', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(requestBody)\n });\n // Handle response\n } catch (error) {\n console.error('Fetch error:', error);\n }\n}\n\n\nThe weird thing is, when I use curl outside of Google, it works fine. I’ve looked for answers, but most talk about calls TO Google Apps Script, not FROM it.\n\nI don’t want to use URLFetch on the server side. It would slow down the UI and doesn’t feel right for what I’m doing.\n\nAre there any special rules for making outside API calls from a Google add-on? Any ideas on how to fix this?

I’ve been down this road before, and it’s a tricky one. The 401 error you’re seeing is likely due to Google’s strict security measures for add-ons. Client-side fetch calls are a no-go in this environment, unfortunately.

In my experience, the only reliable way to make external API calls in a Google Docs add-on is through server-side URLFetchApp. I know it’s not what you want to hear, but it’s the reality of working within Google’s ecosystem.

Here’s what worked for me: I moved all my API calls to the server-side script, then used google.script.run to communicate between the client and server. It’s a bit more complex, but it bypasses the authentication issues.

Also, be careful with how you’re handling that secret key. You might want to store it server-side to keep it secure. Good luck with your project!

hey, i had a similar issue. maybe it’s a cors problem, try using ‘mode:cors’? if that doesn’t help, look into proxying your call since google docs addons can block cross domain requests. hope this helps.

I’ve encountered this issue before. The problem likely stems from Google’s security restrictions on add-ons. Client-side fetch calls are generally not allowed in Google Docs add-ons due to these limitations. Unfortunately, you’ll probably need to use server-side URLFetchApp for API calls. While it may not be ideal for your use case, it’s often the only reliable way to make external requests in this environment. Consider restructuring your add-on to handle API calls on the server-side, then pass the results to your client-side code for rendering. This approach, though less direct, should resolve the authentication issues you’re facing.