HeliumTS is under active development and may have bugs or breaking changes. Report issues on GitHub.

Context API

Every RPC method and HTTP handler in Helium receives a HeliumContext object as the second parameter. This context provides access to request metadata, including the client IP, fresh request headers, and cancellation signal.

Context Structure

1interface HeliumContext {
2 signal: AbortSignal; // Cancellation for this request and upstream work.
3 req: {
4 ip: string; // Client IP (respects trustProxyDepth config)
5 headers: http.IncomingHttpHeaders; // Request headers
6 url?: string; // Request URL
7 method?: string; // HTTP method
8 raw: http.IncomingMessage; // Raw Node.js request object
9 };
10 [key: string]: unknown; // Custom properties from middleware
11}

Usage in RPC Methods

1import { defineMethod } from "heliumts/server";
2
3export const getClientInfo = defineMethod(async (args, ctx) => {
4 // Access client IP (extracted based on trustProxyDepth configuration)
5 console.log("Client IP:", ctx.req.ip);
6
7 // Access request headers
8 const userAgent = ctx.req.headers["user-agent"];
9 const acceptLanguage = ctx.req.headers["accept-language"];
10
11 // Access the current HTTP RPC request details
12 console.log("Request URL:", ctx.req.url);
13
14 return {
15 ip: ctx.req.ip,
16 userAgent,
17 language: acceptLanguage,
18 };
19});

Usage in HTTP Handlers

1import { defineHTTPRequest } from "heliumts/server";
2
3export const apiEndpoint = defineHTTPRequest("POST", "/api/data", async (req, ctx) => {
4 // Access client IP
5 console.log("Client IP:", ctx.req.ip);
6
7 // Access request headers
8 const authorization = ctx.req.headers["authorization"];
9
10 // Check if request is from a specific IP range
11 if (ctx.req.ip.startsWith("10.0.")) {
12 return { error: "Internal network not allowed" };
13 }
14
15 return { success: true };
16});

Request cancellation

Pass ctx.signal to upstream fetches or provider adapters. The signal is aborted when the client cancels or disconnects. Each RPC call receives the current HTTP request metadata, including updated session cookies; do not cache authentication based on a previous connection.

Custom Context Properties

Middleware can add custom properties to the context:

1import { middleware } from "heliumts/server";
2
3export const authMiddleware = middleware(async (context, next) => {
4 // Add custom property
5 context.ctx.user = await getUserFromToken(context.ctx.req.headers["authorization"]);
6
7 await next();
8});