response
The response global object provides methods to control the HTTP response sent back to the client.
Methods
| Method | Description |
|---|---|
response.setHeader(name, value) | Set a response header |
response.setStatus(code) | Set the HTTP status code |
response.setCookie(name, value, options?) | Set a cookie |
response.setHeader(name, value)
Sets a response header. Can be called multiple times for different headers. The default Content-Type is text/html.
response.setHeader("Content-Type", "application/json");
response.setHeader("X-Powered-By", "js-cgi");
response.setHeader("Cache-Control", "no-cache");
response.setStatus(code)
Sets the HTTP response status code. Default is 200.
// Redirect
response.setStatus(301);
response.setHeader("Location", "/new-page");
// Not found
response.setStatus(404);
print("<h1>Page not found</h1>");
// JSON API error
response.setStatus(400);
response.setHeader("Content-Type", "application/json");
print(JSON.stringify({ error: "Invalid request" }));
response.setCookie(name, value, options?)
Sets a cookie on the response. The optional third argument controls cookie attributes.
Options
| Option | Type | Description |
|---|---|---|
path | string | Cookie path (default: "/") |
maxAge | number | Max age in seconds |
httpOnly | boolean | Not accessible via client-side JS |
secure | boolean | Only send over HTTPS |
sameSite | string | "Strict", "Lax", or "None" |
Examples
// Simple cookie
response.setCookie("theme", "dark");
// Cookie with options
response.setCookie("session", "abc123", {
maxAge: 86400,
httpOnly: true,
secure: true,
sameSite: "Strict"
});
// Delete a cookie
response.setCookie("theme", "", { maxAge: 0 });
Common Patterns
JSON API Response
response.setHeader("Content-Type", "application/json");
response.setStatus(200);
print(JSON.stringify({ users: [{ id: 1, name: "Alice" }] }));
Redirect
response.setStatus(302);
response.setHeader("Location", "/login");
File Download
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"data.csv\"");
print("name,email\nAlice,alice@example.com");