Custom Scalars
You'll learn to
- -Define a custom scalar with serialize and parse functions, and see bad input rejected centrally
- -Say what each of serialize, parseValue and parseLiteral is for
- -Decide when a custom scalar is worth it and when a documented String is enough
GraphQL's built-in scalars, Int, Float, String, Boolean and ID, do not cover every value an API needs to represent precisely. A date, a URL or an email address can be sent as a String, but that throws away the chance to validate and document the value's real shape in the schema.
An Analogy: The Passport Photo Booth
A passport photo has a strict format: size, background, face position. If you let people hand in any photo, every office that receives one must check it for itself and gets it wrong sometimes. A photo booth that only produces the right format checks it once, at the door. A custom scalar is the booth.
Defining a Custom Scalar
scalar DateTime
type Order {
id: ID!
placedAt: DateTime!
}A scalar needs three functions. serialize turns the internal value into the wire format, for responses. parseValue turns wire format into the internal value, for variables. parseLiteral does the same for values written directly inside the query text. Once defined, DateTime behaves like a built-in scalar, with validation and consistent formatting enforced in one place, instead of every resolver that handles a date re-implementing its own parsing.
The demo builds a DateTime scalar. It parses a good value, serializes it back, and rejects two bad ones. Then it shows what happens when the same field is a plain String.
When a Custom Scalar Is Worth It
- -The value has a well-defined format where "is this valid?" is a real, checkable question: dates, URLs, email addresses, currency amounts.
- -The same kind of value appears across many fields and types, so central validation and formatting pay for the setup.
- -Clients benefit from knowing the field is a DateTime and not an opaque String, for their own type generation and form checks.
For a one-off, rarely used field where the "format" is really just documentation, a plain String with a clear description is often simpler and perfectly adequate. A custom scalar earns its cost when validation and reuse matter, not as the default for everything that is not a number or a boolean.
A custom scalar's validation runs as part of GraphQL's own request parsing, before any resolver code. An invalid DateTime is rejected by the framework itself, not quietly passed through to a resolver that might not check it.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Design Custom Scalars Lab in the API Design Lab's GraphQL Mastery act.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!