API Docs

An HTTP server instance created by hs.httpserver.create().

Configure with chainable setter methods, then call start() to begin accepting connections. The server supports synchronous and async (Promise-returning) request callbacks, optional static file serving, HTTP Basic authentication, Bonjour advertisement, and TLS via PKCS#12.

Do not instantiate HSHTTPServer directly — use hs.httpserver.create().

Properties

identifier

string

A unique identifier for this server instance (UUID string).

Methods

setPort(port) -> HSHTTPServer

Set the TCP port to listen on. Must be called before start().

Pass 0 to let the OS assign an available port (use getPort() after start() to discover it).

setPort(port) -> HSHTTPServer
Name Type Description
port number TCP port number (0–65535).
HSHTTPServer
This server, for chaining.
server.setPort(8080)

setInterface(iface) -> HSHTTPServer

Set the network interface to listen on.

Pass null to listen on all interfaces (the default). Pass "localhost" or "loopback" to restrict to the loopback interface only.

setInterface(iface) -> HSHTTPServer
Name Type Description
iface string Interface name or IP address string, or null for all interfaces.
HSHTTPServer
This server, for chaining.
server.setInterface("localhost")  // loopback only
server.setInterface(null)         // all interfaces

setPassword(password) -> HSHTTPServer

Set a password required for Basic authentication.

When set, every request must supply an Authorization: Basic header with any username and the configured password. Pass null to disable authentication.

setPassword(password) -> HSHTTPServer
Name Type Description
password string The required password, or null to remove authentication.
HSHTTPServer
This server, for chaining.
server.setPassword("s3cr3t")

setMaxBodySize(size) -> HSHTTPServer

Set the maximum allowed incoming request body size in bytes.

Requests with a body exceeding this limit receive a 413 response. Defaults to 10 MB.

setMaxBodySize(size) -> HSHTTPServer
Name Type Description
size number Maximum body size in bytes.
HSHTTPServer
This server, for chaining.
server.setMaxBodySize(1024 * 1024)  // 1 MB

setName(name) -> HSHTTPServer

Set the Bonjour service name advertised on the local network.

Only used when Bonjour is enabled via setBonjour(true).

setName(name) -> HSHTTPServer
Name Type Description
name string The Bonjour service name.
HSHTTPServer
This server, for chaining.
server.setName("My Hammerspoon Server")

setBonjour(enable) -> HSHTTPServer

Enable or disable Bonjour advertisement of this server on the local network.

setBonjour(enable) -> HSHTTPServer
Name Type Description
enable boolean true to advertise via Bonjour, false to disable (default).
HSHTTPServer
This server, for chaining.
server.setBonjour(true)

setCallback(callback) -> HSHTTPServer

Set the request handler callback.

The callback receives (method, path, headers, body, query) and must return either:

  • A plain object {body, status, headers} for a synchronous response.
  • A Promise resolving to {body, status, headers} for an async response.

path never includes the query string. query is an object mapping each query parameter name to its percent-decoded value (+ is decoded as a space). A parameter that appears more than once maps to an array of its values, in order. A parameter with no = maps to an empty string. If the request has no query string, query is an empty object.

If the callback returns null or undefined, the server falls through to static file serving (if a document root is set), or responds with 404.

setCallback(callback) -> HSHTTPServer
Name Type Description
callback function | null The request handler, or null to clear.
HSHTTPServer
This server, for chaining.
server.setCallback((method, path, headers, body, query) => {
    // GET /hello?name=World
    return {body: `<h1>Hello, ${query.name}!</h1>`, status: 200, headers: {"Content-Type": "text/html"}}
})

setDocumentRoot(path) -> HSHTTPServer

Set the filesystem path to serve static files from.

When a document root is set, requests not handled by the callback are served as static files from this directory. Pass null to disable static file serving.

setDocumentRoot(path) -> HSHTTPServer
Name Type Description
path string Absolute path to a directory, or null to disable.
HSHTTPServer
This server, for chaining.
server.setDocumentRoot("/Users/me/Sites")

setDirectoryIndex(files) -> HSHTTPServer

Set the list of index filenames checked when a directory is requested.

Defaults to ["index.html", "index.htm"]. Files are checked in order.

setDirectoryIndex(files) -> HSHTTPServer
Name Type Description
files string[] Array of filename strings.
HSHTTPServer
This server, for chaining.
server.setDirectoryIndex(["index.html", "default.html"])

setAllowDirectoryListing(allow) -> HSHTTPServer

Enable or disable directory listing for requests that map to a directory with no index file.

When disabled (the default), directory requests without an index file return 403.

setAllowDirectoryListing(allow) -> HSHTTPServer
Name Type Description
allow boolean true to serve directory listings, false to return 403 (default).
HSHTTPServer
This server, for chaining.
server.setAllowDirectoryListing(true)

setTLSFromPKCS12(path, password) -> HSHTTPServer

Configure TLS using a PKCS#12 (.p12) identity file.

When TLS is configured, the server accepts HTTPS connections. The .p12 file must contain both the certificate and the private key.

setTLSFromPKCS12(path, password) -> HSHTTPServer
Name Type Description
path string Absolute path to the .p12 file.
password string The password protecting the .p12 file.
HSHTTPServer
This server, for chaining.
server.setTLSFromPKCS12("/path/to/identity.p12", "passphrase").start()

start() -> HSHTTPServer

Start the server and begin accepting connections.

The server must be configured before calling start(). To restart the server with new settings, call stop() followed by start().

start() -> HSHTTPServer
HSHTTPServer
This server, for chaining.
A running server, and its callbacks, stay alive until it's stopped, even if you don't keep a reference to it
const server = hs.httpserver.create().setPort(8080).setCallback(handler).start()

stop() -> HSHTTPServer

Stop the server and close all connections.

stop() -> HSHTTPServer
HSHTTPServer
This server, for chaining.
server.stop()

destroy() -> None

Destroy this server, releasing all resources.

After calling destroy(), the server object should not be used.

destroy() -> None
None
server.destroy()

getPort() -> number

Get the TCP port the server is currently listening on.

Returns 0 if the server is not running.

getPort() -> number
number
The TCP port number.
console.log("Listening on port " + server.getPort())

getName() -> string

Get the configured Bonjour service name.

getName() -> string
string
The Bonjour service name.
console.log(server.getName())

getInterface() -> string

Get the configured network interface, or null if listening on all interfaces.

getInterface() -> string
string
The interface name or IP address string, or null.
console.log(server.getInterface())

setWebSocketCallback(path, callback) -> HSHTTPServer

Register a WebSocket handler for a URL path.

When a client connects and performs a WebSocket upgrade handshake on path, the callback is invoked with three arguments: event (string), connection (HSWebSocketConnection), and message (string).

Events:

  • "connected" — a new client connected; message is "".
  • "message" — the client sent a text frame; message contains the text.
  • "closed" — the client disconnected; message is "".

Pass null to remove the WebSocket handler for the path.

setWebSocketCallback(path, callback) -> HSHTTPServer
Name Type Description
path string The URL path to handle WebSocket connections on (e.g. "/ws").
callback function | null The event handler, or null to remove.
HSHTTPServer
This server, for chaining.
server.setWebSocketCallback('/ws', (event, conn, msg) => {
    if (event === 'connected') conn.send('Welcome!')
    else if (event === 'message') conn.send('Echo: ' + msg)
})