The fetch function is the most basic way to perform requests.
It takes a Request as input and returns an Effect with Response.
Automatically handles errors such as network issues, request abortion, and non-OK HTTP responses.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
As you can see, using fetch will add a new requirement: Fetch.Fetch.
So to run programs that use fetch, you will need to provide an implementation of the Fetch service.
Provides an implementation for a service in the context of an effect.
Details
This function allows you to supply a specific implementation for a service
required by an effect. Services are typically defined using Context.Tag,
which acts as a unique identifier for the service. By using this function,
you link the service to its concrete implementation, enabling the effect to
execute successfully without additional requirements.
For example, you can use this function to provide a random number generator,
a logger, or any other service your effect depends on. Once the service is
provided, all parts of the effect that rely on the service will automatically
use the implementation you supplied.
Example
import { Effect, Context } from"effect"
// Declaring a tag for a service that generates random numbers
Runs an effect in the background, returning a fiber that can be observed or
interrupted.
Unless you specifically need a Promise or synchronous operation, runFork
is a good default choice.
Details
This function is the foundational way to execute an effect in the background.
It creates a "fiber," a lightweight, cooperative thread of execution that can
be observed (to access its result), interrupted, or joined. Fibers are useful
for concurrent programming and allow effects to run independently of the main
program flow.
Once the effect is running in a fiber, you can monitor its progress, cancel
it if necessary, or retrieve its result when it completes. If the effect
fails, the fiber will propagate the failure, which you can observe and
handle.
When to Use
Use this function when you need to run an effect in the background,
especially if the effect is long-running or performs periodic tasks. It's
suitable for tasks that need to run independently but might still need
observation or management, like logging, monitoring, or scheduled tasks.
This function is ideal if you don't need the result immediately or if the
effect is part of a larger concurrent workflow.
The layer export provides a convenient way to use the live Fetch implementation with Effect’s layer composition.
This is the recommended approach when building applications with multiple layers.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
const provide: <Fetch.Fetch, never, never>(layer:Layer<Fetch.Fetch, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Fetch.Fetch>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
Effect.provide(Fetch.layer), // ◀︎── Provide Fetch layer
Effect.runPromise
);
@since ― 1.2.0
layer), // ◀︎── Provide Fetch layer
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?:AbortSignal|undefined;
} |undefined) => Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
Example (Running a Successful Effect as a Promise)
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
The fetchArrayBuffer function is a helper that combines fetch with Response.readArrayBuffer.
It is similar to fetchJson, but reads the body as ArrayBuffer.
The fetchReadableStream function is a helper that combines fetch with Response.readReadableStream.
It is similar to fetchJson, but reads the body as ReadableStream.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
When dealing with APIs that return paginated data,
fx-fetch provides convenient functions to handle pagination: paginatedFetch and paginatedFetchStream.
The paginatedFetch function is used to handle paginated HTTP endpoints. It repeatedly performs fetch requests based on the provided logic until there are no more pages to fetch.
The function takes an initial Request and an onResponse callback. The callback receives the last Response and should return an object containing:
pageEmission: The data to emit for the current page.
nextRequest: An Option containing the next Request to fetch, or None if there are no more pages.
Transforms the value inside a Some to a new value using the provided
function, while leaving None unchanged.
Details
This function applies a mapping function f to the value inside an Option
if it is a Some. If the Option is None, it remains unchanged. The
result is a new Option with the transformed value (if it was a Some) or
still None.
This utility is particularly useful for chaining transformations in a
functional way without needing to manually handle None cases.
The paginatedFetchStream function is similar to paginatedFetch, but instead of returning all pages at once,
it returns a Stream that emits each page as it is fetched.
Transforms the value inside a Some to a new value using the provided
function, while leaving None unchanged.
Details
This function applies a mapping function f to the value inside an Option
if it is a Some. If the Option is None, it remains unchanged. The
result is a new Option with the transformed value (if it was a Some) or
still None.
This utility is particularly useful for chaining transformations in a
functional way without needing to manually handle None cases.
The makeMiddlewareLayer function creates a middleware Layer that allows customizing request and response handling.
This is useful for adding cross-cutting concerns like authentication, logging, or request transformation.
The middleware can transform requests before they are sent and responses after they are received.
Both mapRequest and mapResponse are optional - if not provided, they pass through unchanged.
Creates a middleware Layer that allows customizing request and response handling.
The middleware can transform requests before they are sent and responses after they are received.
Both mapRequest and mapResponse are optional - if not provided, they pass through unchanged.
@example
import { Effect } from'effect';
import { Fetch, Request } from'fx-fetch';
// Middleware that adds authorization header to all requests
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
const provide: <Fetch.Fetch, never, never>(layer:Layer<Fetch.Fetch, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Fetch.Fetch>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?:AbortSignal|undefined;
} |undefined) => Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
Example (Running a Successful Effect as a Promise)
Creates a middleware Layer that allows customizing request and response handling.
The middleware can transform requests before they are sent and responses after they are received.
Both mapRequest and mapResponse are optional - if not provided, they pass through unchanged.
@example
import { Effect } from'effect';
import { Fetch, Request } from'fx-fetch';
// Middleware that adds authorization header to all requests
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
const provide: <Fetch.Fetch, never, Config>(layer: Layer.Layer<Fetch.Fetch, never, Config>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Config|Exclude<R, Fetch.Fetch>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
const provide: <Config, never, never>(layer: Layer.Layer<Config, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Config>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?:AbortSignal|undefined;
} |undefined) => Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
Example (Running a Successful Effect as a Promise)
Creates a middleware Layer that allows customizing request and response handling.
The middleware can transform requests before they are sent and responses after they are received.
Both mapRequest and mapResponse are optional - if not provided, they pass through unchanged.
@example
import { Effect } from'effect';
import { Fetch, Request } from'fx-fetch';
// Middleware that adds authorization header to all requests
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level.
Details
This function provides a simple way to log messages or error causes during
the execution of your effects. By default, logs are recorded at the INFO
level, but this can be adjusted using other logging utilities
(Logger.withMinimumLogLevel). Multiple items, including Cause instances,
can be logged in a single call. When logging Cause instances, detailed
error information is included in the log output.
The log output includes useful metadata like the current timestamp, log
level, and fiber ID, making it suitable for debugging and tracking purposes.
This function does not interrupt or alter the effect's execution flow.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
const provide: <Fetch.Fetch, never, never>(layer:Layer<Fetch.Fetch, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Fetch.Fetch>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []
@see ― provideService for providing a service to an effect.
@since ― 2.0.0
provide(
const mockLayer:Layer<Fetch.Fetch, never, never>
mockLayer), // ◀︎── Uses mock instead of real fetch
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?:AbortSignal|undefined;
} |undefined) => Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
Example (Running a Successful Effect as a Promise)
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
@param ― searchString search string
@param ― position If position is undefined, 0 is assumed, so as to search all of the String.
Creates an Effect that represents a recoverable error.
When to Use
Use this function to explicitly signal an error in an Effect. The error
will keep propagating unless it is handled. You can handle the error with
functions like
catchAll
or
catchTag
.
Example (Creating a Failed Effect)
import { Effect } from"effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
newError("Operation failed due to network error")
)
@see ― succeed to create an effect that represents a successful value.
Represents general errors that occur during the fetch operation.
Depending on the nature of the error, it may make sense to retry the operation.
import {
import Fetch
Fetch } from'fx-fetch';
type
type MyType = Fetch.FetchError
MyType=
import Fetch
Fetch.
classFetchError
Wrap for TypeError. It is al most impossible to categorize all possible errors. Because it depends on the environment (browser, nodejs, deno, etc), location, network, etc.
Possible reasons:
Blocked by a permissions policy.
Invalid header name.
Invalid header value. The header object must contain exactly two elements.
Invalid URL or scheme, or using a scheme that fetch does not support, or using a scheme that is not supported for a particular request mode.
URL includes credentials.
Invalid referrer URL.
Invalid modes (navigate and websocket).
If the request cache mode is "only-if-cached" and the request mode is other than "same-origin".
If the request method is an invalid name token or one of the forbidden headers ('CONNECT', 'TRACE' or 'TRACK').
If the request mode is "no-cors" and the request method is not a CORS-safe-listed method ('GET', 'HEAD', or 'POST').
If the request method is 'GET' or 'HEAD' and the body is non-null or not undefined.