Creating Services with Effect v4

VerifiedSafe

Learn to create services using Context.Service, IdentityComposer keys, and Layer composition in Effect v4. Covers dependency injection and best practices for consuming services.

Sby Skills Guide Bot
DevelopmentAdvanced
8/11/2026
Claude CodeCursorWindsurfCopilotCodex
#effect-ts#dependency-injection#typescript#service-layer#context-service

Recommended for

Automated summary

Walks through creating Effect v4 services with Context.Service, branded identity keys from IdentityComposer, and Layer composition for dependency injection.

Strengths

  • Clear five-step sequence from identity key creation to service consumption
  • Explains the reasoning behind each choice (class syntax, Layer.effect, yield* over .use())
  • Handles edge cases: parameterized constructors with Effect.fn, callback-only APIs, MemoMap deduplication
  • Ends with a verification checklist covering compilation and removal of legacy APIs

Limitations

  • Tightly coupled to the internal @beep/identity/packages package, which is not publicly available
  • Assumes existing familiarity with Effect primitives (Effect.gen, Layer, Schema) and offers little background
  • Targets Effect v4 specifically, whose APIs differ from earlier versions
When to use it

Reach for this when adding a new Effect service or rewiring a dependency graph with Layers in an Effect v4 codebase.

When not to use it

Skip it on pre-v4 Effect versions or in projects that do not use the @beep identity package.

Security analysis

Safe
Quality score92/100

The skill provides declarative guidance and code examples for defining services in the Effect library. It does not instruct the execution of shell commands, network operations, destructive actions, or exfiltration. No tools are declared, and the content is purely educational with no meaningful execution risk.

No concerns found

How this analysis is made

Examples

New service definition
Create a new Effect v4 Notifications service using Context.Service with an identity key from $I`Notifications`, an explicit constructor effect, and a static Layer that provides AppConfig.
Wire the dependency graph
Compose Notifications.layer and UserService.layer into an AppLayer with Layer.mergeAll and provide it at the application entry point.
Migrate away from legacy tags
Refactor this service so it no longer uses Context.Tag, Effect.Service, or .Default, and consumes dependencies with yield* ServiceName instead of .use().

name: effect-services description: > Creating services with Context.Service, IdentityComposer keys, and Layer composition. Trigger on: new service, service definition, Layer wiring, dependency injection, Context. version: 0.1.0 status: active

Creating a Service (Effect v4)

Step 1: Create the Identity

Every service needs a unique key from @beep/identity/packages. Never use plain strings.

// WHY: IdentityComposer produces branded strings with compile-time path validation.
// The tagged template literal validates segment characters at runtime.
import { $PackageNameId } from "@beep/identity/packages"

const $I = $PackageNameId.create("relative/path/to/file/from/package/src")
//                        ↑ package composer      ↑ file-local composer

Step 2: Define the Service Class

Use Context.Service<Self, Shape>()(identityKey). Note: type params FIRST, then key in second call.

import { Effect, Context, Layer } from "effect"

// WHY: Class syntax gives you a nominal type (Self) + the service shape in one declaration.
// The $I template tag produces a branded IdentityString under the file-local path.
class Notifications extends Context.Service<Notifications, {
  readonly notify: (msg: string) => Effect.Effect<void>
}>()($I`Notifications`) {}

Step 3: Add the Constructor

Use an explicit constructor effect and Layer.effect(...). Parameterized or reusable constructor functions should be named Effect.fn("Service.make"). Zero-arg constructor values may stay Effect.gen(...).pipe(Effect.withSpan("Service.make")) to avoid immediate Effect.fn() IIFEs.

const makeNotifications = Effect.gen(function*() {
  const config = yield* AppConfig
  return {
    notify: Effect.fn("Notifications.notify")(function*(msg: string) {
      yield* Effect.annotateCurrentSpan({ message_length: msg.length })
      yield* Effect.logInfo({ message: "notification emitted" }).pipe(
        Effect.annotateLogs({ service: "notifications" })
      )
      return yield* Effect.log(`[${config.prefix}] ${msg}`)
    })
  }
}).pipe(Effect.withSpan("Notifications.make"))

class Notifications extends Context.Service<Notifications, {
  readonly notify: (msg: string) => Effect.Effect<void>
}>()($I`Notifications`) {
  // WHY: Explicit layer construction. Wire deps with Layer.provide, not `dependencies`.
  static layer = Layer.effect(this, makeNotifications).pipe(
    Layer.provide(AppConfig.layer)
  )
}

Step 4: Consume the Service

Prefer yield* over .use() — it makes dependencies visible at the call site.

Exception: in callback-only APIs (for example SchemaTransformation.transform* decode/encode callbacks) where yield* is not available, use Context.Service.use(...) directly.

// WHY: yield* in Effect.fn makes the Notifications dependency appear in the R channel.
const sendWelcome = Effect.fn("sendWelcome")(function*(userId: string) {
  const notifications = yield* Notifications
  yield* notifications.notify(`Welcome ${userId}`)
})

const JsoncTextToUnknown = S.String.pipe(
  S.decodeTo(
    S.Unknown,
    SchemaTransformation.transformOrFail({
      decode: (content) => JsoncCodecService.use((service) => service.parseUnknown(content)),
      encode: (value) => Effect.fail(`unsupported encode: ${value}`)
    })
  )
)

Step 5: Compose Layers

Wire the full dependency graph at the application entry point.

// WHY: MemoMap deduplicates layers by reference. Same const = built once.
// No intermediate bundles needed — just provide each layer directly.
const AppLayer = Layer.mergeAll(
  Notifications.layer,
  UserService.layer
)

const program = myEffect.pipe(Effect.provide(AppLayer))

Verify

  1. yield* ServiceName compiles — the R channel includes the service.
  2. Layer.effect(Service, constructorEffect) compiles — shape matches.
  3. No Context.Tag, Effect.Tag, Effect.Service, or .Default anywhere in your code.
  4. All service keys use $I\Name`` template tags, not string literals.
  5. Reusable service methods use named Effect.fn("Service.method").
  6. Constructor flows are observable with Effect.withSpan(...) plus structured log annotations where the path matters.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/creating-services-with-effect-v4-mso6xfjl' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/creating-services-with-effect-v4-mso6xfjl/download' --output '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md.part' && mv '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md.part' '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && test -s '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/effect-services' && cp -R '.skill-downloads/creating-services-with-effect-v4-mso6xfjl' '.claude/skills/effect-services'

Cursor
test -f '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && test -s '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/effect-services' && cp -R '.skill-downloads/creating-services-with-effect-v4-mso6xfjl' '.cursor/skills/effect-services'

Codex
test -f '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && test -s '.skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/effect-services' && cp -R '.skill-downloads/creating-services-with-effect-v4-mso6xfjl' '.agents/skills/effect-services'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/creating-services-with-effect-v4-mso6xfjl'

openskills read 'creating-services-with-effect-v4-mso6xfjl'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/creating-services-with-effect-v4-mso6xfjl/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills