| name | effect-ts |
| description | This skill should be used when the user asks about Effect-TS patterns, services, layers, error handling, service composition, or writing/refactoring code that imports from 'effect'. Also covers Effect + Next.js integration with @prb/effect-next. |
Effect-TS Expert
Expert guidance for functional programming with the Effect library, covering error handling, dependency injection,
composability, and testing patterns.
Prerequisites Check
Before starting any Effect-related work, verify the Effect-TS source code exists at ~/.effect.
If missing, stop immediately and inform the user. Clone it before proceeding:
git clone https://github.com/Effect-TS/effect.git ~/.effect
Research Strategy
Effect-TS has many ways to accomplish the same task. Proactively research best practices using the Task tool to spawn
research agents when working with Effect patterns, especially for moderate to high complexity tasks.
Research Sources (Priority Order)
-
Codebase Patterns First — Examine similar patterns in the current project before implementing. If Effect patterns
exist in the codebase, follow them for consistency. If no patterns exist, skip this step.
-
Effect Source Code — For complex type errors, unclear behavior, or implementation details, examine the Effect
source at ~/.effect/packages/effect/src/. This contains the core Effect logic and modules.
When to Research
HIGH Priority (Always Research):
- Implementing Services, Layers, or complex dependency injection
- Error handling with multiple error types or complex error hierarchies
- Stream-based operations and reactive patterns
- Resource management with scoped effects and cleanup
- Concurrent/parallel operations and performance-critical code
- Testing patterns, especially unfamiliar test scenarios
MEDIUM Priority (Research if Complex):
- Refactoring imperative code (try-catch, promises) to Effect patterns
- Adding new service dependencies or restructuring service layers
- Custom error types or extending existing error hierarchies
- Integrations with external systems (databases, APIs, third-party services)
Research Approach
- Spawn multiple concurrent Task agents when investigating multiple related patterns
- Focus on finding canonical, readable, and maintainable solutions rather than clever optimizations
- Verify suggested approaches against existing codebase patterns for consistency (if patterns exist)
- When multiple approaches are possible, research to find the most idiomatic Effect-TS solution
Codebase Pattern Discovery
When working in a project that uses Effect, check for existing patterns before implementing new code:
- Search for Effect imports — Look for files importing from
'effect' to understand existing usage
- Identify service patterns — Find how Services and Layers are structured in the project
- Note error handling conventions — Check how errors are defined and propagated
- Examine test patterns — Look at how Effect code is tested in the project
If no Effect patterns exist in the codebase, proceed using canonical patterns from the Effect source and examples.
Do not block on missing codebase patterns.
Effect Principles
Apply these core principles when writing Effect code:
Error Handling
- Use Effect's typed error system instead of throwing exceptions
- Define descriptive error types with proper error propagation
- Use
Effect.fail, Effect.catchTag, Effect.catchAll for error control flow
- See
./references/CRITICAL_RULES.md for forbidden patterns
Dependency Injection
- Implement dependency injection using Services and Layers
- Define services with
Context.Tag
- Compose layers with
Layer.merge, Layer.provide
- Use
Effect.provide to inject dependencies
Composability
- Leverage Effect's composability for complex operations
- Use appropriate constructors:
Effect.succeed, Effect.fail, Effect.tryPromise, Effect.try
- Apply proper resource management with scoped effects
- Chain operations with
Effect.flatMap, Effect.map, Effect.tap
Code Quality
- Write type-safe code that leverages Effect's type system
- Use
Effect.gen for readable sequential code
- Implement proper testing patterns using Effect's testing utilities
- Prefer
Effect.fn() for automatic telemetry and better stack traces
Critical Rules
Read and internalize ./references/CRITICAL_RULES.md before writing any Effect code. Key guidelines:
- INEFFECTIVE: try-catch in Effect.gen (Effect failures aren't thrown)
- AVOID: Type assertions (as never/any/unknown)
- RECOMMENDED:
return yield* pattern for errors (makes termination explicit)
Common Failure Modes
Quick links to patterns that frequently cause issues:
- SubscriptionRef version mismatch —
unsafeMake is not a function → Quick Reference
- Cancellation vs Failure — Interrupts aren't errors → Error Taxonomy
- Option vs null — Use Option internally, null at boundaries → OPTION_NULL.md
- Stream backpressure — Infinite streams hang → STREAMS.md
Explaining Solutions
When providing solutions, explain the Effect-TS concepts being used and why they're appropriate for the specific use
case. If encountering patterns not covered in the documentation, suggest improvements while maintaining consistency with
existing codebase patterns (when they exist).
Quick Reference
Creating Effects
Effect.succeed(value)
Effect.fail(error)
Effect.tryPromise(fn)
Effect.try(fn)
Effect.sync(fn)
Composing Effects
Effect.flatMap(effect, fn)
Effect.map(effect, fn)
Effect.tap(effect, fn)
Effect.all([...effects])
Effect.forEach(items, fn)
Effect.all([e1, e2, e3], { mode: "validate" })
Effect.partition([e1, e2, e3])
Error Handling
class UserNotFoundError extends Data.TaggedError("UserNotFoundError")<{
userId: string
}> {}
Effect.gen(function* () {
if (!user) {
return yield* new UserNotFoundError({ userId })
}
})
Effect.catchTag(effect, tag, fn)
Effect.catchAll(effect, fn)
Effect.result(effect)
Effect.orElse(effect, alt)
Error Taxonomy
Categorize errors for appropriate handling:
| Category | Examples | Handling |
|---|
| Expected Rejections | User cancel, deny | Graceful exit, no retry |
| Domain Errors | Validation, business rules | Show to user, don't retry |
| Defects | Bugs, assertions | Log + alert, investigate |
| Interruptions | Fiber cancel, timeout | Cleanup, may retry |
| Unknown/Foreign | Thrown exceptions | Normalize at boundary |
const safeBoundary = Effect.catchAllDefect(effect, (defect) =>
Effect.fail(new UnknownError({ cause: defect }))
)
Effect.catchTag(effect, "UserCancelledError", () => Effect.succeed(null))
Effect.onInterrupt(effect, () => Effect.log("Operation cancelled"))
Pattern Matching (Match Module)
Default branching tool for tagged unions and complex conditionals.
import { Match } from "effect"
const handleError = Match.type<AppError>().pipe(
Match.tag("UserCancelledError", () => null),
Match.tag("ValidationError", (e) => e.message),
Match.tag("NetworkError", () => "Connection failed"),
Match.exhaustive
)
Effect.catchAll(effect, (error) =>
Match.value(error).pipe(
Match.tag("A", handleA),
Match.tag("B", handleB),
Match.tag("C", handleC),
Match.exhaustive
)
)
const describe = Match.value(status).pipe(
Match.when("pending", () => "Loading..."),
Match.when("success", () => "Done!"),
Match.orElse(() => "Unknown")
)
Services and Layers
class MyService extends Context.Tag("MyService")<MyService, { ... }>() {}
const MyServiceLive = Layer.succeed(MyService, { ... })
Effect.provide(effect, MyServiceLive)
class UserRepo extends Effect.Service<UserRepo>()("UserRepo", {
effect: Effect.gen(function* () {
const db = yield* Database
return { findAll: db.query("SELECT * FROM users") }
}),
dependencies: [Database.Default],
accessors: true
}) {}
Effect.provide(effect, UserRepo.Default)
class ConfiguredApi extends Effect.Service<ConfiguredApi>()("ConfiguredApi", {
effect: (config: { baseUrl: string }) =>
Effect.succeed({ fetch: (path: string) => `${config.baseUrl}/${path}` })
}) {}
class SpecialNumber extends Context.Reference<SpecialNumber>()(
"SpecialNumber",
{ defaultValue: () => 2048 }
) {}
function effectHandler<I, A, E, R>(service: Context.ReadonlyTag<I, Effect.Effect<A, E, R>>) {
}
Generator Pattern
Effect.gen(function* () {
const a = yield* effectA;
const b = yield* effectB;
if (error) {
return yield* Effect.fail(new MyError());
}
return result;
});
const fetchUser = Effect.fn("fetchUser")(function* (id: string) {
const db = yield* Database
return yield* db.query(id)
})
Resource Management
Effect.acquireUseRelease(acquire, use, release)
Effect.scoped(effect)
Effect.addFinalizer(cleanup)
Duration
Effect accepts human-readable duration strings anywhere a DurationInput is expected:
Duration.toMillis("5 minutes")
Duration.toMillis("1 minute")
Duration.toMillis("30 seconds")
Duration.toMillis("100 millis")
Duration.toMillis(Duration.minutes(5))
Scheduling
Effect.retry(effect, Schedule.exponential("100 millis"))
Effect.repeat(effect, Schedule.fixed("1 second"))
Schedule.compose(s1, s2)
State Management
Ref.make(initialValue)
Ref.get(ref)
Ref.set(ref, value)
Deferred.make<E, A>()
SubscriptionRef (Reactive References)
SubscriptionRef.make(initial)
SubscriptionRef.get(ref)
SubscriptionRef.set(ref, value)
SubscriptionRef.changes(ref)
const ref = yield* SubscriptionRef.make<User | null>(null)
Concurrency
Effect.fork(effect)
Fiber.join(fiber)
Effect.race(effect1, effect2)
Effect.all([...effects], { concurrency: "unbounded" })
Configuration & Environment Variables
import { Config, ConfigProvider, Effect, Layer, Redacted } from "effect"
const port = Config.number("PORT")
const host = Config.string("HOST").pipe(
Config.withDefault("localhost")
)
const apiKey = Config.redacted("API_KEY")
const secret = Redacted.value(yield* apiKey)
const dbConfig = Config.all({
host: Config.string("HOST"),
port: Config.number("PORT"),
name: Config.string("NAME"),
}).pipe(Config.nested("DATABASE"))
const program = Effect.gen(function* () {
const p = yield* Config.number("PORT")
const key = yield* Config.redacted("API_KEY")
return { port: p, apiKey: Redacted.value(key) }
})
const customProvider = ConfigProvider.fromMap(
new Map([["PORT", "3000"], ["API_KEY", "secret"]])
)
const withCustomConfig = Effect.provide(
program,
Layer.setConfigProvider(customProvider)
)
const validPort = Config.number("PORT").pipe(
Config.validate({
message: "Port must be between 1 and 65535",
validation: (n) => n >= 1 && n <= 65535,
})
)
Array Operations
import { Array as Arr, Order } from "effect"
Arr.sort([3, 1, 2], Order.number)
Arr.sort(["b", "a", "c"], Order.string)
Arr.sort(new Set([3n, 1n, 2n]), Order.bigint)
Arr.sortWith(users, (u) => u.age, Order.number)
Arr.sortBy(
users,
Order.mapInput(Order.number, (u: User) => u.age),
Order.mapInput(Order.string, (u: User) => u.name)
)
Utility Functions
import { constVoid as noop } from "effect/Function"
noop()
Effect.tap(effect, noop)
Promise.catch(noop)
eventEmitter.on("event", noop)
Deprecations
BigDecimal.fromNumber — Use BigDecimal.unsafeFromNumber instead (3.11.0+)
Schema.annotations() — Now removes previously set identifier annotations; identifiers are tied to the schema's
ast reference only (3.17.10)
Additional Resources
Local Effect Resources
~/.effect/packages/effect/src/ — Core Effect modules and implementation
External Resources
Reference Files
./references/CRITICAL_RULES.md — Forbidden patterns and mandatory conventions
./references/EFFECT_ATOM.md — Effect-Atom reactive state management for React
./references/NEXT_JS.md — Effect + Next.js 15+ App Router integration patterns
./references/OPTION_NULL.md — Option vs null boundary patterns
./references/STREAMS.md — Stream patterns and backpressure gotchas
./references/TESTING.md — Vitest deterministic testing patterns