From Chaos to Order in the Frontend
Source: Dev.to
How it worked
- Backend updates GraphQL schemas for microservices.
- Frontend pulls the latest schemas, creates queries/mutations and regenerates types.
- Any breaking changes are caught before the frontend build.
This approach allows us to detect all mismatches between backend queries and responses at frontend build time, long before they reach runtime.
How it created
To integrate type generation, add the following dependencies to your project:
@graphql-codegen/cli@graphql-codegen/typescript@graphql-codegen/typescript-document-nodes@graphql-codegen/typescript-operations
Type generation and updates are configured via a YAML file for GraphQL Code Generator.
Generating types from a local schema
# Should existing files be overwritten after generation
overwrite: true
generates:
# Path to the generated output
src/generated/schema.graphql.ts:
# Path to the GraphQL schema
schema: ./graphql-schema/schema.graphql
# GraphQL documents (queries/mutations) to parse in the project
documents: src/**/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-document-nodes
Generating types from an introspection endpoint
overwrite: true
generates:
src/generated/introspection.graphql.ts:
# GraphQL endpoint URL
schema: "http://localhost:4000/graphql"
documents: "src/**/*.graphql"
plugins:
- typescript
- typescript-operations
- typescript-document-nodes
Running the generation
Define convenient scripts in package.json:
{
"scripts": {
"codegen:schema": "npx graphql-codegen --config codegen-schema.yml",
"codegen:introspection": "npx graphql-codegen --config codegen-introspection.yml"
}
}
Example usage
GraphQL query
query GetOpportunities($request: GetOpportunitiesRequestInput!) {
opportunities(request: $request) {
statusCode
message
data {
contractNumber
creationDate
}
}
}
Type‑safe variables and query execution (TypeScript)
// Type-safe variables
const variables: GetOpportunitiesThemesQueryVariables = {
providerId: test1,
keycloakUserId: test2,
};
// Query using Apollo (example from the project)
this.apollo
.watchQueryWithService('accreditationService', {
query: GetOpportunitiesThemes,
variables,
});
Conclusion
Using GraphQL Code Generator together with a strict backend deployment workflow keeps frontend teams in sync with backend changes, catches mismatches at build time, and dramatically reduces manual debugging.
The approach works for both SDL‑based and introspection‑based workflows and scales well for projects with multiple microservices.
Feel free to try the setup in your own project and share your thoughts or alternative approaches!