Skip to content

HTTP Module

The std/http module provides everything you need for HTTP in Chuks: a high-performance server with routing and middleware, typed Request/Response objects, and an asynchronous HTTP client.

// Server + types
import { createServer, Request, Response } from "std/http"
// HTTP client
import { http } from "std/http"
// All exports
import { createServer, Request, Response, http, HttpResponse } from "std/http"
ExportKindDescription
createServerfunctionCreate an HTTP server instance (HttpServer)
RequestdataTypeIncoming request object passed to route handlers
ResponsedataTypeOutgoing response object passed to route handlers
UploadedFiledataTypeUploaded file from multipart/form-data requests
httpHTTPHTTP client instance for outbound requests
HTTPclassHTTP client class
HttpResponsedataTypeResponse returned by HTTP client calls

The Request object is the first argument to every route handler and middleware.

dataType Request {
method: string // HTTP method (GET, POST, etc.)
path: string // Request path (e.g. "/users/123")
body: string // Raw request body
params: map[string]string // Route parameters (e.g. { id: "123" })
query: map[string]string // Query string parameters
headers: map[string]string // Request headers (keys lowercased)
ip: string // Client IP address
originalUrl: string // Full URL path + query string
protocol: string // "http" or "https"
hostname: string // Hostname from Host header (port stripped)
secure: bool // true when protocol is "https"
userAgent: string // User-Agent header value
contentType: string // Content-Type header value
referer: string // Referer header value
cookies: map[string]string // All cookies as key-value pairs
formData: map[string]string // Parsed form fields from multipart requests
files: []UploadedFile // Uploaded files from multipart/form-data
}
PropertyTypeDescription
methodstringHTTP method (GET, POST, etc.)
pathstringRequest path (e.g. “/users/123”)
bodystringRaw request body
paramsmap[string]stringRoute parameters (e.g. { id: "123" })
querymap[string]stringQuery string parameters
headersmap[string]stringRequest headers (keys lowercased)
ipstringClient IP address (e.g. “127.0.0.1”)
originalUrlstringFull URL path + query string (e.g. “/users?page=1”)
protocolstringProtocol string — “http” or “https”
hostnamestringHostname from Host header, port stripped
secureboolShorthand for protocol == "https"
userAgentstringValue of the User-Agent header
contentTypestringValue of the Content-Type header
refererstringValue of the Referer header
cookiesmap[string]stringAll cookies as key-value pairs
formDatamap[string]stringParsed form fields from multipart requests
files[]UploadedFileUploaded files from multipart/form-data requests
MethodReturnDescription
header(name)stringGet a specific header value (case-insensitive)
cookie(name)stringGet a cookie value by name
parseBody(Type?)anyParse JSON body, optionally into a typed dataType
app.post("/api/data", function(req: Request, res: Response) {
const contentType = req.header("Content-Type")
const body = req.body
const search = req.query["q"]
const userId = req.params["id"]
const clientIp = req.ip
const fullUrl = req.originalUrl
res.json('{"received": true}')
})

parseBody() parses the raw JSON body string into a Chuks value. When called with a dataType argument, it returns a typed instance:

dataType CreateUserRequest {
name: string
email: string
}
app.post("/api/users", function(req: Request, res: Response) {
// Untyped — returns a generic map
const data = req.parseBody()
println(data["name"])
// Typed — returns a CreateUserRequest instance
const user = req.parseBody(CreateUserRequest)
println(user.name)
println(user.email)
res.status(201).json('{"created": true}')
})
app.get("/dashboard", function(req: Request, res: Response) {
const sessionId = req.cookie("session_id")
if (sessionId == "") {
res.redirect("/login")
return
}
res.send("Welcome back!")
})

Common header values are available directly on the request:

app.post("/api/data", function(req: Request, res: Response) {
println(req.userAgent) // e.g. "Mozilla/5.0 ..."
println(req.contentType) // e.g. "application/json"
println(req.referer) // e.g. "https://example.com"
// All cookies as a typed map
var cookies: map[string]string = req.cookies
println(cookies["session_id"])
})

When a request is sent as multipart/form-data, Chuks automatically parses form fields into req.formData and uploaded files into req.files.

import { createServer, Request, Response, UploadedFile } from "std/http"
const app = createServer()
app.post("/upload", function(req: Request, res: Response) {
// Access form fields
var name: string = req.formData["name"]
// Access uploaded files
var fileCount: int = req.files.length
if (fileCount > 0) {
var f: UploadedFile = req.files[0]
println(f.fileName) // e.g. "photo.jpg"
println(f.contentType) // e.g. "image/jpeg"
println(f.size) // file size in bytes
println(f.extension) // e.g. ".jpg"
println(f.data) // raw file content
}
res.json('{"uploaded": true}')
})
app.listen(3000)

Represents an uploaded file from a multipart/form-data request.

dataType UploadedFile {
fieldName: string // Form field name (e.g. "avatar")
fileName: string // Original filename (e.g. "photo.jpg")
contentType: string // MIME type (e.g. "image/jpeg")
size: int // File size in bytes
data: string // Raw file content
extension: string // File extension including dot (e.g. ".jpg")
}
PropertyTypeDescription
fieldNamestringForm field name (e.g. “avatar”)
fileNamestringOriginal filename (e.g. “photo.jpg”)
contentTypestringMIME type (e.g. “image/jpeg”)
sizeintFile size in bytes
datastringRaw file content as a string
extensionstringFile extension including dot (e.g. “.jpg”, “.png”)

The Response object is the second argument to every route handler and middleware. All methods are chainable.

dataType Response {
statusCode: int // HTTP status code (default 200)
body: string // Response body
}
MethodReturnDescription
res.status(code: int)ResponseSet the HTTP status code
res.header(key, value)ResponseSet a response header
res.json(body: any)ResponseSend JSON response (sets Content-Type: application/json)
res.send(body: string)ResponseSend plain text response
res.redirect(url, status?)ResponseRedirect to URL (default 302). Sets Location header
res.type(contentType)ResponseSet Content-Type with shorthand (json, html, text, xml, form)
res.cookie(name, value, options?)ResponseSet a cookie. Options: maxAge, httpOnly, secure, sameSite, path, domain
res.clearCookie(name)ResponseClear a cookie (expires it via Max-Age=0)
app.get("/api/user", function(req: Request, res: Response) {
res.status(200)
.header("X-Request-Id", "abc123")
.json('{"name": "Alice"}')
})
app.get("/old-page", function(req: Request, res: Response) {
res.redirect("/new-page") // 302 Found (default)
})
app.get("/moved", function(req: Request, res: Response) {
res.redirect("/permanent-new", 301) // 301 Moved Permanently
})

res.type() supports convenient shorthand aliases:

ShorthandExpands to
jsonapplication/json
htmltext/html
texttext/plain
xmlapplication/xml
formapplication/x-www-form-urlencoded
app.get("/page", function(req: Request, res: Response) {
res.type("html").send("<h1>Hello</h1>")
})
app.post("/login", function(req: Request, res: Response) {
res.cookie("session_id", "abc123", {
"maxAge": 86400,
"httpOnly": true,
"secure": true,
"sameSite": "Strict",
"path": "/"
}).json('{"loggedIn": true}')
})
app.post("/logout", function(req: Request, res: Response) {
res.clearCookie("session_id").json('{"loggedOut": true}')
})

Created by createServer(). All methods are chainable.

MethodSignatureDescription
useuse(handler) → HttpServerRegister a middleware
getget(path, handler) → HttpServerRegister GET route
postpost(path, handler) → HttpServerRegister POST route
putput(path, handler) → HttpServerRegister PUT route
deletedelete(path, handler) → HttpServerRegister DELETE route
patchpatch(path, handler) → HttpServerRegister PATCH route
allall(path, handler) → HttpServerRegister catch-all route
listenlisten(port) → voidStart server on given port
closeclose() → voidGraceful shutdown
import { createServer, Request, Response } from "std/http"
const app = createServer()
app.use(function(req: Request, res: Response, next: any) {
res.header("X-Powered-By", "Chuks")
next()
})
app.get("/", function(req: Request, res: Response) {
res.json('{"status": "ok"}')
})
app.listen(3000)

For the full server guide (routing, middleware patterns, configuration, context integration, and benchmarks), see the HTTP Server guide.


http.get(url: string, headers?: map): Task<HttpResponse>

Section titled “http.get(url: string, headers?: map): Task<HttpResponse>”

Performs an asynchronous GET request. An optional headers map can be passed as the second argument.

const resp = await http.get("https://api.example.com/data")
println(resp.status) // 200
println(resp.body) // Response body string
// With custom headers
const resp2 = await http.get("https://api.example.com/data", {
"Authorization": "Bearer token123"
})

http.post(url: string, body: string, contentType?: string): Task<HttpResponse>

Section titled “http.post(url: string, body: string, contentType?: string): Task<HttpResponse>”

Performs an asynchronous POST request. An optional content type can be passed as the third argument.

const resp = await http.post(
"https://api.example.com/users",
'{"name": "Alice"}'
)
println(resp.status) // 201

http.put(url: string, body: string, contentType?: string): Task<HttpResponse>

Section titled “http.put(url: string, body: string, contentType?: string): Task<HttpResponse>”

Performs an asynchronous PUT request.

const resp = await http.put(
"https://api.example.com/users/1",
'{"name": "Bob"}'
)

http.del(url: string, headers?: map): Task<HttpResponse>

Section titled “http.del(url: string, headers?: map): Task<HttpResponse>”

Performs an asynchronous DELETE request. An optional headers map can be passed as the second argument.

const resp = await http.del("https://api.example.com/users/1")
println(resp.status) // 204

http.patch(url: string, body: string, contentType?: string): Task<HttpResponse>

Section titled “http.patch(url: string, body: string, contentType?: string): Task<HttpResponse>”

Performs an asynchronous PATCH request.

const resp = await http.patch(
"https://api.example.com/users/1",
'{"name": "Charlie"}'
)

http.request(method: string, url: string, body?: string, headers?: map): Task<HttpResponse>

Section titled “http.request(method: string, url: string, body?: string, headers?: map): Task<HttpResponse>”

Performs a custom HTTP request with any method.

const resp = await http.request("OPTIONS", "https://api.example.com/users")

All HTTP functions return a Task<HttpResponse>. Use await to get the response.

dataType HttpResponse {
status: int
body: string
headers: any
}
FieldTypeDescription
statusintHTTP status code (200, 404, etc.)
bodystringResponse body as a string
headersanyResponse headers
FunctionDescription
http.get(url, headers?)HTTP GET request
http.post(url, body, contentType?)HTTP POST request
http.put(url, body, contentType?)HTTP PUT request
http.del(url, headers?)HTTP DELETE request
http.patch(url, body, contentType?)HTTP PATCH request
http.request(method, url, body?, headers?)Custom HTTP request
import { http } from "std/http"
import { json } from "std/json"
async function fetchUser(id: int): any {
const resp = await http.get("https://api.example.com/users/" + id)
if (resp.status == 200) {
return json.parse(resp.body)
}
throw new Error("Failed to fetch user: " + resp.status)
}
const user = await fetchUser(1)
println(user["name"])