5. Runtime APIs
Detailed reference for Titan's built-in runtime APIs, providing high-performance native operations for your actions.
Overview
Titan Planet provides a comprehensive set of runtime APIs exposed via the global t object or through the @titanpl/native utility package. These APIs execute directly in the high-performance Rust core, offering near-native speed for system-level operations.
Environment Variables (t.env)
Titan provides access to your environment variables (defined in your project's .env files) via t.env. This is available both globally and within your actions.
const dbUri = t.env.DB_URI; // Maps to DB_URI in .envInstallation & Import
While t is always available globally, you can also import specific utilities for better type support and clarity:
import { fs, task, db, ws, crypto, response } from "@titanpl/native";
export const myAction = (req) => {
const content = fs.readFile("tanfig.json"); // Uses project root as base
return response.json({ content });
};The Request Object (req)
Every Titan action receives a Request object containing details about the incoming event. This object is stable and serializable across all execution modes.
method: string— HTTP method (e.g.,GET,POST,PUT,DELETE,PATCH).path: string— The request path (e.g.,"/user/42").headers: Record<string, string>— Key-value pairs of request headers (lowercased).params: Record<string, string>— Path parameters (e.g.,idfrom/users/:id).query: Record<string, string>— URL query parameters (e.g.,?page=2).body: any— The parsed request body (automatically parsed for JSON).socketId?: string— Unique ID for WebSocket connections.event?: "open" | "message" | "close"— Type of WebSocket event.
Asynchronous Orchestration (drift)
Titan runs on the synchronous Gravity V8 engine. All asynchronous operations (DB, Fetch, FS) must use the drift() operator to suspend and resume the isolate properly.
// Correct pattern for async calls
export function getUsers(req) {
const conn = drift(t.db.connect(t.env.DATABASE_URL));
const users = drift(conn.query("SELECT * FROM users"));
return { users };
}Note: Titan uses your project root as the base for all file system operations. There is no need for ../app or complex path arithmetic — paths resolve directly relative to where your package.json lives. This is managed by the @titanpl/packet bundler.
API Reference
Core Functions
These global functions are available for general logging, action definition, and asynchronous orchestration.
log(message: any): void— Log information to the Titan system console.fetch(url: string, options?: object): Promise<any>— Native, high-performance HTTP client.defineAction(handler: Function): Function— Utility for defining Titan actions with built-in type safety.drift(operation: Promise<any>): any— Wraps asynchronous operations to ensure they are handled correctly by Titan's execution engine.
fs (File System)
Asynchronous file system operations. All methods return a Promise and must be used with drift().
fs.readFile(path: string): Promise<string>— Read file content as UTF-8 string.fs.readFileBase64(path: string): Promise<string>— Read file content as a Base64 string.fs.readFileBinary(path: string): Promise<Uint8Array>— Read file content as raw binary bytes.fs.writeFile(path: string, content: string): Promise<void>— Write string content to file.fs.writeFileBinary(path: string, bytes: Uint8Array): Promise<void>— Write binary content to file.fs.exists(path: string): Promise<boolean>— Check if a path exists.fs.mkdir(path: string): Promise<void>— Create a directory (recursive).fs.remove(path: string): Promise<void>— Remove file or directory.fs.readdir(path: string): Promise<string[]>— List directory contents.fs.stat(path: string): Promise<object>— Get metadata:{ size, isFile, isDir, modified }.fs.isDirectory(path: string): Promise<boolean>— Check if path is a directory.fs.isFile(path: string): Promise<boolean>— Check if path is a regular file.
path (Path Manipulation)
Utilities for handling file paths.
path.join(...parts: string[]): string— Join path segments using platform-specific separators.path.resolve(...parts: string[]): string— Resolve path to an absolute path.path.dirname(path: string): string— Get the directory name of a path.path.basename(path: string): string— Get the base name (filename) of a path.path.extname(path: string): string— Get the extension of a path (including the dot).
crypto (Cryptography)
Secure cryptographic utilities.
crypto.hash(algo: string, data: string): string— Hash data (e.g.,sha256,sha512).crypto.randomBytes(size: number): string— Generate random bytes as a hex string.crypto.uuid(): string— Generate a UUID v4.crypto.encrypt(algorithm: string, key: string, plaintext: string): string— Encrypt text using native Rust implementations.crypto.decrypt(algorithm: string, key: string, ciphertext: string): string— Decrypt text.crypto.hashKeyed(algo: string, key: string, message: string): string— Keyed-hash (HMAC) support.crypto.compare(hash: string, target: string): boolean— Securely compare two strings in constant time.
jwt (JSON Web Tokens)
Native utilities for signing and verifying tokens. These methods are synchronous.
jwt.sign(payload: object, secret: string, options?: { expiresIn?: string | number }): string— Sign a JWT.jwt.verify(token: string, secret: string): any— Verify and decode a JWT. Throws on failure.
password (Password Hashing)
Secure password management powered by bcrypt (Rust implementation).
password.hash(password: string): Promise<string>— Hash a plain-text password.password.verify(password: string, hash: string): Promise<boolean>— Verify a password against a hash.
buffer (Buffer Utilities)
Utilities for binary and data encoding.
buffer.fromBase64(str: string): Uint8Array— Decode Base64 string to bytes.buffer.toBase64(bytes: Uint8Array | string): string— Encode bytes or string to Base64.
Serialization (V8 Native)
Binary-serializes or deserializes JavaScript values (including Map, Set, Date, and TypedArrays) using V8's fast internal format.
serialize(value: any): Uint8Array— Binary-serializes a value. (Alias:serialise)deserialize(buffer: Uint8Array): any— Deserializes a Uint8Array back into its original JS value. (Alias:deserialise)
os (Operating System)
Retrieve system-level information.
os.platform(): string— OS platform (e.g.,linux,windows,darwin).os.cpus(): number— Number of logical CPU cores.os.totalMemory(): number— Total system memory in bytes.os.freeMemory(): number— Free system memory in bytes.os.tmpdir(): string— Path to the system temporary directory.
net (Network)
Basic network utilities.
net.resolveDNS(hostname: string): string[]— Resolve a hostname to IP addresses.net.ip(): string— Get the local system IP address.
db (Database)
Native interface for SQL databases (PostgreSQL). Async methods require drift().
db.connect(url: string, options?: ConnectionOptions): Promise<DbConnection>— Establish a connection with optional pooling settings.db.query(sql: string, params?: any[], options?: QueryOptions): Promise<any[]>— Run a query on the default connection.
ConnectionOptions:
max: number— Maximum number of connections in the pool (default: 16).pool_timeout: number— Timeout in milliseconds for acquiring a connection (default: 5000).
QueryOptions:
timeout: number— Timeout in milliseconds for query execution (default: 10000).
DbConnection interface:
query(sql: string, params?: any[], options?: QueryOptions): Promise<any[]>— Execute SQL with positional placeholders ($1,$2).
task (Managed Background Tasks)
Offload long-running I/O, heavy computations, or sequential workflows to background workers with zero infrastructure overhead.
task.spawn(key: string, actionName: string, payload?: any, options?: TaskOptions): void— Dispatch a one-off background job. Supports built-in deduplication by key, instant execution, and cooldown-based rate-limiting.task.enqueue(queueKey: string, actionName: string, payload?: any, options?: { timeout?: number }): void— Native FIFO Queues. Jobs in the same queue are executed strictly one-after-another.task.status(key: string): TaskStatus | null— Query the real-time state of any task (pending,running,done, orfailed), including active rate-limiting cooldown info.task.stop(key: string): void— Force-stops a task and removes its tracking entry.task.clear(queueKey: string): void— Removes all pending jobs from a specific queue.
TaskOptions:
dedupe: boolean— If true, skip if a task with this key is already active (default: true).timeout: number— Kill task after these many milliseconds (default: 30000).delay: number— Active rate-limiting cooldown window in milliseconds. Tasks spawn and execute immediately (no blocking/sleeping delays), but subsequent spawns for the same key will be rejected if triggered within this cooldown window.
TaskStatus:
state: "pending" | "running" | "done" | "failed"startedAt: number— Unix timestamp (ms) when the task was started.duration?: number— Execution duration in milliseconds.delayRemaining?: number— Remaining milliseconds of the active rate-limiting cooldown window.error?: string— Error message if the task failed.
Implementation Example
import { task, response } from "@titanpl/native";
export default defineAction((req) => {
// Send welcome email in background
task.spawn(`welcome:${req.body.email}`, "send-welcome", {
to: req.body.email,
name: req.body.name
});
return response.json({ status: "Account created, email sending in background..." });
})import { defineTask, response, log, shareContext, fetch } from "@titanpl/native";
export default defineTask((req) => {
const { userId = "anon", page = 1, label = "unnamed" } = req.body || {};
log(`[task-worker] Running — userId: ${userId}, page: ${page}, label: ${label}`);
// Simulate work: fetch a public API
const result = drift(fetch(`https://jsonplaceholder.typicode.com/posts/${page}`));
const post = JSON.parse(result.body);
// Store result in shareContext so the main request can read it
const cacheKey = `task-result:${userId}:${page}`;
shareContext.set(cacheKey, {
userId,
page,
label,
fetchedAt: Date.now(),
post
});
log(`[task-worker] Done — stored result at shareContext["${cacheKey}"]`);
return response.json({ ok: true, cacheKey });
});// Sequential Queue (FIFO)
// Jobs in the same queue key run one after another, never in parallel.
export function syncData(req) {
const { userId } = req.body;
task.enqueue(`sync:${userId}`, "fetch-page", { page: 1 });
task.enqueue(`sync:${userId}`, "fetch-page", { page: 2 });
return { enqueued: true };
}types (Type Casting API)
The types API provides helper functions to explicitly mark your JavaScript values as specific database types. This ensures deterministic OID binding in prepared statements.
| Function | Purpose | Example |
|---|---|---|
STRING(val) | t.types.STRING("name") | Casts value to a standard SQL string. |
NUMBER(val) | t.types.NUMBER(42.5) | Casts value to a double precision number. |
BOOLEAN(val) | t.types.BOOLEAN(true) | Casts value to a SQL boolean. |
UUID(val) | t.types.UUID(req.body.id) | Required for UUID columns. |
TIMESTAMP(val) | t.types.TIMESTAMP(new Date()) | Casts to a timestamp without time zone. |
TIMESTAMPTZ(val) | t.types.TIMESTAMPTZ(date) | Casts to a timestamp with time zone. |
DATE(val) | t.types.DATE("2024-01-01") | Casts to a standard SQL date. |
JSON(val) | t.types.JSON({ foo: "bar" }) | Required for JSON and JSONB columns. |
VARCHAR(val) | t.types.VARCHAR("short") | Casts to a varchar string. |
CHAR(val) | t.types.CHAR("A") | Casts to a fixed-length char. |
TEXT(val) | t.types.TEXT("long text...") | Casts to a text column. |
INT(val) | t.types.INT(100) | Casts to a 32-bit integer (int4). |
BIGINT(val) | t.types.BIGINT("9007199") | Casts to a 64-bit integer (int8). |
FLOAT(val) | t.types.FLOAT(1.23) | Casts to a single precision float. |
Implementation Example
import { db, types, drift } from "@titanpl/native";
export const createUser = (req) => {
const { id, profile, joinedAt } = req.body;
const conn = drift(db.connect(process.env.DATABASE_URL));
drift(conn.query(
"INSERT INTO users (id, profile_data, joined_at) VALUES ($1, $2, $3)",
[
types.UUID(id),
types.JSON(profile),
types.TIMESTAMP(joinedAt)
]
));
return { success: true };
};ws (WebSockets)
Real-time messaging utilities for TitanPl WebSocket actions.
ws.send(socketId: string, message: string): void— Send a message to a specific WebSocket connection.ws.broadcast(message: string): void— Broadcast a message to all connected clients.
Example:
import { ws } from "@titanpl/native";
export default function chat(req) {
if (req.event === "open") {
ws.send(req.socketId, "Welcome!");
ws.broadcast("Someone joined.");
}
}proc (Process Management)
Manage and query system processes.
proc.pid(): number— Get the Process ID of the current TitanPl engine.proc.info(): object— Get basic info about the current process.proc.run(command: string, args?: string[], cwd?: string): object— Spawn a background process.proc.kill(pid: number): boolean— Terminate a process by PID.proc.list(): object[]— List all running system processes with CPU and memory usage.proc.memory(): object— Get the detailed memory usage of the process (rss, heapTotal, heapUsed, etc.).
Example for proc.memory:
const mem = t.proc.memory();
t.log(`RSS: ${(mem.rss / 1024 / 1024).toFixed(2)} MB`);time (Time Utilities)
time.sleep(ms: number): Promise<void>— Pause execution. Requiresdrift().time.now(): number— Returns a high-resolution millisecond timestamp.time.timestamp(): string— Returns the current time as an ISO 8601 string (e.g.,"2026-01-15T12:30:45.123Z").
ls (Persistent Local Storage) [DEPRECATED]
t.ls is deprecated. For high-performance, RAM-based key-value storage with near-zero latency, use t.shareContext.
High-performance key-value storage persisted to disk.
ls.get(key: string): string|null— Retrieve a string value.ls.set(key: string, value: string): void— Persist a string value.ls.remove(key: string): void— Delete a key.ls.clear(): void— Clear all stored data.ls.keys(): string[]— List all stored keys.ls.setObject(key: string, value: any): void— Store a complex JS object using native V8 serialization.ls.getObject(key: string): any— Retrieve and restore a complex JS object.ls.serialize(value: any): Uint8Array— Native V8 serialization. (Prefer using the globalserializeinstead).ls.deserialize(bytes: Uint8Array): any— Native V8 deserialization. (Prefer using the globaldeserializeinstead).
session (Session Management)
session.get(sid: string, key: string): string|null— Get session data.session.set(sid: string, key: string, value: string): void— Set session data.session.delete(sid: string, key: string): void— Delete session data.session.clear(sid: string): void— Clear an entire session.
cookies (HTTP Cookies)
cookies.get(req: object, name: string): string|null— Extract cookie value from request.cookies.set(res: object, name: string, value: string, options?: object): void— AttachSet-Cookieto response.
shareContext (Memory Cache / Shared State)
High-performance, RAM-based key-value storage. Use this as a Redis-like cache for high-speed data access and sharing state between different isolates/threads.
shareContext.get(key: string): any— Retrieve stored context from memory.shareContext.set(key: string, value: any): void— Set context value.shareContext.delete(key: string): void— Delete a context key.shareContext.keys(): string[]— List all stored keys.shareContext.broadcast(event: string, payload: any): void— Broadcast an event.
url (URL Utilities)
url.parse(str: string): any— Parse a URL string into its component parts.url.format(urlObj: object): string— Format a URL object back into a URL string.new url.SearchParams(init?: string)— Construct query parameters.
Example for url.format:
const url = t.url.format({
protocol: "https:",
hostname: "api.example.com",
pathname: "/users",
search: "?active=true"
});
// → "https://api.example.com/users?active=true"response (HTTP Response Builder)
Helper for constructing standardized Titan responses.
response.text(content: string, options?: object): object— Create a plain text response.response.json(data: any, options?: object): object— Create a JSON response.response.html(content: string, options?: object): object— Create an HTML response.response.redirect(url: string, status?: number): object— Create a redirect response.response.binary(bytes: Uint8Array, options?: object): object— Send a binary response using raw bytes (e.g., images, ZIPs, PDFs).response.empty(status?: number): object— Create an empty response (default: 204 No Content).
📦 Node.js Compatibility
Titan Planet provides a comprehensive compatibility layer that maps standard Node.js core APIs (like fs, path, and crypto) directly to our high-performance Rust core.
👉 Explore Node.js Compatibility & @titanpl/node — Stop fighting with shims and start building with the tools you already know.
4. CLI Reference
The Titan CLI is the central toolchain for building, testing, compiling, and managing Titan Planet applications and extensions. It powers the entire Orbit + Gravity workflow from local development to production deployment.
6. Environment Variables
Configure secrets and environment-specific values using environment variables.