Custom Scalars

GraphQL's built-in scalars are useful but do not cover every domain value.

A custom scalar can represent a domain-specific leaf value such as:

scalar DateTime
scalar JSON
scalar URL
scalar EmailAddress

For example:

scalar DateTime

type User {
  id: ID!
  createdAt: DateTime!
}

The server implementation defines how the custom scalar serializes output and parses input.

Conceptually, a DateTime scalar may accept ISO-formatted timestamps and serialize internal date objects into a consistent wire representation.

Custom scalars are useful when the semantic type matters. However, creating a scalar for every primitive value can make a schema unnecessarily complicated.

A scalar should have clearly defined semantics. For example, if DateTime accepts multiple unrelated formats, different clients may interpret the same API inconsistently.

Custom scalar validation should be strict enough to prevent ambiguous values and should produce predictable serialization.

Custom DateTime Scalar Concept
scalar DateTime

type Event {
  id: ID!
  name: String!
  startsAt: DateTime!
}

input CreateEventInput {
  name: String!
  startsAt: DateTime!
}
💡 The DateTime scalar communicates that startsAt is not arbitrary text. The server implementation is responsible for parsing client input and serializing output according to a documented format.
Key Takeaways
  • Custom scalars represent domain-specific leaf values.
  • Serialization and input parsing belong to the scalar implementation.
  • Custom scalar formats should be documented and predictable.
  • Do not create custom scalars without a meaningful semantic benefit.
Knowledge Check

What is a primary reason to create a custom GraphQL scalar?