Validate and Sanitize GraphQL Input Types Server-Side
Implement centralized input validation in GraphQL using Zod schemas, input type transforms, and structured field-level errors
GraphQL validates that inputs match their declared types, but it doesn’t enforce business constraints such as string length, number ranges, email format, or XSS sanitization. Without a validation layer, resolvers receive raw user input and each one rolls its own checks. Centralizing validation with Zod schemas keeps resolvers clean and produces consistent, field-level error messages.
When to Use This
- Any mutation that accepts user input (create, update, delete)
- APIs exposed to public clients where input can’t be trusted
- Schemas with complex input types that need cross-field or async validation
- Teams that already use Zod elsewhere (REST handlers, frontend forms) and want one validation vocabulary
Skip this pattern for read-only queries with only scalar arguments: GraphQL’s type checking and a couple of guard clauses are enough there. For validation tied to a specific mutation’s business rules (for example, “only the owner may edit”), the GraphQL Mutation Validation Pattern covers the trade-offs better.
Prerequisites
- A GraphQL server (the examples use Apollo Server 4)
- Zod 4 installed (
npm install zod)
Solution
1. Define Input Types in the Schema
// schema.ts
import gql from 'graphql-tag';
export const typeDefs = gql`
input CreatePostInput {
title: String!
content: String!
tags: [String!]!
publishedAt: String
}
input UpdateUserInput {
name: String
bio: String
website: String
}
type Post {
id: ID!
title: String!
content: String!
tags: [String!]!
publishedAt: String
}
type Mutation {
createPost(input: CreatePostInput!): Post!
updateUser(id: ID!, input: UpdateUserInput!): User!
}
`;
2. Create Zod Validation Schemas
// validation/schemas.ts
import { z } from 'zod';
export const createPostSchema = z.object({
title: z.string()
.min(3, 'Title must be at least 3 characters')
.max(200, 'Title must be at most 200 characters')
.trim(),
content: z.string()
.min(10, 'Content must be at least 10 characters')
.max(50000, 'Content is too long')
.trim(),
tags: z.array(z.string().min(1).max(30).trim())
.min(1, 'At least one tag is required')
.max(10, 'Maximum 10 tags allowed'),
publishedAt: z.iso.datetime()
.optional()
.refine(
(date) => !date || new Date(date) > new Date(),
'Published date must be in the future'
),
});
export const updateUserSchema = z.object({
name: z.string().min(1).max(100).trim().optional(),
bio: z.string().max(500).trim().optional(),
website: z.url('Must be a valid URL').optional().or(z.literal('')),
});
export function validateInput<T>(
schema: z.ZodType<T>,
input: unknown
): { success: true; data: T } | { success: false; errors: { field: string; message: string }[] } {
const result = schema.safeParse(input);
if (result.success) {
return { success: true, data: result.data };
}
const errors = result.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
}));
return { success: false, errors };
}
3. Use Validation in Resolvers
// resolvers.ts
import { createPostSchema, updateUserSchema, validateInput } from './validation/schemas';
import { ValidationException } from './errors';
export const resolvers = {
Mutation: {
createPost: async (
_: unknown,
{ input }: { input: unknown },
ctx: { db: { posts: { create: (data: unknown) => Promise<unknown> }; user: { id: string } } }
) => {
const result = validateInput(createPostSchema, input);
if (!result.success) {
throw new ValidationException(result.errors);
}
return ctx.db.posts.create({
...result.data,
authorId: ctx.user.id,
});
},
updateUser: async (
_: unknown,
{ id, input }: { id: string; input: unknown },
ctx: { db: { users: { update: (id: string, data: unknown) => Promise<unknown> } } }
) => {
const result = validateInput(updateUserSchema, input);
if (!result.success) {
throw new ValidationException(result.errors);
}
return ctx.db.users.update(id, result.data);
},
},
};
4. Custom Error Class for Validation
// errors.ts
export class ValidationException extends Error {
readonly validationErrors: { field: string; message: string }[];
constructor(validationErrors: { field: string; message: string }[]) {
super('Validation failed');
this.name = 'ValidationException';
this.validationErrors = validationErrors;
}
}
5. Format Errors in Apollo Server 4
Resolver errors arrive at formatError wrapped in a GraphQLError, so a bare instanceof check against your custom class fails. Unwrap first:
// server.ts
import { ApolloServer } from '@apollo/server';
import { unwrapResolverError } from '@apollo/server/errors';
import { ValidationException } from './errors';
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: (formattedError, error) => {
const unwrapped = unwrapResolverError(error);
if (unwrapped instanceof ValidationException) {
return {
message: 'Input validation failed',
extensions: {
code: 'VALIDATION_ERROR',
errors: unwrapped.validationErrors,
},
};
}
return formattedError;
},
});
The client receives a VALIDATION_ERROR code plus the errors array, ready to map onto form fields. For the broader error-formatting strategy (masking internal errors, error codes taxonomy), see GraphQL Error Handling Best Practices.
How It Works
- Zod schemas declare constraints alongside the data shape: min/max length, regex, URL format, custom refinements.
safeParsereturns a discriminated union instead of throwing:{ success: true, data }or{ success: false, error }.- Transforms run during parsing:
.trim(), DOMPurify sanitization, and type coercion produce cleaned output that resolvers can persist directly. validateInputconverts Zod issues to a flat{ field, message }array.issue.pathcarries nested locations liketags.2oraddress.zip.ValidationExceptiontransports structured errors through GraphQL’s error pipeline into theextensionsblock.
Variants
Cross-Field Validation
Validate that two fields relate to each other. The path option attaches the error to a specific field:
export const eventSchema = z.object({
startDate: z.iso.datetime(),
endDate: z.iso.datetime(),
}).refine(
(data) => new Date(data.endDate) > new Date(data.startDate),
{ message: 'End date must be after start date', path: ['endDate'] }
);
Sanitization with DOMPurify
Strip HTML from user input to prevent XSS. Because .transform() runs during parsing, the resolver receives already-sanitized content:
import DOMPurify from 'isomorphic-dompurify';
export const htmlContentSchema = z.string()
.transform((value) => DOMPurify.sanitize(value))
.refine((value) => value.length > 0, 'Content cannot be empty after sanitization');
Async Refinements
.refine() also accepts async functions, useful for checks that hit a database, like enforcing uniqueness:
export const createUserSchema = z.object({
email: z.email(),
}).refine(
async (data) => !(await db.users.existsByEmail(data.email)),
{ message: 'Email is already registered', path: ['email'] }
);
Async validation is slower, so order schemas to run cheap checks first and reserve database lookups for fields that passed basic shape validation.
Nested Input Objects
Zod nests cleanly: the field path reported back reflects the structure (profile.website):
export const updateProfileSchema = z.object({
profile: z.object({
displayName: z.string().min(1).max(50).trim(),
website: z.url().optional(),
}),
});
Validation Directives
For schema-declared constraints, the graphql-constraint-directive package annotates SDL directly:
input CreatePostInput {
title: String @constraint(minLength: 3, maxLength: 200)
content: String @constraint(minLength: 10, maxLength: 50000)
}
Directives keep constraints visible in the schema itself, which helps introspection-driven clients. The trade-off: no transforms, no cross-field logic, and an extra dependency. Most teams use Zod at the resolver boundary and reserve directives for simple format hints.
Best Practices
- Validate at the boundary: run validation as the first statement in every resolver that accepts input, before touching the database
- Sanitize, don’t just validate:
.trim()and HTML sanitizers clean input instead of only rejecting it - Return structured errors: field-level errors let clients map messages to specific inputs; the pattern aligns with GraphQL Error Handling Best Practices
- Reuse schemas across layers: share Zod schemas between GraphQL resolvers, REST handlers, and frontend forms; see Data Validation with Zod
- Keep format validation in scalars: email, date, and URL formats also fit custom scalar types; scalars validate at parse time, before the resolver runs
- Don’t leak schema internals: return field names and messages, never the full Zod issue object with internals
Common Mistakes
- Trusting GraphQL’s built-in type checking: it validates types, not constraints like minimum length or format
- Validating in each resolver separately: leads to inconsistent rules and duplicated logic
- Throwing raw errors: without structured
extensions, clients can’t handle validation errors programmatically - Forgetting to sanitize HTML: validation alone doesn’t prevent XSS; strip dangerous tags before storing
- Checking
instanceofon wrapped errors: Apollo Server 4 wraps resolver errors; useunwrapResolverErrorinformatError - Putting business rules in the schema:
@constraintcan’t express “endDate must be after startDate” or async checks; keep those in Zod
Troubleshooting
formatErrornever matchesinstanceof ValidationException: resolver errors arrive wrapped inGraphQLError; callunwrapResolverError(error)first, or match onerror.extensions.code.z.string().datetime()throws a TypeError in Zod 4: ISO validators moved to top level:z.iso.datetime(),z.email(),z.url(),z.uuid(). The string-method variants were removed.- Errors report the wrong field name: for nested objects, Zod’s
issue.pathis an array; join it (profile.website) instead of readingpath[0]. - Transform doesn’t run on an absent optional field:
.optional()short-circuits before.transform(); apply.transform()inside the inner schema or use.default(). - Async refine runs on every keystroke-shaped retry: GraphQL retries resubmit the whole mutation; debounce expensive checks client-side and keep server-side async refines idempotent.
See Also
- GraphQL Mutation Validation Pattern: where mutation-specific business rules live
- GraphQL Error Handling Best Practices: error codes, masking, and extensions
- GraphQL Custom Scalar Types: format validation at parse time
- Complete Guide to GraphQL Security: the broader threat model
- Zod documentation: full API reference
- Apollo Server error handling:
formatError,unwrapResolverError, and extensions - graphql-constraint-directive: SDL-declared constraints
Frequently Asked Questions
Should I use Zod, custom scalars, or validation directives?
They layer rather than compete. Scalars validate format at parse time (the input never reaches your resolver). Directives declare simple constraints in SDL. Zod handles everything else: cross-field rules, transforms, async checks, and reusable schemas. Most schemas end up using all three.
What's the difference between parse and safeParse?
parse throws a ZodError on failure; safeParse returns a result object. Use safeParse when you control error formatting, as in validateInput, and parse inside try/catch if a thrown ZodError fits your pipeline better.
Can I share Zod schemas with the frontend?
Yes, if the frontend is TypeScript. Import the same schema for client-side validation before submitting the mutation. The shapes must stay in sync, which is exactly what sharing the file gives you.
How do I validate file uploads?
GraphQL's multipart spec passes uploads as a Promise<File>-like object, so Zod can't validate it directly. Resolve the upload first, then validate metadata (size, MIME type) with a small schema or plain checks.
How do I localize validation messages?
Pass a ZodErrorMap or use Zod's locale helpers to translate issue.message per request locale. Keep field names in English (clients map them to inputs) and localize only the message text.
Does validation belong in resolvers or in a plugin?
Boundary resolvers are the pragmatic default: explicit, debuggable, framework-agnostic. A Yoga useValidation plugin or Envelop plugin centralizes it further at the cost of indirection. Start with resolvers; extract a plugin when dozens of mutations share the pattern.
Related Resources
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
RecipeStructured GraphQL Errors with Extension Codes
Implement structured error handling in GraphQL with custom error classes, extension codes, and consistent error formatting for clients.
RecipeSchema-Based Data Validation with Zod in TypeScript
Validate and sanitize incoming data using Zod schemas with TypeScript inference, custom refinements, and error formatting for reliable API and form validation
RecipeField-Level Auth with Custom GraphQL Directives
Add field-level authorization to GraphQL with custom schema directives. Check roles, permissions, and ownership per field in Apollo Server.
PatternGraphQL Mutation Validation: Centralized Input Checks
Centralize GraphQL mutation validation with reusable rules, custom scalars, and structured errors. Includes TypeScript examples and best practices.