The Definitive Guide to doGet(e): Building Web Apps with Google Apps Script
If you have ever wanted to turn a simple Google Sheet into a website, create a custom API for your business, or build a dynamic dashboard that executes code in the cloud, you need to master one specific function: doGet(e).
In the world of Google Apps Script, most scripts are bound to a document or run on a time-based trigger. But doGet(e) is different. It opens the door to the entire internet. It transforms your script from a background task into a live web application that can be accessed by a browser, a mobile app, or another server anywhere in the world.
This guide will take you from the absolute basics of how doGet works to building production-ready APIs and web interfaces.
doGet, your Google Apps Script is locked inside your Google Drive. With doGet, your script gets a public URL (Uniform Resource Locator) and becomes a part of the World Wide Web.
1. What is doGet(e)?
At its core, doGet(e) is a reserved function name in Google Apps Script. When you publish a script as a "Web App," Google's servers listen for HTTP GET requests sent to your script's unique URL.
When that URL is visited (clicked in a browser or fetched via code), Google automatically looks for a function named doGet inside your script file and executes it.
The "e" Parameter
You will often see it written as doGet(e). The e stands for "event object." This is a special object that Google passes to your function automatically. It contains critical information about the request, specifically the URL parameters (query string) that the user added to the link.
2. Technical Deep Dive
Understanding the architecture of this function is vital before writing code. Here is exactly what happens under the hood when a request is made.
Execution Context
When doGet runs, it operates under specific permissions determined when you deploy the web app. You have two choices:
- Execute as Me: The script runs with your permissions, regardless of who visits the URL. This is perfect for public dashboards where users shouldn't need a Google account to see data.
- Execute as User accessing the web app: The script runs with the visitor's permissions. This is useful for internal corporate tools where you need to track who is editing a spreadsheet.
Return Values (Crucial)
Unlike normal functions that can return strings, numbers, or arrays, doGet must return a specific type of object served by the HtmlService or the ContentService. If you return a simple string like return "Hello";, your web app will crash with an error.
You have two main return options:
- HtmlOutput: Used for rendering web pages (HTML, CSS, JavaScript).
- TextOutput: Used for returning raw text, JSON, or XML (for APIs).
doGet generally cannot exceed 6 minutes (or 30 seconds for simultaneous executions in some consumer accounts). Keep your logic fast and efficient.
3. Real-World Use Cases
Where is this actually used in production environments? Here are common scenarios:
- Custom APIs: A third-party service (like Salesforce or Trello) requests data from your Google Sheet via your script URL.
- React/Vue Hosting: Developers use
doGetto serve a singleindex.htmlfile that contains a bundled React application, using Google's servers as free hosting. - Email Unsubscribe Links: When a user clicks "Unsubscribe," the link points to a
doGetscript that updates a "Do Not Contact" sheet. - Dynamic Reports: A manager clicks a link, and the script generates a PDF report based on live Sheets data and serves it immediately.
4. Code Examples
Let’s walk through three distinct levels of implementation.
Level 1: The Basic "Hello World" (Text Output)
This example creates a simple endpoint that displays plain text. It’s useful for testing if your deployment is working.
function doGet(e) {
// Create a text output object
var output = ContentService.createTextOutput();
// Set the content
output.setContent("Hello! The server is running successfully.");
// Return the object (MANDATORY)
return output;
}
Level 2: The Dynamic Greeter (Reading Parameters)
This example reads data from the URL. If the user visits .../exec?name=Sarah&city=London, the script will personalize the response.
function doGet(e) {
// 1. Extract parameters from the event object 'e'
// e.parameter is a key-value map of the query string
var name = e.parameter.name;
var city = e.parameter.city;
// 2. Fallback logic if parameters are missing
if (!name) {
name = "Guest";
}
if (!city) {
city = "Unknown Location";
}
// 3. Construct the HTML string
var htmlString = "<h1>Welcome, " + name + "!</h1>";
htmlString += "<p>We see you are visiting from " + city + ".</p>";
// 4. Return HTML content
return HtmlService.createHtmlOutput(htmlString)
.setTitle("Welcome Page")
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
Code Explanation:
e.parameter.name: Grabs the value of "name" from the URL.createHtmlOutput: Tells Google to render this as a web page, not raw text.setXFrameOptionsMode: Allows this page to be embedded in an iframe (useful for Google Sites).
Level 3: Advanced JSON API (Production Grade)
This is a professional pattern used to serve Google Sheets data as JSON to external applications.
function doGet(e) {
var result = {};
try {
// 1. Security Check: Validate an API token passed in the URL
// URL format: .../exec?action=getData&token=12345
if (e.parameter.token !== "SECRET_API_KEY_123") {
throw new Error("Unauthorized access.");
}
// 2. Business Logic: Check what the user wants to do
if (e.parameter.action === "getData") {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory");
// Get all data (assuming headers in row 1)
var data = sheet.getDataRange().getValues();
result = {
status: "success",
timestamp: new Date(),
data: data
};
} else {
throw new Error("Unknown action provided.");
}
} catch (error) {
// 3. Error Handling: Always return structured JSON errors
result = {
status: "error",
message: error.toString()
};
}
// 4. Return JSON
// MimeType.JSON fixes formatting for browsers and code parsers
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}
doGet inside the Apps Script editor because the editor doesn't pass the e parameter when you click Run. To test, you must write a dummy function like function test() { doGet({parameter: {name: 'Test'}}); } or deploy and visit the URL.
5. Performance Optimization
When you anticipate high traffic to your Web App, efficiency is key. Google Apps Script is not Node.js; it has startup latency.
- Minimize Service Calls: In the API example above, we called
getValues()once. Never putgetValue()inside a loop. Fetch all data at once, then process it in JavaScript memory. - Cache Service: Use
CacheServiceto store results. If your Sheet data only changes once a day, cache the JSON response for 6 hours so the script doesn't have to open the Spreadsheet on every single visit. - Lightweight HTML: If serving a web page, keep your initial HTML payload small and load heavy scripts via CDN links.
6. Security Best Practices
Opening a script to the web carries risks. Follow these rules:
- Never expose private data: If your script runs as "Me" (the owner), anyone with the link can see what your script sees. Ensure you filter data before returning it.
- Sanitize Inputs: If you take user input from a URL parameter and print it directly to HTML, you are vulnerable to XSS (Cross-Site Scripting). Always use
textContentwhen manipulating the DOM client-side, or use templating engine sanitization. - Manage Access: In the deployment settings, you can restrict access to "Only Myself," "Anyone within [My Domain]," or "Anyone." Use "Anyone" with extreme caution.
7. FAQ: Common Developer Questions
This usually happens if you spelled the function name wrong (e.g., Doget or doget). It is case-sensitive. It must be exactly doGet.
This is the #1 confusion for beginners. When you deploy a Web App, you create a "Version." If you change the code, the live URL is still pointing to the old locked version. You must go to Deploy > Manage Deployments > Edit (Pencil Icon) > Version: New Version to push your changes live. Alternatively, use the "Test Deployment" URL for development.
Yes, but you cannot host separate .css or .js files in the Apps Script editor. You must put your CSS inside <style> tags and JS inside <script> tags within your HTML file. Alternatively, you can include external CDNs (like Bootstrap or jQuery).
No. doGet only handles HTTP GET requests. For POST requests (like submitting a form securely), you must use its sibling function, doPost(e).
Conclusion
The doGet function is the bridge that connects the rigid world of spreadsheets to the flexible world of the web. Whether you are building a simple status page for your team or a complex JSON feed for a mobile application, mastering the event object, return types, and deployment versions is essential.
Next Steps: Try building the "Dynamic Greeter" example above. Deploy it, change the URL parameters manually in your browser address bar, and watch the page update instantly. Once you understand that data flow, the possibilities are endless.