PureScript Row Polymorphism: Practical Patterns for Evolving API Boundaries
PureScript's row polymorphism lets you build reusable, versioned API codecs from shared field groups — without inheritance or dynamic typing. This post shows practical patterns for composable codecs, schema migration, and pagination wrappers, plus the trade-offs you'll hit in production.
11 Feb 2026, 02:34 UTC

The Problem: Rigid Types vs. Dynamic Objects at API Boundaries
When your API evolves — adding optional fields, versioning responses, sharing common metadata across endpoints — you face a familiar tension. Define separate types for every version and you drown in boilerplate. Reach for Foreign.Object or Json.Value and you lose the compiler's help exactly where you need it most: at the serialization boundary.
PureScript's row polymorphism offers a third path. It lets you write functions that operate on any record containing at least these fields, then compose those functions into codecs that grow with your schema. This post shows how to structure API boundaries around extensible records, derive versioned codecs from a shared base, and migrate between versions without duplicating logic.
Row Polymorphism in Five Lines
A row-polymorphic function accepts a record constrained by a row variable r:
getId :: forall r a. IsSymbol "id" r => SProxy "id" -> Record (id :: a | r) -> a
getId _ rec = rec.id
The constraint IsSymbol "id" r (satisfied via RowCons) guarantees the record has an id field of type a. The function works on { id :: Int, name :: String }, { id :: String, createdAt :: DateTime }, or any record with an id field — no inheritance, no wrapper types.
At the API boundary this means: write one pagination decoder, one timestamp extractor, one authentication header parser, and reuse them across every endpoint that carries those fields.
Composing Codecs from Shared Field Groups
Libraries like argonaut-codecs and simple-json derive EncodeJson/DecodeJson instances from record types. Row-polymorphic combinators let you build partial codecs for common field groups and extend them per endpoint.
Define a base row for audit fields:
type BaseFields r = ( createdAt :: DateTime
, updatedAt :: DateTime
| r )
baseCodec :: forall r.
( EncodeJson (Record (BaseFields r))
, DecodeJson (Record (BaseFields r))
) =>
JsonCodec (Record (BaseFields r))
baseCodec = codec
where
codec = object $ do
createdAt := field "createdAt" dateTimeCodec
updatedAt := field "updatedAt" dateTimeCodec
Now extend it for a user endpoint:
type UserV1 = BaseFields ( name :: String )
type UserV2 = BaseFields ( name :: String
, email :: Maybe String )
userV1Codec :: JsonCodec UserV1
userV1Codec = baseCodec \\ object (name := field "name" stringCodec)
userV2Codec :: JsonCodec UserV2
userV2Codec = baseCodec \\ object (name := field "name" stringCodec
\\ email := optionalField "email" stringCodec)
The \\ operator (from argonaut-codecs) merges codecs. Each version gets the audit fields automatically; adding email in v2 doesn't touch the base logic.
Schema Evolution: Migration Between Row Types
When you need to transform v1 payloads to v2 (or strip v2 down for a v1 client), write migration functions that operate on the row structure directly:
v1ToV2 :: UserV1 -> UserV2
v1ToV2 rec =
Record.insert (SProxy :: SProxy "email") nothing rec
v2ToV1 :: UserV2 -> UserV1
v2ToV1 rec =
Record.delete (SProxy :: SProxy "email") rec
Record.insert and Record.delete (from Prim.Row) are type-safe: the compiler verifies the field exists (or doesn't) in the source row. If you later add phone :: Maybe String to v2, v2ToV1 still compiles — it only removes email.
For more complex migrations (renaming, restructuring), pattern-match on the concrete record and reconstruct:
renameEmailToContact :: UserV2 -> UserV2
renameEmailToContact rec =
let email = rec.email
in Record.delete (SProxy :: SProxy "email")
$ Record.insert (SProxy :: SProxy "contactEmail") email rec
Worked Example: Paginated Response Wrapper
Many APIs wrap lists in a pagination envelope. With row polymorphism the envelope becomes a reusable codec parameterized by the item row:
type PaginationMeta = ( total :: Int
, page :: Int
, pageSize :: Int )
type Paginated itemRow = BaseFields ( items :: Array (Record itemRow)
, meta :: PaginationMeta )
paginatedCodec :: forall itemRow.
JsonCodec (Record itemRow) ->
JsonCodec (Record (Paginated itemRow))
paginatedCodec itemCodec =
baseCodec \\ object ( items := field "items" (arrayCodec itemCodec)
\\ meta := field "meta" paginationMetaCodec )
-- Usage:
userListCodec :: JsonCodec (Record (Paginated (name :: String)))
userListCodec = paginatedCodec (object (name := field "name" stringCodec))
Change the item codec, the pagination codec stays the same. Add email to the item row and only the item codec changes.
Trade-offs and Limitations
- Error messages can be opaque. When row unification fails, the compiler may report a constraint like
RowCons "email" (Maybe String) rwithout pointing to the exact call site. Mitigate by adding explicit type annotations at module boundaries:decodeUserV2 :: String -> Either DecodeError UserV2. - Not structural subtyping. A function requiring
name :: Stringrejects{ name :: Int }even though the field exists. The type must unify exactly — this is intentional but surprises developers coming from TypeScript or Go. - Deeply nested rows hit compiler limits. Constraints like
RowToList,RowConschains, or recursive row types can slow type checking. Prefer flat records ornewtypewrappers for complex hierarchies. - FFI requires explicit serialization. PureScript records do not automatically map to JavaScript objects with the same shape. Use
Foreign.Objectorsimple-json'stoForeign/fromForeignwhen crossing the FFI boundary.
Try It in a Spago Project
spago initin a fresh directory.- Add dependencies to
spago.dhall:dependencies = [ "argonaut-codecs", "simple-json", "foreign-object", "datetime", "maybe", "arrays", "record" ] - Create
src/Api/Types.purswith theBaseFields,UserV1,UserV2, andPaginatedtypes above. - Create
src/Api/Codecs.purswith the codec definitions and migration functions. - Run
spago repland test round-trips:> import Api.Types > import Api.Codecs > import Data.Argonaut.Codec as Codec > let v1 = { createdAt: _, updatedAt: _, name: "Ada" } > -- typed hole shows inferred row > Codec.encodeJson userV1Codec v1 > Codec.decodeJson userV2Codec "{ \"createdAt\": \"2024-01-01T00:00:00Z\", \"updatedAt\": \"2024-01-01T00:00:00Z\", \"name\": \"Ada\", \"email\": null }" - Inspect inferred rows in VS Code with the PureScript extension: type
myFn { createdAt: _, name: "test" }and hover the hole. - For verbose unification traces:
spago build --purs-args "--verbose-errors".
Closing: Start Small, Extend Incrementally
You don't need to rewrite your entire API layer. Pick one endpoint family that shares timestamps or pagination. Define a BaseFields row, derive a partial codec, and extend it for two versions. Write a single migration function between them. The compiler will guide you through the row constraints — and the next time you add a field, you'll change one codec instead of five.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.