Scalar types and custom scalars

Intermediate · 10 min

The five built-in GraphQL scalars, how input and output coercion works, and how to write a DateTime custom scalar with serialize, parseValue and parseLiteral.

Before thisSchema definition language

Ben Awad · 10 min

Scalar types and custom scalars

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ben AwadReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Scalars are the leaves of a query: the built-in ones are Int, Float, String, Boolean, and ID, and a selection set cannot go below them.
  • Int is a signed 32-bit integer, so a resolver returning 2147483648 for an Int field fails with an error instead of being rounded.
  • A custom scalar has three coercion functions: serialize for output, parseValue for variables, and parseLiteral for values written inline in the query.
  • Custom scalars are how dates, URLs, and JSON are carried; the wire format is still a string or number, and the scalar decides how it is validated.
  • Annotate a custom scalar with a description and specifiedBy so clients know the format they must send.

Leaves of the query

Every GraphQL query ends in scalars. A field whose type is an object must have a selection set beneath it. A field whose type is a scalar cannot. If you write { book { title { x } } } the server rejects it: “Field “title” must not have a selection since type “String!” has no subfields.” The scalar is where the graph stops and plain data begins.

The specification gives you five.

Scalar Represents
Int signed 32-bit integer
Float double-precision number
String UTF-8 text
Boolean true or false
ID a unique identifier, serialised as a string

ID is a string in disguise. It signals “this is an opaque key, not text to display”, and accepts an integer input too, converting it. I sent book(id: 10) to a field of type ID! and it was accepted.

The type checks are strict

Run these against a graphql-js 17.1.0 schema where i(x: Int) echoes its argument. Each result is real output:

Query Result
{ i(x: 1.5) } Int cannot represent non-integer value: 1.5
{ i(x: "3") } Int cannot represent non-integer value: “3”
{ i(x: 3000000000) } Int cannot represent non 32-bit signed integer value: 3000000000

Returning too large a value from a resolver fails the same way, with a field error and the field becoming null. The practical consequence: store big counters or database ids that overflow 32 bits as String, ID, or a custom scalar such as BigInt.

There is no built-in date type. That is the gap custom scalars fill.

Writing a custom scalar

A scalar has three jobs because a value enters and leaves a GraphQL system three ways.

  1. serialize: output. Your resolver returns an internal value (a Date); this turns it into what goes in the response JSON.
  2. parseValue: input from variables. The client sent JSON, so you get a string or number.
  3. parseLiteral: input written inline in the query. You receive a syntax node (an AST node), not a plain value, so check its kind.

Here is DateTime built that way, run on graphql-js 17.1.0:

import { GraphQLScalarType, Kind } from 'graphql'

export const DateTime = new GraphQLScalarType({
  name: 'DateTime',
  description: 'ISO 8601 timestamp',
  specifiedByURL: 'https://scalars.graphql.org/chillicream/date-time.html',
  serialize(v) {
    if (!(v instanceof Date)) throw new TypeError('DateTime cannot serialize a non-Date')
    return v.toISOString()
  },
  parseValue(v) {
    if (typeof v !== 'string' || Number.isNaN(Date.parse(v)))
      throw new TypeError('DateTime must be an ISO string')
    return new Date(v)
  },
  parseLiteral(ast) {
    if (ast.kind !== Kind.STRING || Number.isNaN(Date.parse(ast.value)))
      throw new TypeError('DateTime must be an ISO string')
    return new Date(ast.value)
  },
})

With fields now: DateTime (returns a Date), plus(from: DateTime): DateTime (adds a day), and a deliberately wrong bad: DateTime (returns 'yesterday'):

{ now }
 => {"data":{"now":"2026-11-22T10:00:00.000Z"}}
{ plus(from: "2026-11-22T10:00:00Z") }
 => {"data":{"plus":"2026-11-23T10:00:00.000Z"}}
{ plus(from: "nope") }
 => Expected value of type "DateTime", but encountered error "DateTime must be an ISO string"; found: "nope".
{ bad }
 => DateTime cannot serialize a non-Date   (data: {"bad": null})

And with a variable { "d": 5 } the message is Variable "$d" has invalid value: ... DateTime must be an ISO string; found: 5. That is parseValue rejecting it; a literal goes through parseLiteral. If you implement only one of them, the other path misbehaves. That is the usual bug with hand-written scalars.

Printing the schema shows how clients see it:

"""ISO 8601 timestamp"""
scalar DateTime @specifiedBy(url: "https://scalars.graphql.org/chillicream/date-time.html")

The @specifiedBy directive points at a written format, so a client developer does not have to guess whether "2026-11-22" is acceptable. (Which specification URL you cite is your choice; I used the ChilliCream DateTime one as an example.)

In SDL-first servers

If you write SDL and use Yoga or Apollo, you declare scalar DateTime in the schema and supply the GraphQLScalarType object in your resolvers map under the name DateTime. Libraries like graphql-scalars ship ready-made scalars for dates, URLs, emails, and JSON, which is nearly always better than writing your own.

Using scalars well

  • Prefer ID for identifiers, even when they are numbers in your database. Clients should treat them as opaque.
  • Money is a classic trap. Float loses precision. Send an integer in minor units, or a custom Decimal scalar.
  • A scalar that carries arbitrary JSON hides structure from the schema, so no tool can check it. Use it as a last resort.

What the video covers

Ben Awad’s “How to Handle Dates in GraphQL” is a little under ten minutes and was published in September 2018. Its description links to the Apollo graphql-tools docs on “Date as a scalar” and to code for the video. It is seven years old and links to graphql-tools docs of that time, so expect its helper API to differ from today’s; the underlying idea (a scalar with serialize and parse functions) is the same one shown above. I could not read a transcript. Jamie Barton’s short video on the scalar specification is linked as a second view.

Where this fits

Scalars are leaves. Everything above them is built from object types and their fields. Next: object types and fields.

Check yourself

  1. 01Why does returning 3000000000 from an Int field produce an error?

    GraphQL's Int is a 32-bit signed integer, so values outside that range cannot be represented and the executor refuses them.

  2. 02What is the difference between parseValue and parseLiteral?

    parseValue handles a value that arrived in the variables JSON, while parseLiteral handles a value written directly in the query text, which arrives as a syntax node.

  3. 03What does serialize do in a custom scalar?

    It converts the internal value a resolver returned, such as a Date, into the JSON-compatible value sent to the client.

  4. 04How do you tell clients what format a custom scalar expects?

    Give it a description and a specifiedBy URL that points to the format's specification.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark