Edit

serve()

Environment: server.

Low-level function that turns a telefunction HTTP request into an HTTP response. It's a pure function: stateless and side-effect-free. It runs in any runtime, with no adapter required.

Most apps should use new Telefunc() instead — it's the standard server integration.

new Telefunc() has full-fledged support for Telefunc Stream, whereas serve() doesn't support the following:

  • WebSocket

    You can still use Telefunc Stream, but not over the WebSocket transport — Telefunc falls back to another transport instead.

  • Channels on Cloudflare

    You won't be able to use channels on Cloudflare at all. (Because channels need Durable Objects.)

Web Request

You can pass the web-standard Request object:

// Environment: server
 
import { serve } from 'telefunc'
 
const httpResponse = await serve({
  // `request` being a `Request` instance
  request
})
 
// Build an HTTP response using the following:
httpResponse.getReadableWebStream() // or httpResponse.getBody()
httpResponse.statusCode
httpResponse.headers

You can convert the result to a Response:

const response = new Response(httpResponse.getReadableWebStream(), {
  status: httpResponse.statusCode,
  headers: httpResponse.headers
})

Node.js req

You can pass the Node.js req readable stream (e.g. when using Express):

// Environment: server
 
import { serve } from 'telefunc'
 
const httpResponse = await serve({
  url: req.originalUrl,
  method: req.method,
  readable: req,
  headers: req.headers
})
 
// Build an HTTP response using the following:
httpResponse.getReadableWebStream() // or httpResponse.getBody()
httpResponse.statusCode
httpResponse.headers

With context

Pass a context object to make request-scoped data available inside telefunctions via getContext():

const httpResponse = await serve({
  // ...
  context: {
    user: await getUser(request)
  }
})

The context parameter is optional — only needed if you use getContext(). See API > getContext() > Provide.

Response object

httpResponse contains everything needed to send the response:

PropertyTypeDescription
statusCode200 | 400 | 403 | 422 | 500HTTP status code
headers[string, string][]Response headers
getReadableWebStream()ReadableStreamWeb-standard stream (Hono, Cloudflare, Deno, etc.)
pipe(writable)Promise<void>Pipe to Node.js writable (Express, Fastify)
getBody()Promise<string>Full body as string (awaits streaming if needed)
errunknownThe error thrown by your telefunction, if any (otherwise undefined) — see Guides > Error handling

See also