Skip to content

k.response ​

HTTP response processing - write output, headers, views, binary/files, status codes, page meta, and redirects

Execution ContextPrerequisitesTypical Use
KScript APIs; meta/executeView/stop mainly in Page/Layout/View <script env="server">Referenced View or site file must exist for view/file helpersEmit JSON/HTML/file downloads, set status codes & headers, redirect, and set head meta

k.response provides methods for shaping HTTP responses, including writing bodies, setting headers, executing views, returning files or binary downloads, configuring status codes, stopping template rendering, redirecting, and setting page head metadata.

Quick Start ​

js
k.api.get(() => {
  k.response.setHeader("Content-Type", "application/json; charset=utf-8")
  k.response.setHeader("X-Served-By", "Kooboo")
  k.response.json({ success: true, timestamp: Date.now() })
})

Quick Reference ​

Method / PropertyDescriptionReturns
metaRead/write current page <title> and <meta> (matches k.page)PageMeta
write(value)Write primitive or JSON-serialized object to bodyvoid
json(value)Serialize JSON to body (keeps default Content-Type unless set)void
setHeader(key, value)Set a custom HTTP response headervoid
statusCode(code)Set the HTTP response status codevoid
unauthorized()Set status code 401 (empty response body)void
notFound()Set status code 404void
redirect(url, absolute?)Send an HTTP redirect responsevoid
executeView(viewNameOrId)Execute a View directly into the current responsevoid
renderViewAsString(viewNameOrId)Render a View and return its HTML string (null if missing)string | null
file(path, contentType?, fileName?)Send a file from the k.file disk folder (always sets Content-Disposition: attachment)void
binary(contentType, bytes, filename?)Send a binary byte-array response or downloadvoid
execute(url)Render another site Page or fetch an http(s):// URL and append outputvoid
stop()Cancel downstream page/template rendering (use JS return to exit early)void

meta ​

k.response.meta is the object-style counterpart of k.page for configuring <title> and <meta> tags during HTML page/layout/view rendering (for example inside <script env="server">). Standalone JSON API endpoints do not render an HTML <head>.

MemberDescription
meta.titleRead or write the page title
meta.setMeta(name, content)Set <meta name="..." content="..."> (name must be a non-null string)
meta.setMeta(name, httpEquiv, charSet, content)Set a meta tag with http-equiv / charset (name must be a non-null string)
meta.getMeta(name)Read an existing meta entry (MetaItem when present, null when missing)
meta.setCustomerHeader(headerString)Append a custom head HTML fragment
html
<!-- Inside a Page or Layout server script -->
<script env="server">
  k.response.meta.title = "Order detail"
  k.response.meta.setMeta("description", "Order detail page")
  k.response.meta.setMeta("charset", "Content-Type", "utf-8", "text/html")
  k.response.meta.setCustomerHeader('<meta property="og:title" content="Order detail">')

  const descMeta = k.response.meta.getMeta("description")
  const descContent = descMeta ? descMeta.content : ""
</script>

Reading MetaItem fields

MetaItem stores name, content, httpEquiv, charSet, and property as public fields on the runtime object. Read those properties directly in script rather than calling JSON.stringify(k.response.meta.getMeta(...)), which serializes as {}.

Methods ​

write() ​

Write content to the response body. Primitive values are emitted directly, while objects are serialized to JSON.

ParameterTypeRequiredDescription
valueanyYesContent to write to the response body

Returns: void.

js
k.api.get(() => {
  k.response.write("hello world")
  k.response.write(1234)

  const obj = { name: "kooboo" }
  k.response.write(obj)
})
// Output: hello world1234{"name":"kooboo"}

json() ​

Serialize a value to JSON and write it to the response body. This method does not automatically change the Content-Type header (text/html; charset=UTF-8 by default); call k.response.setHeader("Content-Type", "application/json; charset=utf-8") when clients expect application/json.

ParameterTypeRequiredDescription
valueanyYesValue to serialize as JSON

Returns: void.

js
k.api.get(() => {
  k.response.setHeader("Content-Type", "application/json; charset=utf-8")
  k.response.json({
    success: true,
    data: { id: 1, name: "test" }
  })
})
// Output: {"success":true,"data":{"id":1,"name":"test"}}

executeView() ​

Render a View resource by name or ID and write its HTML directly into the current response output. Commonly used in Layouts, Pages, or server scripts to emit a View dynamically.

ParameterTypeRequiredDescription
ViewNameOrIdstringYesView resource name or GUID

Returns: void.

html
<!-- Inside a Page or Layout server script -->
<script env="server">
  k.response.executeView("test")
</script>

renderViewAsString() ​

Render a View resource by name or ID and return its rendered HTML as a string without immediately writing to the response.

ParameterTypeRequiredDescription
ViewNameOrIdstringYesView resource name or GUID

Returns: string | null, rendered HTML output, or null if the view does not exist.

js
k.api.get("preview", () => {
  const html = k.response.renderViewAsString("test")
  if (html === null) {
    k.response.statusCode(404)
    return { error: "View not found" }
  }
  return { html }
})

file() ​

Stream a file from the site's k.file (FileIO) disk folder as a download response.

ParameterTypeRequiredDescription
pathstringYesRelative file path inside the k.file disk folder (not k.site.files)
contentTypestringNoResponse Content-Type; inferred from the file extension when omitted
fileNamestringNoDownload filename; Content-Disposition: attachment;filename=... is always added and defaults to the basename of path

Returns: void. Throws "File not found" if the file does not exist; check k.file.exists(path) beforehand.

js
// Example API URL: /api/files/{action}

// Basic usage (infers MIME type and uses logo.png in Content-Disposition: attachment)
k.api.get("logo", () => {
  const path = "images/logo.png"
  if (!k.file.exists(path)) {
    k.response.statusCode(404)
    return { error: "File not found" }
  }
  k.response.file(path)
})

// Specify Content-Type and custom download filename
k.api.get("report", () => {
  const path = "docs/report.pdf"
  if (!k.file.exists(path)) {
    k.response.statusCode(404)
    return { error: "File not found" }
  }
  k.response.file(path, "application/pdf", "report-2024.pdf")
})

binary() ​

Send a binary byte-array response. When filename is provided, Kooboo sets Content-Disposition: attachment;filename=....

ParameterTypeRequiredDescription
contentTypestringYesResponse Content-Type
bytesnumber[]YesBinary byte array
filenamestringNoDownload filename

Returns: void.

js
k.api.get("download-txt", () => {
  const bytes = [75, 111, 111, 98, 111, 111] // "Kooboo"
  k.response.binary("text/plain", bytes, "hello.txt")
})

statusCode() ​

Set the HTTP status code.

ParameterTypeRequiredDescription
codenumberYesHTTP status code

Returns: void.

js
k.api.get(() => {
  k.response.statusCode(404)
  return "Not Found"
})

unauthorized() ​

Set the HTTP status code to 401 (leaves the response body empty unless you write content explicitly).

Parameters: None.

Returns: void.

js
k.api.get(() => {
  k.response.unauthorized()
})
// HTTP status code: 401, empty body

notFound() ​

Set the HTTP status code to 404.

Parameters: None.

Returns: void.

js
k.api.get(() => {
  k.response.notFound()
})

redirect() ​

Redirect to a target URL.

ParameterTypeRequiredDescription
urlstringYesTarget URL
absolutebooleanNoWhether the URL uses an absolute or non-HTTP scheme

Returns: void.

js
// Example API URL: /api/go/{action}

// Relative path
k.api.get("relative", () => {
  k.response.redirect("/login")
})

// Absolute URL
k.api.get("external", () => {
  k.response.redirect("https://example.com")
})

// Custom URI scheme (e.g. WeChat deep link)
k.api.get("wechat", () => {
  k.response.redirect("wechat://kooboo.com", true)
})

setHeader() ​

Set a custom HTTP response header.

ParameterTypeRequiredDescription
keystringYesResponse header name
valuestringYesResponse header value

Returns: void.

js
k.api.get(() => {
  k.response.setHeader("X-Custom-Header", "value")
  k.response.setHeader("Access-Control-Allow-Origin", "*")
  return "ok"
})

execute() ​

Execute another site Page URL or an external http(s):// URL and append its output to the current response.

  • Relative site URLs (such as "/another-page"): resolve and render site Page resources only; k.api / Code routes are not supported (passing an /api/... route finds no Page and silently writes nothing). Use ES import in Module scripts to share logic across APIs.
  • Full http:// / https:// URLs: perform an outbound HTTP GET request via Curl and write the returned body into the current response.
ParameterTypeRequiredDescription
urlstringYesSite Page URL or external http(s):// URL to execute

Returns: void.

js
// Example API URL: /api/exec/{action}

// 1. Relative site URL: renders a Page resource (does not invoke k.api routes)
k.api.get("render-page", () => {
  k.response.execute("/another-page")
  k.response.write("<!-- appended -->")
})

// 2. http(s):// URL: fetches the remote URL via Curl GET and appends its body
k.api.get("proxy", () => {
  k.response.execute("https://example.com/snippet.html")
})

stop() ​

Mark downstream page/template rendering as cancelled (RenderCancelled). It does not abort execution of subsequent JavaScript statements in the same callback (a following return still executes in an API handler; use JS return to exit early).

Parameters: None.

Returns: void.

html
<!-- Stop remaining page template output after emitting a custom response -->
<script env="server">
  k.response.write("custom output")
  k.response.stop()
</script>

Common Usage ​

CORS Cross-Origin Configuration ​

CORS response headers are handled by the platform:

When either is enabled, the platform sets Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials. Note how OPTIONS preflight requests differ:

  • Site-wide enableCORS enabled: Kooboo short-circuits OPTIONS preflight requests, bypassing script body execution and site auth checks before returning CORS headers.
  • Only per-API cors: true enabled (enableCORS off): top-level script statements still execute on OPTIONS requests (though k.api.get/post/put/delete callbacks do not match OPTIONS) before CORS headers are added, and site auth guards are not bypassed automatically.

Call k.response.setHeader when you want to override a specific header; the platform preserves headers you set explicitly:

js
k.api.get(() => {
  k.response.setHeader("Access-Control-Allow-Origin", "https://example.com")
  return { ok: true }
})

File Download ​

js
k.api.get("download", () => {
  const filePath = "exports/data.csv"
  if (!k.file.exists(filePath)) {
    k.response.statusCode(404)
    return { error: "File not found" }
  }
  k.response.file(filePath, "text/csv", "export.csv")
})

TypeScript Definitions ​

ts
interface Response {
  meta: PageMeta;

  write(value: any): void;
  setHeader(key: string, value: string): void;
  redirect(url: string, absolute?: boolean): void;
  json(value: any): void;
  executeView(ViewNameOrId: string): void;
  renderViewAsString(ViewNameOrId: string): string | null;
  binary(contentType: string, bytes: number[]): void;
  binary(contentType: string, bytes: number[], filename?: string): void;
  file(path: string, contentType?: string, fileName?: string): void;
  statusCode(code: number): void;
  unauthorized(): void;
  notFound(): void;
  execute(url: string): void;
  stop(): void;
}

interface PageMeta {
  title: string;
  setMeta(Name: string, content: string): void;
  setMeta(Name: string, HttpEquiv: string, CharSet: string, content: string): void;
  setCustomerHeader(HeaderString: string): void;
  getMeta(Name: string): MetaItem;
}

interface MetaItem {
  name: string;
  content: string;
  httpEquiv: string;
  charSet: string;
  property: string;
}