0
0
GraphqlDebug / FixBeginner · 4 min read

How to Handle Dates in GraphQL: Best Practices and Fixes

GraphQL does not have a built-in Date type, so you handle dates by defining a custom scalar type like Date or DateTime. Use libraries such as graphql-scalars or implement your own scalar to parse and serialize date strings in ISO format.
🔍

Why This Happens

GraphQL's default scalar types do not include a Date or DateTime type. If you try to use a date directly as a String or Int, you lose type safety and proper validation. This often causes confusion or errors when clients send or receive date values.

graphql
type Query {
  getEvent(id: ID!): Event
}

type Event {
  id: ID!
  name: String!
  date: String!
}
Output
Dates are treated as plain strings without validation, which can lead to inconsistent formats or errors in client apps.
🔧

The Fix

Define a custom scalar type for dates to ensure consistent parsing and serialization. You can use a library like graphql-scalars or write your own scalar resolver that handles ISO 8601 date strings. This approach validates date inputs and outputs properly.

javascript
const { GraphQLScalarType, Kind } = require('graphql');

const DateScalar = new GraphQLScalarType({
  name: 'Date',
  description: 'Custom Date scalar type in ISO 8601 format',
  parseValue(value) {
    return new Date(value); // from client input
  },
  serialize(value) {
    return value.toISOString(); // sent to client
  },
  parseLiteral(ast) {
    if (ast.kind === Kind.STRING) {
      return new Date(ast.value);
    }
    return null;
  },
});

// Schema definition
const typeDefs = `
  scalar Date

  type Event {
    id: ID!
    name: String!
    date: Date!
  }

  type Query {
    getEvent(id: ID!): Event
  }
`;

// Resolver map
const resolvers = {
  Date: DateScalar,
  Query: {
    getEvent: () => ({ id: '1', name: 'Party', date: new Date() }),
  },
};
Output
{ "data": { "getEvent": { "id": "1", "name": "Party", "date": "2024-06-01T12:00:00.000Z" } } }
🛡️

Prevention

Always use custom scalars for dates in GraphQL schemas to maintain type safety and consistent formats. Adopt ISO 8601 date strings for interoperability. Use existing libraries like graphql-scalars to avoid reinventing the wheel. Validate date inputs on the server side and document the expected format clearly for clients.

⚠️

Related Errors

Common related errors include:

  • Sending dates as plain strings causing format mismatches.
  • Parsing errors when clients send invalid date strings.
  • Using Int for timestamps without clear documentation.

Fixes involve switching to custom scalars and validating inputs.

Key Takeaways

GraphQL has no built-in date type; use custom scalars for dates.
Implement or import a Date scalar that parses and serializes ISO 8601 strings.
Validate date inputs on the server to avoid format errors.
Use libraries like graphql-scalars to simplify date handling.
Document date formats clearly for API clients.