Skip to content

Canonical Codecs

Canonical codec derivation preserves a schema's decoded type while selecting a standard external representation for JSON, string trees, or structural updates. Derivation returns a codec; decoding and encoding remain separate calls. Plain builders follow the call rules.

JSON, string-tree, and isomorphism codecs

const AuditRecord = Schema.Struct({
  created: Schema.Date,
  sequence: Schema.BigInt,
  labels: Schema.Array(Schema.String)
})
 
effect function encodeAudit(input: unknown) {
  const value = try Schema.decodeUnknownEffect(AuditRecord)(input)
  const jsonCodec = Schema.toCodecJson(AuditRecord)
  return try Schema.encodeEffect(jsonCodec)(value)
}
// The JSON representation contains date and bigint strings.
// Run in an effect function:
//   {
//     const jsonValue = try encodeAudit({ created: new Date("2026-01-02T00:00:00Z"), sequence: 12n, labels: ["fragile"] })
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
{"created":"2026-01-02T00:00:00.000Z","sequence":"12","labels":["fragile"]}

Schema.toCodecJson recursively maps domain types to JSON values (preserving explicit encodings, such as epoch-millisecond dates). Wrap with Schema.fromJsonString when you need serialized JSON text.

const Search = Schema.Struct({
  offset: Schema.Int,
  archived: Schema.Boolean,
  labels: Schema.Array(Schema.String)
})
 
effect function encodeSearch() {
  const codec = try sync(() => Schema.toCodecStringTree(Search))
  return try Schema.encodeEffect(codec)({ offset: 20, archived: false, labels: ["large"] })
}
// { offset: "20", archived: "false", labels: ["large"] }
// Run in an effect function:
//   {
//     const jsonValue = try encodeSearch()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
{"offset":"20","archived":"false","labels":["large"]}

Schema.toCodecStringTree keeps object and array structure while encoding leaves as strings (and permitting undefined), fitting query strings, forms, and config providers.

class Slot extends Schema.Class<Slot>("Slot")({
  row: Schema.Int,
  column: Schema.Int
}) {}
 
effect function slotRepresentation(input: unknown) {
  const slot = try Schema.decodeUnknownEffect(Slot)(input)
  const codec = Schema.toCodecIso(Slot)
  const structural = try Schema.encodeEffect(codec)(slot)
  return try Schema.decodeUnknownEffect(codec)(structural)
}
// Run in an effect function:
//   const slot = try slotRepresentation({ row: 2, column: 3 })
//   try Console.log(slot instanceof Slot, slot.row, slot.column)
true 2 3

Schema.toCodecIso maps domain values (such as Schema.Class instances) to plain structural objects and back without promising reference identity.

Hooks for custom declarations

class DepotRef {
  constructor(readonly region: string, readonly number: number) {}
}
 
const DepotRefSchema = Schema.instanceOf(DepotRef, {
  toCodecJson: () => Schema.link<DepotRef>()(
    Schema.Struct({ region: Schema.String, number: Schema.Int }),
    SchemaTransformation.transform({
      decode: (data) => new DepotRef(data.region, data.number),
      encode: (ref) => ({ region: ref.region, number: ref.number })
    })
  )
})
 
effect function encodeDepot() {
  const codec = try sync(() => Schema.toCodecStringTree(DepotRefSchema))
  return try Schema.encodeEffect(codec)(new DepotRef("nw", 14))
}
// { region: "nw", number: "14" }
// Run in an effect function:
//   {
//     const jsonValue = try encodeDepot()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
{"region":"nw","number":"14"}

Hook fallback order for opaque declarations:

  • JSON: toCodecJson -> toCodec -> unconstrained JSON fallback.
  • StringTree: toCodecStringTree -> toCodecJson -> toCodec -> throws.
  • Iso: toCodecIso -> toCodec -> keeps declaration as-is.

Returning undefined from a JSON or StringTree hook marks the declaration as already canonical. Hooks cannot introduce services outside the codec's service type; Schema.toIso runs synchronously.

Relation to JSON Schema

function describeDepotJson() {
  return Schema.toJsonSchemaDocument(DepotRefSchema)
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(describeDepotJson())))
{"dialect":"draft-2020-12","schema":{"type":"object","properties":{"region":{"type":"string"},"number":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991}},"required":["region","number"],"additionalProperties":true},"definitions":{}}

Schema.toJsonSchemaDocument derives toCodecJson first and describes its encoded side. A single toCodecJson hook therefore defines both runtime JSON encoding and exported JSON Schema; an unhooked opaque declaration exports an unconstrained schema.


The matching Effect page: effect.website/docs/v4/schema/canonical-codecs