TExcelTAD
Home › GraphQL › Custom Scalars

Custom Scalars

The five built-in scalars cover a lot, but real APIs also deal with dates, email addresses, URLs, money and large integers. A custom scalar gives such a value its own type name, with your own rules for checking and converting it.

Declaring one

In SDL a custom scalar is a single line:

graphql
scalar Date

On its own this accepts anything and passes it through unchanged. The real work is done by three functions on a GraphQLScalarType:

Function Direction Called with
serialize(value) server → client the value your resolver returned
parseValue(value) client → server a value from the JSON variables
parseLiteral(ast) client → server a literal written in the query text

A Date scalar

Our resolvers will work with JavaScript Date objects, while clients see "YYYY-MM-DD" strings:

js · try it yourself
import {
  graphql, GraphQLSchema, GraphQLObjectType, GraphQLScalarType,
  GraphQLString, GraphQLError, Kind,
} from 'graphql';

const toDate = (text) => {
  if (typeof text !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(text)) {
    throw new GraphQLError(`Date must be a "YYYY-MM-DD" string, got: ${JSON.stringify(text)}`);
  }
  return new Date(`${text}T00:00:00Z`);
};

const DateScalar = new GraphQLScalarType({
  name: 'Date',
  description: 'A calendar date in YYYY-MM-DD format.',
  serialize: (value) => value.toISOString().slice(0, 10),
  parseValue: (value) => toDate(value),
  parseLiteral: (ast) => toDate(ast.kind === Kind.STRING ? ast.value : null),
});

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    releaseDate: { type: DateScalar, resolve: () => new Date(Date.UTC(2026, 2, 14)) },
    addDays: {
      type: DateScalar,
      args: { date: { type: DateScalar }, days: { type: GraphQLString } },
      resolve: (_root, { date, days }) => {
        console.log('resolver sees a', date.constructor.name);
        return new Date(date.getTime() + Number(days) * 86_400_000);
      },
    },
  },
});

const schema = new GraphQLSchema({ query: Query });

const r1 = await graphql({ schema, source: '{ releaseDate }' });
console.log(JSON.stringify(r1.data));

const r2 = await graphql({ schema, source: '{ addDays(date: "2026-02-27", days: "3") }' });
console.log(JSON.stringify(r2.data));

const r3 = await graphql({
  schema,
  source: 'query Q($d: Date) { addDays(date: $d, days: "1") }',
  variableValues: { d: '2026-12-31' },
});
console.log(JSON.stringify(r3.data));

const r4 = await graphql({ schema, source: '{ addDays(date: "14/03/2026", days: "1") }' });
console.log(r4.errors[0].message);
{"releaseDate":"2026-03-14"}
resolver sees a Date
{"addDays":"2026-03-02"}
resolver sees a Date
{"addDays":"2027-01-01"}
Date must be a "YYYY-MM-DD" string, got: "14/03/2026"

The resolver always gets a real Date, whether the client used a literal (parseLiteral) or a variable (parseValue), and invalid input never reaches it.

Attaching scalar behaviour to buildSchema

If you prefer SDL, declare scalar Email and attach the functions to the type object afterwards. Here an Email scalar normalizes and validates addresses:

js · try it yourself
import { graphql, buildSchema, GraphQLError, Kind } from 'graphql';

const schema = buildSchema(`
  scalar Email
  type Query { normalize(email: Email!): Email! }
`);

const checkEmail = (value) => {
  if (typeof value !== 'string' || !/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i.test(value.trim())) {
    throw new GraphQLError(`Not a valid email address: ${JSON.stringify(value)}`);
  }
  return value.trim().toLowerCase();
};

const Email = schema.getType('Email');
Email.serialize = checkEmail;
Email.parseValue = checkEmail;
Email.parseLiteral = (ast) => checkEmail(ast.kind === Kind.STRING ? ast.value : null);

const rootValue = { normalize: ({ email }) => email };

for (const source of [
  '{ normalize(email: "  Ada@Example.COM ") }',
  '{ normalize(email: "ada-at-example") }',
  '{ normalize(email: 42) }',
]) {
  const result = await graphql({ schema, source, rootValue });
  console.log(result.errors ? result.errors[0].message : JSON.stringify(result.data));
}
{"normalize":"ada@example.com"}
Not a valid email address: "ada-at-example"
Not a valid email address: null

Money without floating-point errors

A classic: store money as integer cents, expose it as a decimal string. The scalar keeps the conversion in one place:

js · try it yourself
import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLScalarType, GraphQLList } from 'graphql';

const Money = new GraphQLScalarType({
  name: 'Money',
  serialize: (cents) => `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`,
});

const lines = [{ cents: 1999 }, { cents: 10 }, { cents: 20 }];

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      prices: { type: new GraphQLList(Money), resolve: () => lines.map((l) => l.cents) },
      total: { type: Money, resolve: () => lines.reduce((sum, l) => sum + l.cents, 0) },
    },
  }),
});

const result = await graphql({ schema, source: '{ prices total }' });
console.log(JSON.stringify(result.data));
console.log('with floats, 0.10 + 0.20 =', 0.1 + 0.2);
{"prices":["19.99","0.10","0.20"],"total":"20.29"}
with floats, 0.10 + 0.20 = 0.30000000000000004

Tips for custom scalars

  • Document the format in the description and, ideally, with @specifiedBy(url: "…").
  • Throw GraphQLError from the parse functions for friendly messages.
  • Don't overdo it. Every custom scalar is something each client must understand. Libraries like graphql-scalars provide well-tested DateTime, EmailAddress, URL, BigInt, and more.
  • Scalars can't have sub-fields. If you need { amount currency }, that's an object type, not a scalar.

Test yourself

Which function converts a value from a resolver into what the client receives?

  1. parseValue
  2. parseLiteral
  3. serialize
  4. resolve

A client writes addDays(date: "2026-01-01") directly in the query text. Which function parses it?

  1. serialize
  2. parseValue
  3. parseLiteral
  4. None; literals are passed through

What does a bare scalar Date (with no functions attached) do?

  1. Rejects all values
  2. Passes values through unchanged
  3. Converts to ISO strings
  4. Converts to timestamps