Skip to content

Platform & Runtime Hosts ​

Effect's platform layer separates service interfaces (in the core effect package, runtime-agnostic) from concrete implementations (provided as a Layer from @effect/platform-node, @effect/platform-bun, @effect/platform-deno, or @effect/platform-browser; the experimental @effect/platform-cloudflare hosts Effect Cluster on Durable Objects). Business logic imports only from effect/*; only the entrypoint imports the platform package. Swapping the Layer swaps the runtime.

Official guides: Introduction to Effect Platform (its module table lists a PlatformLogger that this release does not ship — the function is Logger.toFile — and it routes Deno through @effect/platform-node, while Effect also publishes a dedicated @effect/platform-deno). These guides track Effect's main branch rather than this stable release, so where they differ, this page and the tagged source win.

Who owns each of these runtimes, and when it is disposed, is a separate question from which Layer implements a service: see Choosing a host below and Owning Lifetimes — Startup, Readiness, and Shutdown.

FileSystem ​

effect/FileSystem — unstable

Service interface for filesystem operations: read, write, stat, copy, move, delete, make directories, create temp paths, stream bytes, watch for changes. Discrete operations return an Effect failing with PlatformError (BadArgument or SystemError carrying the OS reason); stream and watch expose that failure through a Stream. PlatformError.isPlatformError(error) is a type guard for narrowing an unknown caught value — useful at a boundary that re-throws or logs errors from several sources.

Mental model: typed composable wrapper over node:fs/promises, working identically on Bun. Business modules import from effect/FileSystem; the entrypoint imports NodeFileSystem.layer. Use FileSystem.layerNoop to stub in tests.

Common methods: readFileString / writeFileString (text), readFile / writeFile (Uint8Array), exists, stat, makeDirectory, copy, remove, stream (lazy byte Stream, configurable chunk size), and glob(pattern, { root, exclude, dot }) (it reads subdirectories concurrently, in at most 16 forked fibers per call, and returns results in a stable order). watch(path) observes direct children by default; pass { recursive: true } for subdirectories. Scoped helpers makeTempDirectoryScoped and makeTempFileScoped auto-clean on scope close. An opened File is the public handle type; its seek(offset, from) takes and returns a plain bigint position and rejects a negative result with BadArgument, leaving the cursor unchanged (there is no public FileDescriptor type).

The service covers the whole node:fs surface, so reaching for raw node:fs costs typed errors and testability without buying an operation:

GroupOperations
Whole-file I/OreadFile, readFileString, writeFile, writeFileString (both writes take flag and mode)
Streams and handlesstream (lazy bytes), sink (a byte Sink; opens with flag "w" unless you pass one, so use { flag: "a" } to append), open (a scoped File: read, readAlloc, write, writeAll, seek, truncate, sync, stat)
Directories and treesmakeDirectory (recursive), readDirectory (recursive), readDirectoryEntries (names with a File.Type), glob, copy (like cp -r), rename, remove (recursive, force)
Single files and linkscopyFile, truncate, link, symlink, readLink, realPath
Metadata and permissionsexists, access (readable, writable), stat, lstat (does not follow a final symlink), chmod, chown, utimes
Temporary pathsmakeTempDirectory, makeTempFile, and the …Scoped variants that delete on scope close
Change notificationwatch

Sizes are ByteSize values. File.Info.size is a stable ByteSize.ByteSize — an exact non-negative bigint brand — so compare it with ByteSize.isGreaterThan and friends rather than with >; there is no separate FileSystem.Size brand or KiB / MiB / GiB / TiB / PiB family on FileSystem. stream's offset and bytesToRead accept any ByteSize.Input; chunkSize and truncate's length are plain numbers. The 64-bit stat metadata uses exact arithmetic: dev is bigint, while ino, rdev, and blocks use Option<bigint>; unavailable optional metadata remains Option.none(). The same exact-arithmetic treatment reaches HTTP file responses: HttpPlatform clamps a requested range to the file's size, so Content-Length always matches the bytes actually sent.

Self-contained source · Type-checked

ts
import { ByteSize, FileSystem } from "effect"
import { NodeFileSystem } from "@effect/platform-node"
import { Effect, Layer, Stream } from "effect"

// Read a comp-bands CSV and stream large files in chunks
const loadCompBands = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem

  // Load the comp-bands definition for this merit cycle
  const csv = yield* fs.readFileString("./data/comp_bands.csv")
  const bands = csv.split("\n").slice(1).map((row) => {
    const [level, min, mid, max] = row.split(",")
    return { level, min: Number(min), mid: Number(mid), max: Number(max) }
  })

  // Write a lock file so a second process knows the import is running
  const lockExists = yield* fs.exists("./data/.import.lock")
  if (!lockExists) {
    yield* fs.writeFileString("./data/.import.lock", `started:${new Date().toISOString()}`)
  }

  // Stat the full employee dump — stream it if it's large
  const info = yield* fs.stat("./data/employees.bin")
  if (ByteSize.isGreaterThan(info.size, ByteSize.mebibytes(100))) {
    yield* Effect.log(`large employee dump (${ByteSize.format(info.size, { system: "binary" })}), streaming instead`)
    const bytes = fs.stream("./data/employees.bin", { chunkSize: 64 * 1024 })
    yield* bytes.pipe(Stream.runDrain)
  }

  // Scoped temp file for an in-progress export — deleted automatically
  const tmp = yield* fs.makeTempFileScoped({ prefix: "merit-export-" })
  yield* fs.writeFileString(tmp, JSON.stringify(bands))
  yield* Effect.log(`staged comp bands at: ${tmp}`)

  return bands
})

// Entrypoint wires in the Node implementation
const program = loadCompBands.pipe(
  Effect.provide(NodeFileSystem.layer),
  // ... NodeRuntime.runMain
)

fs.glob(pattern, options) is one shared implementation on Node, Bun, and Deno, using the Glob syntax. Results are /-separated paths relative to root (default: the working directory), or absolute when the pattern is absolute, visited depth-first with each directory sorted by name. Wildcards skip dotfiles unless the segment starts with . or dot: true; ** does not descend through directory symlinks; an exclude match drops the path and prunes the directory so it is never read. A missing path yields [], an unreadable directory reached through a wildcard is skipped, and a read failure at root or at a leading literal directory fails with PlatformError. Patterns use / and backslash escapes on every host, and extglobs are not expanded.

Self-contained source · Type-checked

ts
import { Effect, FileSystem } from "effect"

// Every TypeScript source under ./src, skipping generated code.
export const sources = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem
  return yield* fs.glob("**/*.{ts,tsx}", { root: "src", exclude: ["generated/**"] })
})

Migration: a custom FileSystem passed to FileSystem.make must now supply lstat and readDirectoryEntries (mapping readDirectory names to { name, type: "Unknown" } is acceptable; glob then falls back to stat). make derives glob and no longer accepts one, so override it afterwards with FileSystem.of({ ...fs, glob: customGlob }). Wrappers that rewrite directory listings must change both readDirectory and readDirectoryEntries.

fs.watch(path) returns a Stream<WatchEvent> whose tags are Create, Update, and Remove. Watching is host-dependent and may fail with PlatformError. A caller-provided FileSystem.WatchBackend is honored at the watch call, so provide it around consumption rather than assuming the backend was captured when the filesystem layer was built. open supports noFollow, and handle reads accept explicit positions without advancing the implicit cursor.

When to use: any filesystem I/O in an Effect program. Use FileSystem.layerNoop to stub in unit tests.

Official guide: FileSystem.

Testing without a disk ​

FileSystem.layerNoop(partial) builds a complete service from only the methods the code under test calls (FileSystem.makeNoop(partial) is the same object without the Layer, for Effect.provideService). A forgotten override is loud, not silent: most defaults fail with a typed PlatformError whose reason is NotFound; makeDirectory and the makeTemp* family die with not implemented; only exists (answers false) and remove (succeeds) are quiet.

Self-contained source · Type-checked

ts
import { Effect, FileSystem } from "effect"

const TestFs = FileSystem.layerNoop({
  readFileString: (path) =>
    path === "./data/comp_bands.csv"
      ? Effect.succeed("level,min,mid,max\nL5,100,120,140")
      : Effect.die(`unexpected read: ${path}`)
})

const firstBand = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem
  const csv = yield* fs.readFileString("./data/comp_bands.csv")
  return csv.split("\n")[1] // "L5,100,120,140"
}).pipe(Effect.provide(TestFs))

The noop service's glob, lstat, and readDirectoryEntries also fail with NotFound unless overridden.

Glob ​

effect/Glob — experimental

Pure path matching with the same syntax FileSystem.glob uses, without touching a disk. Glob.make(pattern, { dot? }) compiles a reusable value, Glob.match(glob, path) (dual) tests a /-separated path, and Glob.escape(text) makes a literal file name match only itself. Syntax: * and ? within one segment, [...] classes (with !/^ negation and POSIX classes such as [[:digit:]]), nested {a,b} alternatives, ** as a whole segment for zero or more segments (so dir/** matches dir too), a trailing / for directories only, and \ escapes. Wildcards never match . or .. and skip dot-names unless dot is set. Leading ! negation and extglobs are not interpreted, malformed syntax such as an unclosed [ matches literally, and UNC paths never match.

Self-contained source · Type-checked

ts
// @effect-diagnostics experimentalApiUsage:off
import { Glob } from "effect"

const reports = Glob.make("exports/**/*.{csv,xlsx}")

Glob.match(reports, "exports/2026/payroll.csv") // true
Glob.match(reports, "exports/.tmp/payroll.csv") // false: dot directory
Glob.match(Glob.make(Glob.escape("band[1].csv")), "band[1].csv") // true

Reach for it when filtering paths you already have (an upload's file list, a zip's entries, a watch event) with the same rules as a file-system search.

Path ​

effect/Path — unstable

Service interface wrapping platform path utilities: join, resolve, dirname, basename, extname, normalize, relative, isAbsolute, parse, format, plus effectful fromFileUrl and toFileUrl helpers. The sep property gives the platform separator.

Mental model: node:path as a service. Core Path.layer deliberately provides POSIX semantics. On Node/Bun/Deno, the aggregate host layer supplies the host-aware implementation; Node also exposes NodePath.layerPosix and NodePath.layerWin32 for cross-platform tooling and tests.

Self-contained source · Type-checked

ts
import { FileSystem, Path } from "effect"
import { Effect } from "effect"

// Build an export file path for this merit cycle's raise recommendations
const buildExportPath = Effect.fn("buildExportPath")(
  function*(cycleId: string, outputDir: string) {
    const path = yield* Path.Path
    const fs = yield* FileSystem.FileSystem

    // Ensure the output directory exists
    yield* fs.makeDirectory(outputDir, { recursive: true })

    // Compose a timestamped CSV path: <outputDir>/merit-<cycleId>-raises.csv
    const filename = `merit-${cycleId}-raises.csv`
    const fullPath = path.join(outputDir, filename)

    yield* Effect.log(`export path: ${fullPath}`)
    return fullPath
  }
)

fromFileUrl and toFileUrl are effectful because malformed or unsupported URLs fail with PlatformError.BadArgument; use them instead of slicing file: strings by hand.

resolveWithin(root, input) returns Option<string> after checking containment using the implementation's path semantics, unlike a raw prefix check; rooted inputs and escapes return None. It is a lexical boundary, not protection against symlinks or filesystem races: combine it with an appropriate file-opening policy for untrusted paths.

When to use: building or decomposing file paths inside an Effect. Inject via service rather than calling path.join directly so tests can control path logic.

Official guide: Path.

Terminal ​

effect/Terminal — unstable

Interactive terminal I/O: query dimensions (columns, rows), follow resizes (size), read a line (readLine), receive a stream of key events (readInput), display text (display). Input reading fails with QuitError on Ctrl+C or Ctrl+D.

size is a scoped Effect yielding a Queue.Dequeue<Terminal.Size> ({ columns, rows }) that starts with the current dimensions, receives each resize until its scope closes, and keeps only the latest value, so a slow renderer never processes stale sizes.

Mental model: the abstraction @effect/cli builds on. Provide a fake terminal in tests via Terminal.make to assert output and simulate input without a real TTY. Migration: the object passed to Terminal.make must now include size; a fixed-size fake can return a queue offered one Size.

Self-contained source · Type-checked

ts
import { Effect, Queue, Terminal } from "effect"

// Re-render a status table whenever the terminal is resized.
export const followResizes = Effect.gen(function*() {
  const terminal = yield* Terminal.Terminal
  const sizes = yield* terminal.size
  while (true) {
    const { columns } = yield* Queue.take(sizes)
    yield* terminal.display(`${"=".repeat(columns)}\n`)
  }
}).pipe(Effect.scoped)

Self-contained source · Type-checked

ts
import { Terminal } from "effect"
import { Effect } from "effect"

// Interactive CLI prompt for confirming a merit cycle run
const confirmMeritRun = Effect.gen(function*() {
  const terminal = yield* Terminal.Terminal
  yield* terminal.display("Confirm merit cycle run? [y/N] ")
  const answer = yield* terminal.readLine
  if (answer.toLowerCase() !== "y") {
    yield* Effect.log("Aborted by user.")
    return false
  }
  yield* terminal.display("Starting merit cycle processing...\n")
  return true
})
// QuitError surfaces if user hits Ctrl+C — handle or let it propagate

Re-prompt by recursion, deferred with Effect.suspend. A validation loop is the prompt calling itself; suspend makes the self-reference lazy so each retry is built only when it is needed. The error channel is the union of the two operations: readLine fails with QuitError, display with PlatformError.

Self-contained source · Type-checked

ts
import { Effect, Option, Terminal } from "effect"
import type { PlatformError } from "effect"

const parsePercent = (input: string): Option.Option<number> => {
  const value = Number(input.trim())
  return input.trim() !== "" && value >= 0 && value <= 25 ? Option.some(value) : Option.none()
}

// Ask until the answer parses. Ctrl+C / Ctrl+D ends the loop as QuitError.
const askMeritPercent: Effect.Effect<
  number,
  Terminal.QuitError | PlatformError.PlatformError,
  Terminal.Terminal
> = Effect.gen(function*() {
  const terminal = yield* Terminal.Terminal
  yield* terminal.display("Merit increase % (0-25): ")
  const answer = parsePercent(yield* terminal.readLine)
  if (Option.isSome(answer)) return answer.value
  yield* terminal.display("Enter a number between 0 and 25.\n")
  return yield* Effect.suspend(() => askMeritPercent)
})

A small script does not need the whole aggregate: NodeTerminal.layer (or BunTerminal.layer) provides Terminal alone.

When to use: CLIs, interactive prompts, or TUI-adjacent tools requiring testable platform-independent I/O.

Official guide: Terminal.

Stdio ​

effect/Stdio — unstable

Lower-level counterpart to Terminal: process.argv via args, write Sinks for stdout and stderr (accepting string | Uint8Array), raw byte Stream for stdin, and stdinIsTerminal / stdoutIsTerminal / stderrIsTerminal effects for adapting output to pipes versus TTYs. I/O can fail with PlatformError. Stdio.layerTest lets you stub any field for unit testing.

Mental model: where Terminal is for interactive programs, Stdio is for pipeable Unix-filter style tools — read stdin, write stdout, parse argv.

Self-contained source · Type-checked

ts
import { Stdio } from "effect"
import { Effect, Stream } from "effect"

// A pipeable tool that accepts NDJSON employee records on stdin
// and echoes validated records to stdout
const validateEmployeeStream = Effect.gen(function*() {
  const stdio = yield* Stdio.Stdio
  const args = yield* stdio.args         // ReadonlyArray<string>
  const interactive = yield* stdio.stdoutIsTerminal
  yield* Effect.log(`argv: ${args.join(" ")}`)
  yield* Effect.log(`stdout is ${interactive ? "interactive" : "redirected"}`)

  // Pipe stdin → decode text → validate → stdout
  yield* stdio.stdin.pipe(
    Stream.decodeText(),
    Stream.map((chunk) => chunk.trim()),
    Stream.filter((line) => line.length > 0),
    Stream.run(stdio.stdout())
  )
})

When to use: streaming CLI tools, stdin byte processing, or typed argv access without globals.

Socket ​

effect/socket/Socket — unstable

Platform-neutral abstraction for a bidirectional socket (TCP, Unix domain, or WebSocket). A Socket is pull-based: it exposes a scoped reader and a scoped writer, and nothing is read from the transport until the consumer pulls.

  • socket.reader — acquiring it dials the connection; its scope owns the connection lifetime. It yields a Reader whose pull returns the next non-empty batch (one buffer for TCP, one entry per WebSocket frame) and whose upgrade(options?) wraps a live connection in TLS (STARTTLS) using TlsUpgradeOptions (key/cert/ca/passphrase/alpnProtocols/requestCert/rejectUnauthorized); an adapter that cannot upgrade in place fails with SocketUpgradeError. Socket.readerBytes(socket) and Socket.readerString(socket, encoding?) acquire a pull already normalized to Uint8Array or string; readerString decodes binary frames with one streaming decoder per acquisition, so a character split across frames is kept intact, and flushes leftover bytes (as U+FFFD) before a text frame or on a 1000 close. Use readerBytes and decode each frame yourself when every binary message must be decoded independently.
  • socket.writer — acquisition cannot fail. It yields a Writer with write(chunk | CloseEvent) and writeAll(chunks); both wait for the transport's native drain signal, so a slow peer backpressures the producer. Writes issued while disconnected suspend until the next connection.

Mental model: a connection is a scoped read loop. Code placed between acquiring the reader and the first pull runs exactly once per (re)connection, which is where a handshake belongs. A pull never completes normally — every termination, a clean close included, fails with SocketError wrapping a SocketCloseError (or SocketReadError, SocketWriteError, SocketOpenError, SocketUpgradeError). Reconnection is therefore ordinary Effect.retry around the scoped loop, not a special socket option.

Backpressure is end to end: TCP pauses while nobody pulls; pausable WebSockets pause at highWaterMark (64 KiB by default) and resume after draining. Browser WebSockets cannot pause, so they fail with SocketReadError when a configured highWaterMark is exceeded — size it for the burst you expect.

WebSockets: Socket.makeWebSocket(url) creates a Socket from a URL; Socket.layerWebSocket(url) provides it as a service. A WebSocketConstructor service controls the underlying constructor. Its second argument is either subprotocols or a typed WebSocketClientOptions ({ headers } for the opening handshake, e.g. an Authorization header): NodeSocket.layerWebSocketConstructor passes it to Node's global WebSocket, BunSocket to Bun's, and NodeWS.layerWebSocketConstructor to the ws package, while the browser constructor throws a TypeError, because browsers cannot set handshake headers. Node's global WebSocket cannot pause reads (frames buffer without limit, or fail with SocketReadError past a configured highWaterMark), ignores a custom Host header, does not compress outgoing messages, and reports connection errors without the underlying error code; provide NodeWS.layerWebSocketConstructor when any of those matter. makeWebSocket forwards only protocols, so to send headers call the constructor service yourself and wrap the result with Socket.fromWebSocket.

TCP in Node: use NodeSocket.layerNet(opts) where opts is a Net.NetConnectOpts object (e.g., { host, port }) plus an optional chunkSize. There is no layerTCP export. For a TLS connection from the start, NodeSocket.makeTls(options) (and its layerTls/makeTlsChannel counterparts) dials tls.connect directly, accepting the same options as tls.connect (ca, cert, key, alpnProtocols, servername, plus an openTimeout); a failed handshake, including an untrusted or expired certificate, fails with SocketOpenError.

Self-contained source · Type-checked

ts
import { Socket } from "effect/socket"
import { NodeSocket } from "@effect/platform-node"
import { Effect, Schedule } from "effect"

// Connect to the payroll service over TCP, send a sync trigger, log every ack.
const triggerPayrollSync = Effect.gen(function*() {
  // Socket is part of the unstable effect/socket module.
  const socket = yield* Socket.Socket

  // Acquiring the reader dials; this scope owns the connection.
  const pull = yield* Socket.readerString(socket)
  const writer = yield* socket.writer

  // Runs once per (re)connection, before the first pull: the handshake slot.
  yield* writer.write("SYNC:merit-cycle-2025\n")

  // Pull until the peer closes. The close arrives as a SocketError failure.
  while (true) {
    for (const ack of yield* pull) {
      yield* Effect.log(`payroll ack: ${ack}`)
    }
  }
}).pipe(
  Effect.scoped,
  // Every termination is a failure, so reconnecting is plain retry.
  Effect.retry({ schedule: Schedule.exponential("200 millis"), times: 5 }),
  // NodeSocket.layerNet — correct name; no layerTCP exists
  Effect.provide(NodeSocket.layerNet({ host: "127.0.0.1", port: 4000 }))
)

For combinator-style consumption, Socket.toStream(socket) is a read-only binary Stream backed by the same pull, and Socket.toChannel / Socket.toChannelString expose the duplex connection as a Channel. All three fail on close for the same reason pull does.

Client-side TLS upgrades also accept servername for SNI/certificate-name selection independently of the numeric connection address. Keep verification enabled and use the intended peer name; a successful TCP connection alone authenticates nothing.

When to use: typed Effect-native TCP or WebSocket communication over a persistent connection.

SocketServer ​

effect/socket/SocketServer — unstable

Server-side counterpart to Socket. The SocketServer service exposes: address — the bound NetAddress.SocketAddress (an InetAddressV4 | InetAddressV6 with address and port, or a UnixPathAddress with path) — and run(handler), a never-ending Effect that accepts connections and passes each as a Socket.Socket to the handler. Errors are SocketServerError with reason SocketServerOpenError | SocketServerUnknownError.

Mental model: provide a handler; the server calls it concurrently per accepted connection. Each handler gets a fresh Socket whose scope closes when the handler completes. An accepted socket starts paused and its reader attaches to the existing connection, so it cannot reconnect after close — a failed pull simply ends that handler. NodeSocketServer.layer({ port: 4000 }) wires up a Node TCP server; NodeSocketServer.layerWebSocket({ port: 8080 }) wires up a WebSocket server backed by ws; NodeSocketServer.makeTls(options) wires up a TLS server from tls.TlsOptions & net.ListenOptions — the tls.createServer options, so a server supplies its own key and cert (the client-side NodeSocket.makeTls takes tls.ConnectionOptions instead).

Self-contained source · Type-checked

ts
import { NetAddress } from "effect/net"
import { Socket, SocketServer } from "effect/socket"
import { NodeSocketServer } from "@effect/platform-node"
import { Effect } from "effect"

// A small HRIS push-notification server: echo events back with a prefix
const hrisNotificationServer = Effect.gen(function*() {
  // SocketServer, NetAddress helpers, and Socket.readerString are part of the
  // unstable effect/socket and effect/net modules.
  const server = yield* SocketServer.SocketServer
  const bound = NetAddress.isInetAddress(server.address)
    ? NetAddress.formatInet(server.address)
    : server.address.path
  yield* Effect.log(`HRIS push server listening on ${bound}`)

  return yield* server.run((socket) =>
    Effect.gen(function*() {
      const pull = yield* Socket.readerString(socket)
      const writer = yield* socket.writer
      while (true) {
        for (const msg of yield* pull) {
          yield* writer.write(`ACK:${msg}`)
        }
      }
    }).pipe(
      Effect.scoped,
      // The peer hanging up is the normal end of this connection, not a server fault.
      Effect.catchTag("SocketError", (error) => Effect.logDebug("connection closed", error))
    )
  )
}).pipe(
  Effect.provide(NodeSocketServer.layer({ port: 4000 })),
  Effect.scoped
)

The bound address and every accepted peer address are NetAddress values rather than strings.

When to use: accepting TCP or WebSocket connections — custom protocols, push event relays, or bidirectional streaming pipelines.

NetAddress ​

effect/net/NetAddress — unstable

Pure, platform-neutral values for network addresses: Ipv4Address / Ipv6Address (IpAddress), MacAddress, internet socket addresses InetAddressV4 / InetAddressV6 (InetAddress, an IP plus a port), and UnixPathAddress. SocketAddress = InetAddress | UnixPathAddress is what SocketServer.address and HttpServer.address report. Ipv4Address and Ipv6Address store their bits as numbers rather than a Uint8Array, so Equal/Hash and comparisons are cheap; every value implements Equal and Hash, so addresses work as HashMap keys and compare structurally.

Classifications are generic branded types parameterized by the address kind, not separate ad-hoc predicates: MulticastAddress<A>, UnicastAddress<A>, BroadcastAddress<A>, LoopbackAddress<A>, LinkLocalAddress<A>, UnspecifiedAddress<A>, PrivateAddress<A>, UniqueLocalAddress<A> narrow an IpAddress or MacAddress to the matching refinement, and Schema.IpMulticastAddress / Schema.IpMulticastAddressFromString / Schema.MacMulticastAddress / Schema.MacMulticastAddressFromString validate multicast addresses straight out of untrusted input.

Mental model: parse once at the boundary, then pass a typed address instead of a string. Parsing is checked — ipFromString, inetAddressFromString, and macAddressFromString return a Result with a NetAddressError, and each has a throwing *Unsafe twin for trusted literals. Formatting is canonical: formatIp, formatInet (brackets IPv6 before the port), and formatUrlHost (brackets IPv6 for use inside a URL; scoped IPv6 is rejected by the URL helpers). Classification predicates — isLoopback, isPrivate, isLinkLocal, isMulticast, isUniqueLocal, isUnspecified — replace ad-hoc prefix string checks, which is what an SSRF or allow-list guard should be built on.

Self-contained source · Type-checked

ts
import { Result } from "effect"
import { IpNetwork, NetAddress } from "effect/net"

// Untrusted input: checked parsing returns a Result, never throws.
// NetAddress and IpNetwork are part of the unstable effect/net module.
const parsed = NetAddress.ipFromString("10.20.3.999")
if (Result.isFailure(parsed)) {
  console.log(parsed.failure._tag) // "NetAddressError"
}

// Trusted literal: the Unsafe twin throws on a typo instead of limping on.
const payrollHost = NetAddress.ipFromStringUnsafe("10.20.3.7")
NetAddress.isLoopback(payrollHost) // false
NetAddress.formatIp(payrollHost)   // "10.20.3.7"

// A socket address keeps the port typed; IPv6 is bracketed when formatted.
const hris = NetAddress.inetAddressFromStringUnsafe("[2001:db8::1]:8443")
hris.port                               // 8443
NetAddress.formatInet(hris)             // "[2001:db8::1]:8443"
NetAddress.formatUrlHost(hris.address)  // "[2001:db8::1]"

// Allow-list an outbound webhook target by CIDR membership, not by string prefix.
const internalRange = IpNetwork.fromStringUnsafe("10.20.0.0/16")
const isInternal = IpNetwork.contains(internalRange, payrollHost) // true

Some socket APIs take the host and the port separately (node:net's { host, port }, a driver's host field). formatHost(address) renders only the numeric host, without brackets or port, and keeps a nonzero IPv6 scope ID as a % suffix. The reverse, inetAddressFromHostString(host, port, scopeIds?), parses an unbracketed numeric host plus a port into an InetAddress and returns a Result; a hostname such as payroll.internal is a failure, because this module never resolves DNS. A named IPv6 zone (fe80::1%en0) needs a map from interface name to numeric scope ID, which scopeIdsFromInterfaces(Object.entries(os.networkInterfaces())) builds from entries you supply; numeric zones need no map, and an unknown name fails with unknown IPv6 interface.

Native socket APIs (raw dgram/net bindings for multicast, scope IDs) need slightly different formatting than formatHost: formatNativeHost(address, scopeIds, platform?) formats an InetAddress host without brackets or a port, keeping IPv6 zones numeric on "win32" and resolving them to an interface name elsewhere; formatMulticastInterface(networkInterface, scopeIds, platform?) formats an IPv4 address or an IPv6 interface index the same way for multicast join/leave calls. Both take the scopeIdsFromInterfaces map and an optional platform string, and neither performs OS lookups itself.

toCanonical(address) converts an IPv4-mapped IPv6 address (and the IP side of an InetAddress) to plain IPv4, preserving the port on an internet address and leaving already-canonical or IPv6-scoped addresses unchanged — use it before comparing or classifying an address that may have arrived in mapped form (common with dual-stack listeners).

Self-contained source · Type-checked

ts
import { Result } from "effect"
import { NetAddress } from "effect/net"
import { networkInterfaces } from "node:os"

// A payroll relay configured with `host` and `port` as separate settings.
// NetAddress is part of the unstable effect/net module.
const scopeIds = NetAddress.scopeIdsFromInterfaces(Object.entries(networkInterfaces()))
const relay = NetAddress.inetAddressFromHostString("fe80::1%lo0", 8443, scopeIds)
if (Result.isSuccess(relay)) {
  NetAddress.formatHost(relay.success) // "fe80::1%1" (lo0's scope ID on this host)
  NetAddress.formatInet(relay.success) // "[fe80::1%1]:8443"
}

Schema ships matching codecs — Schema.IpAddressFromString, Schema.InetAddressFromString, Schema.MacAddressFromString, Schema.SocketAddress, and the v4/v6-specific variants — so a config value or request field decodes straight to an address. A server address has no hostname string field; read NetAddress.formatIp(address.address) instead, and use address.path for Unix sockets. Bun and Deno HTTP server layers can fail with ServeError when the listener address cannot be converted.

The *FromInput constructors normalize supported strings, address values, octets/segments, bytes, or parts objects to their corresponding address kind; IpNetwork.fromInput and IpInterface.fromInput provide the same boundary convenience for networks/interfaces. Each accepts its own declared input union, not arbitrary JSON. Checked forms return Result; keep Unsafe variants at trusted boundaries.

When to use: any time an address crosses a boundary — config, request data, allow/deny lists, logging a bound listener — and whenever address equality or classification matters.

Host ​

effect/net/Host — experimental

Pure values for DNS domain names, numeric hosts (including scoped IPv6), and host/port endpoints. Checked domainNameFromString, hostFromString, and hostPortFromString return Results with NetAddressError; *Unsafe forms are for trusted literals. *FromInput constructors accept the corresponding supported value/string/parts inputs without doing DNS. Format endpoints with formatHostPort so IPv6 gets brackets; bare numeric-address parsing belongs to NetAddress.

toFullyQualified adds the terminal DNS dot; toRelative removes it. parseHostsFile reads text you supply into a name-to-nonempty-addresses map, skips invalid entries and comments, and normalizes names to relative form. It does not read the OS hosts file itself. NetAddress.loopbackAddresses supplies typed loopback values without resolution.

Reach for it when parsing configuration that may contain a name rather than only an IP address.

Dns ​

effect/net/Dns — experimental

Dns.Dns separates lookup (OS host resolution, including hosts-file/system sources), resolve (DNS records of a selected type), and reverse (names for an address). Inputs accept supported strings and typed host/address values. Records include A, AAAA, CAA, CNAME, MX, NAPTR, NS, PTR, SOA, SRV, TXT, and TLSA; record values support structural equality and hashing. A TLSA answer is DNS data, not automatic certificate verification.

Failures are DnsError; do not collapse “lookup failed” into “this name is safe” or silently fall back to another destination. NodeDns.layer, BunDns.layer, and DenoDns.layer provide host adapters. A separate resolver instance can configure name servers for DNS queries; it is not a replacement for the OS lookup policy. Browsers have no equivalent raw DNS layer.

Dns.layerStatic(zone) provides deterministic lookup/record/reverse data without network I/O; invalid zone input fails layer construction with NetAddressError. Use it with AddressResolver.layer() for portable tests, rather than replacing DNS with live public queries. Native lookups do not attach a usable interface to link-local IPv6 addresses; resolve scoped endpoints through AddressResolver when that distinction matters.

Reach for it when querying DNS records or resolving host names without embedding a host API in application code.

AddressResolver ​

effect/net/AddressResolver — experimental

AddressResolver.AddressResolver.resolve(target, { family? }) converts a socket address or host/port input to a nonempty list of socket addresses. Numeric hosts avoid lookup; names use Dns.lookup. Results retain resolver order and are filtered by family; Unix-domain addresses pass through. Invalid endpoints or unsupported numeric families fail with NetAddressError, and lookup failures with DnsError.

Core AddressResolver.layer() requires Dns and handles numeric IPv6 zones only. NodeAddressResolver.layer, BunAddressResolver.layer, and DenoAddressResolver.layer add host interface lookup for named zones. Unscoped link-local IPv6 lookup results are skipped because the resolver cannot infer their interface; a name resolving only to such addresses fails rather than returning unusable endpoints. Supply a zoned literal instead.

Self-contained source · Type-checked

ts
// Host resolution is deliberately experimental.
// @effect-diagnostics experimentalApiUsage:off
import { Effect, Layer } from "effect"
import { AddressResolver } from "effect/net"
import { NodeAddressResolver, NodeDns } from "@effect/platform-node"

export const endpoints = Effect.gen(function*() {
  const resolver = yield* AddressResolver.AddressResolver
  return yield* resolver.resolve("example.com:443", { family: "IPv4" })
}).pipe(
  Effect.provide(NodeAddressResolver.layer.pipe(Layer.provide(NodeDns.layer)))
)

Resolution alone is not an SSRF defense. Validate every resolved candidate and the actual connected peer, consider DNS rebinding and redirects, and do not substitute string-prefix tests for address classification.

Reach for it when turning configured endpoints into typed connection candidates while keeping DNS and interface policy explicit.

DatagramSocket ​

effect/socket/DatagramSocket — experimental

Pull-based UDP with scoped native handles. Acquiring reader opens and binds the socket; only one reader may be open, and another acquisition waits interruptibly. The scoped writer cannot fail to acquire, but writes wait until a reader is open — even send-only applications must acquire one. reader.pull yields a nonempty packet batch; packets retain their bytes safely. writer.write takes { payload, address? }, where payload is text or bytes; omit the destination only for a configured/connected peer.

Closing the reader scope discards queued packets and fails waiting pulls. After a terminal error, queued packets drain before subsequent pulls fail. reader.dropped() counts this reader's receive-buffer overflow, not kernel or network loss. UDP does not guarantee ordering, delivery, uniqueness, or application acknowledgment. writeAll does not resend on failure and does not identify which packet failed; bound sends with Effect.timeout if required.

Use NodeDatagramSocket.layer, BunDatagramSocket.layer, or DenoDatagramSocket.layer; these and DNS/address-resolver adapters are explicit exports, not part of NodeServices.layer, BunServices.layer, or DenoServices.layer. reader.joinMulticast owns membership until its scope closes; the ingress interface is distinct from the adapter's multicast sending interface. Browser WebSockets are not UDP and do not provide this service.

Reach for it when implementing datagram protocols or multicast discovery with deliberate loss and lifetime handling.

IpNetwork ​

effect/net/IpNetwork — unstable

A CIDR network: a network address plus a prefix length, generic over the address family (Ipv4Network, Ipv6Network). Construction is strict — IpNetwork.fromString("10.20.3.7/16") fails because host bits are set; use IpNetwork.fromAddress (which masks them) or go through IpInterface when you have a host address. Operations: contains(network, address), containsNetwork, overlaps, firstAddress / lastAddress, addressCount (a bigint, since an IPv6 range does not fit a number), and format. The native @effect/sql-pg client decodes PostgreSQL cidr columns to their formatted text (for example "10.20.0.0/16"), not to an IpNetwork value — parse it with IpNetwork.fromString where you need the structure.

When to use: allow/deny lists, subnet planning, and tenant or region routing by address range.

IpInterface ​

effect/net/IpInterface — unstable

An address with its prefix length — 10.20.3.7/16 — the form a host or network interface is configured with. Unlike IpNetwork, host bits are preserved. IpInterface.fromString parses it (with ParseOptions), IpInterface.format renders it, and IpNetwork.fromInterface(iface) yields the containing network (10.20.0.0/16). @effect/sql-pg decodes PostgreSQL inet columns to formatted text as well ("10.20.3.7/16", or just the address when the prefix covers the whole address); parse it with IpInterface.fromString.

When to use: modelling "this host, on this subnet" without losing either half.

Worker ​

effect/workers/Worker — unstable

Parent-side API for communicating with a worker thread or IPC child process. A Worker<O, I> provides: send(message: I) — fire a typed message into the worker; run(handler) — a never-completing Effect calling the handler for each emitted O. Errors are WorkerError.

Mental model: typed bidirectional channel where I flows in and O flows out. The parent buffers sends until the worker signals readiness, then drains the queue.

Setup: call NodeWorker.layer(spawnFn) to provide both WorkerPlatform and Spawner; acquire a typed Worker via WorkerPlatform.spawn(id). The spawn function receives a numeric ID and returns a WorkerThreads.Worker or IPC ChildProcess.

Lifetime: run owns the worker. A worker that exits or throws — before or after the ready handshake — fails run with a WorkerError: the Node adapter reports both exit and error events as WorkerReceiveError, the browser adapter reports error events the same way (a dedicated browser worker has no parent-visible exit event), and the Bun adapter reports error events as WorkerUnknownError and does not fail run on a plain exit. A worker that dies before signalling readiness does not leave run hanging uninterruptibly. When the scope around run closes, the Node and Bun adapters send the worker a close message, wait up to five seconds for it to exit, and then call terminate() (Node: kill("SIGKILL") for an IPC child) — so worker-side finalizers get a bounded chance to run. The browser adapter only sends the close message; it does not terminate a dedicated worker you spawned.

Self-contained source · Type-checked

ts
import { Worker } from "effect/workers"
import { NodeWorker } from "@effect/platform-node"
import { Effect } from "effect"
import * as WorkerThreads from "node:worker_threads"

// Parent side: dispatch vesting-schedule computations to worker threads
// Each message is an EquityGrant; workers reply with vestedShares count
const workerLayer = NodeWorker.layer(
  (id) => new WorkerThreads.Worker(new URL("./vesting-worker.js", import.meta.url))
)

const computeVestedSharesInParallel = Effect.gen(function*() {
  // Worker is part of the unstable effect/workers module.
  const platform = yield* Worker.WorkerPlatform
  // Spawn a typed Worker: output = number (vestedShares), input = EquityGrant id
  const worker = yield* platform.spawn<number, string>(0)

  // Send a grant ID; the worker replies with vestedShares
  yield* worker.send("grant-2024-001")

  return yield* worker.run((vestedShares) =>
    Effect.log(`vested shares computed: ${vestedShares}`)
  )
}).pipe(
  Effect.scoped,
  Effect.provide(workerLayer)
)

When to use: offloading CPU-heavy computation to a worker thread while retaining typed error handling and structured concurrency.

WorkerRunner ​

effect/workers/WorkerRunner — unstable

Worker-side counterpart to Worker. A WorkerRunner<O, I> listens for I messages from the parent (tagged by port ID), calls the handler, and sends O replies via send(portId, message) or sendUnsafe. The optional disconnects queue notifies when a port closes; the browser and Deno runners provide it (many ports can share one worker there), the Node runner has a single parent and does not. An RPC server running over a worker forwards every disconnect, so a closed port's in-flight requests are interrupted rather than left running.

Mental model: if Worker is the client, WorkerRunner is the server. Write the worker's main function by yielding the WorkerRunnerPlatform service and calling platform.start(), then provide the platform layer from NodeWorkerRunner.layer.

Self-contained source · Type-checked

ts
// vesting-worker.ts — runs inside the worker thread
import { WorkerRunner } from "effect/workers"
import { NodeWorkerRunner } from "@effect/platform-node"
import { Effect } from "effect"

// Receive a grant ID, compute vested shares, reply to parent
const runner = Effect.gen(function*() {
  // WorkerRunner is part of the unstable effect/workers module.
  const platform = yield* WorkerRunner.WorkerRunnerPlatform
  // start<O, I>() — O is what we send back, I is what we receive
  const workerRunner = yield* platform.start<number, string>()

  yield* workerRunner.run((portId, grantId) =>
    Effect.gen(function*() {
      // CPU-bound vesting math
      const vestedShares = computeVested(grantId)
      yield* workerRunner.send(portId, vestedShares)
    })
  )
}).pipe(
  Effect.provide(NodeWorkerRunner.layer),
  Effect.runFork
)

function computeVested(grantId: string): number {
  // ... real vesting schedule math here
  return 1000
}

When to use: writing the worker-thread side of a Worker/WorkerRunner pair.

WorkerError ​

effect/workers/WorkerError — unstable

Typed error union for worker communication. WorkerError wraps one of four reasons: WorkerSpawnError (worker failed to start), WorkerSendError (message serialization failed), WorkerReceiveError (message decode failed), WorkerUnknownError (anything else). Catch with Effect.catchTag("WorkerError", ...).

Transferable ​

effect/workers/Transferable — unstable

Transfer-list support for worker message fields. Annotate fields with Transferable.schema; a Transferable.Collector records backing ArrayBuffers, MessagePorts, or ImageData buffers for the platform's postMessage transfer list. The surrounding message still passes through Schema encoding and structured clone; only the transferred resources avoid copying. Transferring an ArrayBuffer detaches it from the sender, so do not retain a usable-sender-buffer assumption after sending. Without a Collector the annotation does not collect anything.

ChildProcess ​

effect/process/ChildProcess — unstable

Value type describing a command to run — a typed ProcessBuilder. Use ChildProcess.make(cmd, args, options) to create a StandardCommand, or chain two commands with ChildProcess.pipeTo to create a PipedCommand (shell | equivalent). Modifiers: setEnv, setCwd, prefix.

Mental model: a Command is pure data describing what to run. Nothing executes until passed to a ChildProcessSpawner. Commands are composable and trivially testable. On Windows, the Node spawner hides the child console/GUI window by default unless the command is detached; set windowsHide: false explicitly when a visible window is intended. The option has no effect on other hosts.

Self-contained source · Type-checked

ts
import { ChildProcess } from "effect/process"

// ChildProcess is part of the unstable effect/process module.
// Describe a payroll-export command (pure data, nothing runs yet)
const payrollExportCmd = ChildProcess.make("payroll-cli", ["export", "--format=csv"])

// Pipe pipeline: export payroll data and sign it
const signedExport = ChildProcess.make("payroll-cli", ["export", "--format=csv"]).pipe(
  ChildProcess.pipeTo(ChildProcess.make("gpg", ["--sign", "--armor"]))
)

// Override environment for a production payroll run
const prodExportCmd = ChildProcess.make("payroll-cli", ["export"]).pipe(
  ChildProcess.setEnv({ PAYROLL_ENV: "production", DB_HOST: "prod-db.internal" }),
  ChildProcess.setCwd("/app/payroll")
)

make also has a template-literal form, with or without options first. Interpolations are arguments, never shell text: each interpolated value becomes exactly one argument (an array becomes several), so untrusted input cannot inject a command. The literal text is split the way a POSIX shell splits words — quotes group words and backslashes escape — but no shell runs, so shell syntax in the literal text (|, ;, $HOME, *, a leading ~, {a,b}, an assignment such as FOO=bar cmd) throws a CommandLine.CommandLineError with reason UnsupportedSyntax when make is called. Quote such characters or pass them through ${}. Arguments and env values may be Redacted strings: the child receives the value, and logs and CommandLine.display show <redacted>; the program name cannot be Redacted.

Self-contained source · Type-checked

ts
import { ChildProcess } from "effect/process"

const employee = "Ada Lovelace; rm -rf /" // stays one harmless argument
const flags = ["--format=csv", "--cycle=2026 H1"]

// payroll-cli ["export", "--format=csv", "--cycle=2026 H1", "--employee", "Ada Lovelace; rm -rf /"]
const exportOne = ChildProcess.make`payroll-cli export ${flags} --employee ${employee}`

// Options first, then the template.
const listing = ChildProcess.make({ cwd: "/app/payroll", forceKillAfter: "2 seconds" })`ls -la`

With the shell option the template text is the shell script, kept as written; it cannot contain ${} values (that throws), and extra arguments fail with BadArgument when spawned. Build such a script with CommandLine and pass it as a plain string.

Migration: templates that relied on whitespace-only splitting change meaning when they contain quotes, and templates containing shell syntax now throw. ChildProcess.TemplateExpression and ChildProcess.TemplateExpressionItem moved to CommandLine.

When to use: composing commands before running them, separating command description from execution.

CommandLine ​

effect/process/CommandLine — unstable

Builds the single strings that a shell or a Windows program splits back into arguments — for sh -c, SSH, or a shell command — and argument lists from templates. It is unrelated to effect/cli, which parses your own program's arguments. quote(word, { format? }) quotes one argument, join(words, { format? }) quotes a whole argument list, and both return a Result failing with CommandLineError (a NUL character, or an argument the format cannot carry). display(words) renders the same text for logs with Redacted values replaced by <redacted>; quote and join include the secret, because their output is meant to run. template is the parser ChildProcess.make uses, returning Result<Array<Word>, CommandLineError>. Formats are "posix" (default; sh, bash, zsh, and readable by fish), "powershell" (7.3+), and "windows" (C runtime rules). The format follows the receiving shell: SSH sends the line to the remote account's login shell, and cmd.exe is not supported.

Self-contained source · Type-checked

ts
import { Redacted, Result } from "effect"
import { ChildProcess, CommandLine } from "effect/process"

const cycle = "2026 H1; rm -rf /"
const token = Redacted.make("s3cret")

// One shell script, every value quoted for sh.
const script = Result.getOrThrow(CommandLine.join(["payroll-cli", "export", "--cycle", cycle]))
export const viaShell = ChildProcess.make(`${script} | gzip > export.gz`, { shell: "/bin/sh" })

// Safe to log: the token is hidden.
export const logged = CommandLine.display(["curl", "-H", token, "https://payroll.internal"])
// "curl -H <redacted> https://payroll.internal"

ChildProcessSpawner ​

effect/process/ChildProcessSpawner — unstable

Service that executes ChildProcess.Command values.

Key APIs: spawner.string(cmd), spawner.lines(cmd), spawner.spawn(cmd)

string collects stdout as a single string. lines collects stdout as Array<string>. streamString / streamLines are the incremental Stream forms, and exitCode(cmd) runs a command for its status alone; all five take { includeStderr } except exitCode. spawn returns a scoped ChildProcessHandle with stdout, stderr, all (merged) as byte Streams, and exitCode as an Effect waiting for process completion. Exit code is a branded ExitCode; compare with ChildProcessSpawner.ExitCode(0).

The collecting helpers never deadlock on an unread pipe: exitCode reads and discards stdout and stderr until the process exits, and string, lines, streamString, and streamLines discard stderr unless includeStderr is set. A failure while reading that output (for example from an output Sink) fails the helper. Output sinks configured for stdout, stderr, or output additionalFds only receive data while the matching handle stream is consumed.

Platform implementations: NodeServices.layer includes NodeChildProcessSpawner.layer; Bun uses BunServices.layer.

Termination waits, and only forceKillAfter bounds it. On Node and Bun, closing the scope around spawn (or calling handle.kill(options?)) signals the child's whole process group with killSignal (default SIGTERM), then waits for the leader to exit and up to one more second for descendants to disappear. Nothing escalates by default, so a child that ignores SIGTERM holds the scope — and therefore your shutdown — open until it exits by itself (probed: a trap '' TERM; sleep 4 child delayed release by the remaining four seconds). Set forceKillAfter on the command (or pass it to kill) to send SIGKILL to the group at that deadline; the probe then released in 300 ms. The waits use native timers rather than the Effect Clock, so they elapse under TestClock without adjust. The Node and Bun spawners also clean up the group when the leader has already exited, successfully or by a signal, before the scope closes: a grandchild the command left running in the background (sh -c 'sleep 47 & exit 0' in the probe) is gone once the scope closes. That cleanup targets a numeric process-group ID, so if the group disappears and the operating system reuses its ID first, an unrelated group can be signalled. On Windows the tree is ended with taskkill /T /F and only the leader is awaited; the Deno adapter differs again (see Platform packages).

Self-contained source · Type-checked

ts
import { ChildProcess, ChildProcessSpawner } from "effect/process"
import { NodeServices } from "@effect/platform-node"
import { Console, Data, Effect, Stream } from "effect"

// ChildProcess and ChildProcessSpawner are part of the unstable effect/process module.
class PayrollExportFailed extends Data.TaggedError("PayrollExportFailed")<{
  readonly exitCode: ChildProcessSpawner.ExitCode
}> {}

// Spawn a payroll-export child process and stream its output line by line
const runPayrollExport = Effect.gen(function*() {
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner

  // Collect the version string of the payroll CLI tool
  const cliVersion = yield* spawner.string(
    ChildProcess.make("payroll-cli", ["--version"])
  )
  yield* Effect.log(`payroll-cli version: ${cliVersion.trim()}`)

  // Collect which employee IDs are in the current export batch
  const batchIds = yield* spawner.lines(
    ChildProcess.make("payroll-cli", ["list-pending", "--format=ids"])
  )
  yield* Effect.log(`batch size: ${batchIds.length} employees`)

  // Stream a long-running payroll export, logging each output line
  yield* Effect.scoped(Effect.gen(function*() {
    const handle = yield* spawner.spawn(
      ChildProcess.make("payroll-cli", ["export", "--format=csv"], {
        env: { PAYROLL_ENV: "production" },
        extendEnv: true
      })
    )

    yield* handle.all.pipe(
      Stream.decodeText(),
      Stream.splitLines,
      Stream.runForEach((line) => Console.log(`[payroll-export] ${line}`))
    )

    const code = yield* handle.exitCode
    if (code !== ChildProcessSpawner.ExitCode(0)) {
      return yield* new PayrollExportFailed({ exitCode: code })
    }
  }))

  return batchIds
}).pipe(Effect.provide(NodeServices.layer))

When to use: running external tools with typed I/O, structured error handling, and streamed output.

Platform packages ​

The services above are interfaces. Platform packages provide concrete Layer implementations and a runMain entry point.

@effect/platform-node — package

Implements FileSystem, Path, Terminal, Stdio, ChildProcessSpawner, the effect/crypto services, Socket, SocketServer, Worker, WorkerRunner, HTTP, Redis, cluster transports, and stream adapters using Node.js APIs; it requires Node.js 22.19.0 or newer. NodeServices.layer is deliberately narrower: it aggregates ChildProcessSpawner, FileSystem, Path, Stdio, and Terminal. Crypto (NodeCrypto.layer or one family layer, see Cryptography), sockets, workers, HTTP (NodeHttpServer.layer), and other adapters have explicit layers.

NodeSocket WebSocket clients use Node's global WebSocket, so the ws package is loaded only by NodeSocketServer.layerWebSocket and the NodeWS module (NodeWS.WebSocket, NodeWS.layerWebSocketConstructor). Migration: NodeSocket.NodeWS and NodeSocket.layerWebSocketConstructorWS were removed; import NodeWS from @effect/platform-node instead. Node socket and stream readers return at most chunkSize chunks per pull (default 4096; Infinity restores unbounded batching), and Node stream read(size) byte sizes moved to a separate readSize option.

@effect/platform-node has no Mime export — use Mime from effect/http instead. NodeRedis wraps the redis (node-redis) client, so the optional peer dependency is redis >=5.1.0 <7.0.0; its accessors are unstable because they expose that client's own types directly.

Self-contained source · Type-checked

ts
import { NodeRuntime, NodeServices } from "@effect/platform-node"
import { Effect } from "effect"

const program = Effect.gen(function*() {
  // ... your app
})

program.pipe(
  Effect.provide(NodeServices.layer),
  NodeRuntime.runMain
)

@effect/platform-bun — package

Bun-native counterparts cover the same broad host responsibilities, but use Bun* namespaces and layers rather than promising every Node adapter is interchangeable. Like Node's aggregate, BunServices.layer includes ChildProcessSpawner, FileSystem, Path, Stdio, and Terminal; BunCrypto, HTTP, sockets, workers, BunRedis (unstable — it exposes the underlying redis client's types), and cluster adapters remain explicit. BunHttpServer disables Bun's default 10-second idleTimeout unless you pass one, so quiet response streams and slow uploads are not cut; a server exposed directly to the internet should set idleTimeout (seconds) itself.

Self-contained source · Type-checked

ts
import { BunRuntime, BunServices } from "@effect/platform-bun"
import { Effect } from "effect"

const program = Effect.gen(function*() {
  // same code as the Node version
})

program.pipe(
  Effect.provide(BunServices.layer),
  BunRuntime.runMain
)

@effect/platform-deno — package

The Deno host package (Deno 2.9.3+) covers FileSystem, Path, DenoCrypto, Stdio, Terminal, child processes, HTTP client/server, sockets, workers, DenoRedis (unstable, same caveat as NodeRedis/BunRedis), multipart parsing, key-value storage, and cluster HTTP/socket adapters. DenoServices.layer is the standard aggregate (ChildProcessSpawner, FileSystem, Path, Stdio, Terminal); crypto and specialized HTTP/socket/worker layers remain explicit. DenoRuntime.runMain installs structured SIGINT/SIGTERM interruption and teardown.

The Deno child-process adapter has narrower process-control semantics than Node: commands using detached or additionalFds fail as unsupported, and killing a handle terminates only the direct child, not its descendants. Design process-tree cleanup explicitly when Deno is a deployment target.

Self-contained source · Type-checked

ts
import { DenoRuntime, DenoServices } from "@effect/platform-deno"
import { Effect, FileSystem } from "effect"

const program = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem
  return yield* fs.readFileString("./deno.json")
})

program.pipe(
  Effect.provide(DenoServices.layer),
  DenoRuntime.runMain
)

@effect/platform-cloudflare — package

Experimental (every module is tagged @stability experimental, and its APIs may change in patch releases). It is not a general Workers host adapter with FileSystem or runMain: it runs Effect Cluster on Cloudflare Durable Objects, giving each entity id, workflow execution, durable queue, and singleton its own SQLite-backed Durable Object. The root import exposes five modules:

ModuleRole
CloudflareClusterlayer({ entities, entityNamespace, workflowNamespace, queueNamespace, singletonNamespace, keepAliveHeartbeat? }) provides Sharding, WorkflowEngine, and PersistedQueueFactory; also DurableObjectSqlClient (the entity object's own SQLite as an SqlClient), clusterCronSingletonName, and the encodeName/decodeName naming scheme.
CloudflareDurableObjectsThe four classes the Worker entry re-exports and binds as SQLite-backed classes (ClusterEntity, ClusterWorkflow, ClusterDurableQueue, ClusterSingleton), plus setInitializer for an asynchronously built layer (must finish within 15 seconds).
CloudflareWorkflowEngineThe WorkflowEngine on the workflow namespace alone; it sets DurableClock.InMemoryThreshold to zero, so a DurableClock.sleep without an explicit inMemoryThreshold always schedules a durable timer.
CloudflarePersistedQueueThe PersistedQueueFactory on the queue namespace alone; PersistedQueue.layerCleanup is unsupported.
CloudflareDurableObjectProgramsClass-independent programs behind those classes, for frameworks that create their own Durable Object classes.

AlchemyCloudflareCluster is a subpath-only import (@effect/platform-cloudflare/AlchemyCloudflareCluster) behind the optional @alchemy.run/cloudflare peer (>=2.0.0-beta.85 <3); make registers the classes and bindings from inside an Alchemy Cloudflare.Worker program, so there is no wrangler.jsonc, class re-export, or initializer. Workers' types such as DurableObjectNamespace come from @cloudflare/workers-types, a dependency of the package. The Durable Object classes accept calls only through same-Worker bindings; never route public traffic to them.

@effect/platform-node-shared — package

Contains implementation shared by the Node, Bun, and Deno adapters: Node-compatible Path/FileSystem/Terminal/child-process/socket/worker/Redis building blocks. It is public for adapter authors, but application entrypoints should normally depend on the host package rather than assembling these internals.

@effect/platform-browser — package

Browser-specific implementations: BrowserCrypto.layer (every effect/crypto service on Web Crypto, or one family layer such as BrowserCrypto.layerDigest), BrowserSocket.layer (native WebSocket), BrowserWorker.layer and BrowserWorkerRunner.layer (dedicated/shared workers via postMessage). No FileSystem or ChildProcess in browsers. Additional APIs include Permissions, Clipboard, Geolocation, typed DOM event streams, Fetch/XHR clients, browser persistence/key-value layers, and the typed IndexedDB subsystem below.

BrowserRuntime.runMain listens for pagehide and interrupts the root fiber when the document is being discarded. A persisted pagehide — the page entering the back/forward cache — is ignored, because that document may be restored with its fibers intact. The interruption is best effort: the browser may tear the page down before asynchronous finalizers, network flushes, or timers complete, so persist anything important before unload rather than in a finalizer.

Self-contained source · Type-checked

ts
import { BrowserRuntime, BrowserWorker } from "@effect/platform-browser"
import { Effect } from "effect"

const app = Effect.gen(function*() {
  // browser-specific effects
})

app.pipe(
  Effect.provide(BrowserWorker.layer((id) => new Worker(new URL("./worker.js", import.meta.url)))),
  BrowserRuntime.runMain
)

Choosing a host ​

A platform Layer says how a capability is implemented. The host decides something more important: who owns the runtime, what cancels work, and whether cleanup is actually awaited. Pick the row first, then the package.

HostRunner and ownerWhat the host guaranteesWhat it cannot promise
Node / Bun / Deno processNodeRuntime.runMain, BunRuntime.runMain, DenoRuntime.runMain once at the root; the launched Layer's scope owns everythingSIGINT and SIGTERM interrupt the main fiber; finalizers run; the process exits after teardown with 0, 130 (interrupt-only), the largest Runtime.InterruptExitCode when every interruption carries one, or the error's exit codeSurviving SIGKILL or an expired grace period; signal delivery when another process is PID 1 in the container; identical signal behavior on Windows — verify on the target
Web-standard handler (serverless, edge)HttpRouter.toWebHandler or HttpEffect.toWebHandlerLayer returns { handler, dispose }; module scope owns the Layer, each request owns its own scopeThe Layer is built eagerly; each request's scope closes once its response body has finished; request.signal interrupts the request fiberThat dispose is ever awaited, that the isolate is reused, or that work continues after the response. A Fetch-shaped API is not Node: no node:* modules unless the platform says so
Foreign framework callback (Express, Hono, UI, plugin API)One ManagedRuntime, created at boot and disposed by the host's shutdown hookOne shared Layer graph; idempotent dispose()Cancellation and drain — nothing happens unless you forward the host's AbortSignal and stop admission yourself
Browser pageBrowserRuntime.runMainA non-persisted pagehide interrupts the main fiberCompletion of asynchronous finalizers or network flushes during teardown
Worker thread or IPC childThe parent's scope around Worker.run; worker side runs a WorkerRunner with its platform LayerNode and Bun: close message, five-second grace, then terminate()Worker-side cleanup that needs longer than the grace; termination of a browser worker (the adapter only asks it to close)
CLICommand.run handed to the platform runMainSame as a process; Ctrl+C inside a prompt is a typed QuitError—
TestThe scope of it.effect / it.layerScope closes at the end of the test; time is virtualAnything about real signals, ports, files, or bundling — fakes do not exercise them
  • Same program, different owner. Business code is identical in every row; only the outermost line and the platform Layer change. If a module has to know which row it runs in, a platform import has leaked inward.
  • Server-side rendering is two hosts. The server request and the hydrated page have separate scopes and runtimes: serialize validated data across that seam, never a service, fiber, Scope, or runtime.
  • Edge isolates may forbid timers at module scope. The default scheduler falls back to a microtask when setting a timer throws (Cloudflare Workers' global scope), so an Effect run at module load does not crash there. A module-level ManagedRuntime amortizes acquisition across invocations of a reused isolate, but it must not capture request data and must not assume disposal runs.
  • Platform-specific defaults follow the host. Logger.consolePretty() detects TTY versus browser rendering; pin one with Logger.consolePrettyTty or Logger.consolePrettyBrowser. Logger.toFile writes through the FileSystem service, so it needs a platform Layer in scope (both in Observability).
  • An intentional shutdown can pick its exit code. runMain reports 130 for an interrupt because it assumes someone outside stopped the program. When your own code ends the program by interrupting the main fiber (a stdio server whose input closed, say), interrupt it with Fiber.interruptAs(fiber, undefined, Context.make(Runtime.InterruptExitCode, 0)). Runtime.defaultTeardown uses the largest annotated code when every interrupt reason carries one and falls back to 130 as soon as one does not; a cause mixing interrupts with errors still takes the error path. The code is read from the Cause, so providing Runtime.InterruptExitCode as a service does nothing. RPC and MCP stdio servers use this to exit 0 after stdin closes and pending responses drain.

Fragment · Type-checked

ts
import { Context, Effect, Fiber, Runtime } from "effect"

// Stop the main fiber on purpose and exit 0 instead of 130.
declare const mainFiber: Fiber.Fiber<void>

const finishCleanly = Fiber.interruptAs(
  mainFiber,
  undefined,
  Context.make(Runtime.InterruptExitCode, 0)
)

export const program = Effect.asVoid(finishCleanly)

Official guide: Runtime (platform) (it gives the exit code as only 0 or 1 and names only SIGINT; Effect also uses 130 for an unannotated interrupt and handles SIGTERM). Recipes: a graceful Node entrypoint, ManagedRuntime at an imperative boundary, and request cancellation through a host.

Keep platform and unstable imports behind a capability ​

Let domain code depend on a small app-owned service, and let exactly one module import the platform package or the unstable module that implements it. The reason is churn as much as portability: unstable modules (effect/socket/*, effect/net/*, effect/process/*, effect/workers/*) may change in any release, and a stable module's surface can move across a major version too. A quarantined import turns such a change into a one-file edit. Tests provide a fake Layer instead of patching globals.

Self-contained source · Type-checked

ts
import { Context, Data, Effect, Layer } from "effect"
import { ChildProcess, ChildProcessSpawner } from "effect/process"

class PayrollCliFailed extends Data.TaggedError("PayrollCliFailed")<{
  readonly cause: unknown
}> {}

// Domain code sees only this capability.
class PayrollCli extends Context.Service<PayrollCli, {
  readonly pendingEmployeeIds: Effect.Effect<ReadonlyArray<string>, PayrollCliFailed>
}>()("app/PayrollCli") {
  // The one place that knows about the unstable process API.
  static layer = Layer.effect(
    PayrollCli,
    Effect.gen(function*() {
      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
      return {
        pendingEmployeeIds: spawner.lines(
          ChildProcess.make`payroll-cli list-pending --format=ids`
        ).pipe(Effect.mapError((cause) => new PayrollCliFailed({ cause })))
      }
    })
  )

  static layerTest = (ids: ReadonlyArray<string>) =>
    Layer.succeed(PayrollCli)({ pendingEmployeeIds: Effect.succeed(ids) })
}

Note: This applies to leaf capabilities — a file store, a status client, a subprocess. Framework-level unstable modules such as HttpApi, RpcServer, or SqlClient are used directly throughout a codebase; manage those by pinning one Effect version and re-auditing on upgrade (see Incompatible unstable package versions).

Browser IndexedDB ​

@effect/platform-browser/IndexedDb* — package

Five modules form a schema-aware, versioned database rather than a thin IDBRequest wrapper:

ModuleResponsibility
IndexedDbindexedDB / IDBKeyRange capability service plus valid-key schemas; layerWindow uses browser globals.
IndexedDbTableAn object-store descriptor with a Schema, key path, typed index paths, auto-increment and durability metadata. Declaring an index does not create it.
IndexedDbVersionA non-empty set of tables representing one schema version.
IndexedDbDatabaseOrdered migrations, database layer, getQueryBuilder, and destructive rebuild.
IndexedDbQueryBuilderSchema-encoded writes and decoded reads, index/key ranges, pagination/streaming, transactions, and reactive invalidation.

Self-contained source · Type-checked

ts
import {
  IndexedDb,
  IndexedDbDatabase,
  IndexedDbTable,
  IndexedDbVersion
} from "@effect/platform-browser"
import { Effect, Layer, Schema } from "effect"

const Todo = IndexedDbTable.make({
  name: "todo",
  schema: Schema.Struct({
    id: Schema.Int,
    title: Schema.String,
    completed: Schema.Boolean
  }),
  keyPath: "id",
  indexes: { titleIndex: "title" }
})

const V1 = IndexedDbVersion.make(Todo)

class AppDb extends IndexedDbDatabase.make(
  V1,
  Effect.fn(function*(migration) {
    yield* migration.createObjectStore("todo")
    yield* migration.createIndex("todo", "titleIndex")
  })
) {}

const program = Effect.gen(function*() {
  const db = yield* AppDb.getQueryBuilder
  yield* db.from("todo").insert({
    id: 1,
    title: "Review salary bands",
    completed: false
  })
  return yield* db.from("todo").select("titleIndex").equals("Review salary bands")
}).pipe(
  Effect.provide(
    AppDb.layer("comp-planner").pipe(Layer.provide(IndexedDb.layerWindow))
  )
)

Use .add(V2, (from, to) => ...) to preserve/copy rows while changing stores or indexes. withTransaction({ tables, mode: "readwrite" })(effect) aborts writes when the effect fails. Queries provide equals, comparison/range operators, limit, offset, reverse, filter, first, paged stream, and reactive variants; mutations expose invalidation. rebuild deletes and recreates the database, so data not reintroduced by migrations is lost.

Reach for it when a browser application needs local, typed, queryable state with deliberate migrations and transactions. For simple keys, use BrowserKeyValueStore; for generic persistence, BrowserPersistence.layerIndexedDb is a separate, simpler store that talks to the raw indexedDB API directly rather than building on these typed modules.

Other browser capabilities ​

APIWhat it adds
Permissions.queryTyped permission status; querying does not itself grant permission.
ClipboardText/blob reads and writes, subject to browser security and user-activation rules.
GeolocationCurrent position and a scoped watchPosition stream with typed permission/timeout failures.
BrowserStreamTyped window and document event streams with automatic listener cleanup.
BrowserHttpClientPortable Fetch layer plus an XHR escape hatch and array-buffer response mode.
BrowserKeyValueStoreLocalStorage, SessionStorage, or IndexedDB-backed key/value layers.
BrowserPersistenceThe unstable Persistence abstraction backed by IndexedDB, including TTL behavior.

Tip: Browser APIs remain ordinary services and layers. At portable test boundaries, FileSystem.layerNoop, Stdio.layerTest, and a seeded SecureRandom.make(...) or Layer.mock crypto service (Cryptography) avoid reaching host globals.

Edition 4.1 · audited 2026-11-19 against Effect 4.1.4.