Custom GraphQL Scalar Types for Dates, Emails, and JSON
Define custom GraphQL scalars for Date, Email, URL, and JSON fields with serialization, parsing, and validation logic
The GraphQL spec defines five built-in scalars: Int, Float, String, Boolean, and ID. Real applications need stricter types: dates that serialize to ISO 8601, emails that validate format, URLs that enforce a protocol, and flexible JSON blobs. A custom scalar fills that gap by defining three functions: serialize (server to client), parseValue (client variable to server), and parseLiteral (client AST to server).
When to Use This
- Date or timestamp fields that must round-trip as ISO 8601 strings, not arbitrary formats
- Email, URL, or phone fields you want rejected at the schema boundary, before a resolver runs
- JSON fields for flexible metadata or third-party payloads that can’t be modeled as object types
- Domain types with real invariants (
PositiveInt,Latitude,CurrencyCode) where a bareIntorStringwould accept invalid input - Skip it for business rules: “email must be unique” or “date must be in the future” belong in input validation at the resolver layer, not in a scalar
Prerequisites
- A GraphQL server built with
graphql-tools, Apollo Server, or another library that accepts a resolvers map - Basic understanding of GraphQL scalar resolution
Solution
1. Install Dependencies
npm install graphql @graphql-tools/utils
2. Define a Date Scalar
// scalars/Date.ts
import { GraphQLScalarType, Kind } from 'graphql';
export const DateScalar = new GraphQLScalarType({
name: 'Date',
description: 'ISO 8601 date string',
specifiedByURL: 'https://www.rfc-editor.org/rfc/rfc3339',
serialize(value: unknown): string {
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === 'string') {
const date = new Date(value);
if (isNaN(date.getTime())) {
throw new Error(`Invalid date string: ${value}`);
}
return date.toISOString();
}
throw new Error(`Date scalar cannot serialize ${typeof value}`);
},
parseValue(value: unknown): Date {
if (typeof value !== 'string') {
throw new Error('Date input must be a string');
}
const date = new Date(value);
if (isNaN(date.getTime())) {
throw new Error(`Invalid date string: ${value}`);
}
return date;
},
parseLiteral(ast): Date {
if (ast.kind !== Kind.STRING) {
throw new Error('Date input must be a string literal');
}
const date = new Date(ast.value);
if (isNaN(date.getTime())) {
throw new Error(`Invalid date string: ${ast.value}`);
}
return date;
},
});
3. Define an Email Scalar
// scalars/Email.ts
import { GraphQLScalarType, Kind } from 'graphql';
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export const EmailScalar = new GraphQLScalarType({
name: 'Email',
description: 'Email address string',
serialize(value: unknown): string {
if (typeof value !== 'string' || !EMAIL_REGEX.test(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value;
},
parseValue(value: unknown): string {
if (typeof value !== 'string' || !EMAIL_REGEX.test(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value.toLowerCase();
},
parseLiteral(ast): string {
if (ast.kind !== Kind.STRING || !EMAIL_REGEX.test(ast.value)) {
throw new Error('Invalid email literal');
}
return ast.value.toLowerCase();
},
});
4. Define a JSON Scalar
// scalars/JSON.ts
import { GraphQLScalarType, Kind, type ValueNode } from 'graphql';
export const JSONScalar = new GraphQLScalarType({
name: 'JSON',
description: 'Arbitrary JSON value',
serialize(value: unknown): unknown {
return value;
},
parseValue(value: unknown): unknown {
return value;
},
parseLiteral(ast): unknown {
switch (ast.kind) {
case Kind.STRING:
return ast.value;
case Kind.INT:
return parseInt(ast.value, 10);
case Kind.FLOAT:
return parseFloat(ast.value);
case Kind.BOOLEAN:
return ast.value;
case Kind.LIST:
return ast.values.map((v) => parseLiteralRecursive(v));
case Kind.OBJECT:
return Object.fromEntries(
ast.fields.map((field) => [field.name.value, parseLiteralRecursive(field.value)])
);
case Kind.NULL:
return null;
default:
throw new Error(`Unexpected AST kind: ${ast.kind}`);
}
},
});
function parseLiteralRecursive(ast: ValueNode): unknown {
return JSONScalar.parseLiteral!(ast, {});
}
5. Register Scalars in the Schema
// schema.ts
import gql from 'graphql-tag';
import { DateScalar } from './scalars/Date';
import { EmailScalar } from './scalars/Email';
import { JSONScalar } from './scalars/JSON';
export const typeDefs = gql`
scalar Date
scalar Email
scalar JSON
type User {
id: ID!
email: Email!
createdAt: Date!
metadata: JSON
}
input CreateUserInput {
email: Email!
metadata: JSON
}
type Mutation {
createUser(input: CreateUserInput!): User!
}
`;
interface CreateUserInput {
email: string;
metadata?: Record<string, unknown> | null;
}
export const resolvers = {
Date: DateScalar,
Email: EmailScalar,
JSON: JSONScalar,
Mutation: {
createUser: (_: unknown, { input }: { input: CreateUserInput }) => {
return {
id: crypto.randomUUID(),
email: input.email,
createdAt: new Date(),
metadata: input.metadata ?? null,
};
},
},
};
How It Works
A scalar sits on the boundary between the wire format and your internal types. Which function runs depends on how the value arrives:
parseValueruns when the client sends the scalar as a variable: the value arrives already decoded from JSON. Validate and convert it to your internal representation.parseLiteralruns when the value is written inline in the query string. You get an AST node, so you walk it yourself, which is why the JSON scalar needs the recursive helper forListandObjectnodes.serializeruns on every field you return to the client. Convert internal values (Date objects, numbers, classes) to the wire format.
Error propagation differs by direction. A throw in parseValue or parseLiteral fails the whole operation: the client gets an error and no data. A throw in serialize fails only that field: it returns null in the response alongside a field-level error, and sibling fields still resolve. Returning undefined from serialize is different again: GraphQL treats it as a missing field and omits it, which hides data-quality problems you’d rather surface.
The specifiedByURL field on the Date scalar links the type to its format spec (RFC 3339). Introspection tools expose it as specifiedByURL, so clients can discover the expected wire format without reading your docs.
Variants
Using the graphql-scalars Package
For common types, prefer the tested graphql-scalars package over hand-rolled implementations:
npm install graphql-scalars
import { DateTimeResolver, EmailAddressResolver, JSONResolver, URLResolver } from 'graphql-scalars';
export const resolvers = {
DateTime: DateTimeResolver,
Email: EmailAddressResolver,
JSON: JSONResolver,
URL: URLResolver,
};
URL Scalar with Protocol Enforcement
// scalars/URL.ts
import { GraphQLScalarType, Kind } from 'graphql';
function toURL(value: unknown): URL {
if (typeof value !== 'string') {
throw new Error('URL input must be a string');
}
const url = new URL(value); // throws TypeError on malformed input
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error(`URL must use http or https, got: ${url.protocol}`);
}
return url;
}
export const URLScalar = new GraphQLScalarType({
name: 'URL',
description: 'Absolute HTTP(S) URL',
serialize(value: unknown): string {
return toURL(value).toString();
},
parseValue(value: unknown): string {
return toURL(value).toString();
},
parseLiteral(ast): string {
if (ast.kind !== Kind.STRING) {
throw new Error('URL input must be a string literal');
}
return toURL(ast.value).toString();
},
});
PositiveInt Scalar with Validation
export const PositiveIntScalar = new GraphQLScalarType({
name: 'PositiveInt',
description: 'Integer greater than zero',
serialize(value: unknown): number {
if (typeof value !== 'number' || value <= 0 || !Number.isInteger(value)) {
throw new Error(`PositiveInt cannot serialize ${value}`);
}
return value;
},
parseValue(value: unknown): number {
if (typeof value !== 'number' || value <= 0 || !Number.isInteger(value)) {
throw new Error(`Invalid PositiveInt: ${value}`);
}
return value;
},
parseLiteral(ast): number {
if (ast.kind !== Kind.INT || parseInt(ast.value, 10) <= 0) {
throw new Error('PositiveInt must be a positive integer literal');
}
return parseInt(ast.value, 10);
},
});
Best Practices
- Validate in all three functions:
serialize,parseValue, andparseLiteralshould enforce the same constraints, or you’ll accept values through the door you forgot to lock - Throw descriptive errors: include the rejected value in the message; clients debugging a mutation will thank you
- Prefer
graphql-scalarsfor common types: DateTime, Email, URL, UUID and friends are already tested; write your own only when the invariant is domain-specific - Document the wire format: set
descriptionandspecifiedByURLso introspection tells clients exactly what to send (RFC 3339 for dates, for example) - Normalize on input: lowercasing emails or canonicalizing URLs in
parseValuekeeps the database consistent without extra resolver code
Common Mistakes
- Only implementing
serialize: queries with inline values or variables fail withoutparseValueandparseLiteral - Mishandling
nullandundefined: decide whether your scalar acceptsnulland handle it in every direction; returningundefinedfromserializeomits the field entirely instead of erroring - Forgetting to register the scalar: it must appear in the resolvers map of
makeExecutableSchemaor Apollo Server, and be declared in the SDL (scalar Date); otherwise it behaves like a plainString - Throwing generic
Errorinstead ofGraphQLError: withoutextensions, clients can’t distinguish a bad input from a server failure; see GraphQL error handling best practices - Not configuring codegen tools: GraphQL Code Generator maps custom scalars to
anyunless you declare them (e.g.,scalars: { Date: 'Date' }), which silently removes the type safety you wanted - Using the
JSONscalar too liberally: it bypasses GraphQL’s type safety; prefer explicit object types and reserveJSONfor genuinely free-form payloads
See Also
- Complete Guide to GraphQL Schema Design: when a custom scalar beats
Stringplus a description - Complete Guide to GraphQL Federation: scalar behavior across subgraphs and the gateway
- GraphQL spec: Scalars: the serialize/parse contract every scalar must satisfy
- graphql-scalars library: production-tested scalars you don’t have to write
- Companion examples: runnable scalar implementations with a demo script
Frequently Asked Questions
Should I use custom scalars or input validation in resolvers?
Use scalars for format validation, where an email is an email, a date parses. Use resolver-level input validation for business rules like "email must be unique" or "date must be in the future", because those need database access or context the scalar never sees.
Can I use custom scalars in input types?
Yes. Scalars work in output types, input types, and arguments. parseValue and parseLiteral validate the input side, serialize the output side.
What is the difference between parseValue and parseLiteral?
parseValue receives a decoded JSON value when the client passes the scalar as a variable. parseLiteral receives an AST node when the value is written inline in the query: for a String node you read ast.value, for List or Object nodes you walk the tree.
Are custom scalars type-safe in TypeScript?
Not out of the box: resolvers see them as unknown. Declare them in GraphQL Code Generator (scalars: { Date: 'Date' }) or wrap parseValue so it returns a concrete type.
How do I handle timezone-aware DateTime scalars?
Parse everything to UTC in parseValue, store UTC, serialize UTC. Storing local time creates ambiguity the moment a server or a client moves across timezones. Let the presentation layer convert for display.
Can I use custom scalars with Apollo Federation?
Yes. Define the scalar in each subgraph that uses it: the gateway passes custom scalars through without validating them, so all subgraphs must implement identical parse and serialize logic or responses will differ by subgraph.
Related Resources
Build a GraphQL API with Apollo Server and TypeScript
How to build a production-ready GraphQL API using Apollo Server, TypeScript, and DataLoader to solve the N+1 query problem
RecipeValidate and Sanitize GraphQL Input Types Server-Side
Implement centralized input validation in GraphQL using Zod schemas, input type transforms, and structured field-level errors
RecipeBatch and Cache Database Queries with GraphQL DataLoader
Implement DataLoader batching in GraphQL resolvers with Apollo Server: collapse N+1 database queries into single batched calls cached per request
RecipeStructured GraphQL Errors with Extension Codes
Implement structured error handling in GraphQL with custom error classes, extension codes, and consistent error formatting for clients.
GuideComplete Guide to GraphQL Schema Design
Design GraphQL schemas that evolve without breaking clients. Type design, connections, mutations, error handling, and schema-first vs code-first.