0
0
GraphqlDebug / FixBeginner · 4 min read

How to Handle Null Values in GraphQL Queries and Schemas

In GraphQL, fields are nullable by default, so they can return null unless marked with an exclamation mark ! to make them non-nullable. To handle null values properly, define your schema types carefully, use default values, and check for null in your resolvers to avoid errors or unexpected results.
🔍

Why This Happens

GraphQL fields are nullable by default, meaning they can return null if no value is found or an error occurs. If your schema does not specify non-nullable fields, clients may receive null unexpectedly, which can cause confusion or errors in the client application.

graphql
type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String
  email: String
}

// Resolver returns null for email if user has no email
const resolvers = {
  Query: {
    user: (parent, args) => ({ id: args.id, name: "Alice", email: null })
  }
};
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": null } } }
🔧

The Fix

To fix unexpected null values, mark fields as non-nullable with ! if they must always have a value. Also, handle null in resolvers by providing default values or throwing errors to inform clients clearly.

graphql
type Query {
  user(id: ID!): User!
}

type User {
  id: ID!
  name: String!
  email: String!
}

const resolvers = {
  Query: {
    user: (parent, args) => {
      const user = { id: args.id, name: "Alice", email: null };
      if (!user.email) {
        user.email = "no-email@example.com"; // default value
      }
      return user;
    }
  }
};
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": "no-email@example.com" } } }
🛡️

Prevention

To avoid null-related issues in GraphQL, always define your schema with clear nullability rules. Use non-nullable types ! for required fields, provide default values in resolvers, and validate inputs. Also, use tools like GraphQL schema linting to catch nullable field misuse early.

⚠️

Related Errors

Common related errors include Cannot return null for non-nullable field, which happens when a resolver returns null for a field marked as non-nullable. Fix this by ensuring resolvers never return null for such fields or by changing the schema to allow nulls.

Key Takeaways

GraphQL fields are nullable by default; use ! to make them non-nullable.
Handle nulls in resolvers by providing default values or throwing errors.
Define clear nullability rules in your schema to avoid unexpected nulls.
Use schema linting tools to catch nullability issues early.
Fix 'Cannot return null for non-nullable field' by adjusting resolvers or schema.