What Is WunderGraph?
WunderGraph is a type-safe API Gateway that consolidates multiple data sources into a unified interface for frontend applications. It acts as a middleware layer between your frontend and various APIs (GraphQL, REST, databases), generating type-safe operations and React hooks automatically.
Key Benefits
- Type Safety: End-to-end TypeScript type inference from API definitions
- Unified API: Aggregate GraphQL, REST, and database sources into one interface
- Generated Hooks: Automatic React hook generation from operations
- Performance: Intelligent caching and request batching
LogRocket's WunderGraph integration guide provides comprehensive patterns for Next.js implementations.
Why It Matters
Traditional API integration requires manual type definitions, error-prone data fetching, and complex state management. WunderGraph eliminates these challenges by generating types automatically and providing a declarative approach to data fetching that works seamlessly with React and Next.js. Our team at Digital Thrive leverages this approach when building modern web applications that require robust data layers without the overhead of manual API management.
For teams working on custom software development projects, WunderGraph provides a standardized way to handle data integration that scales cleanly as application complexity grows. When choosing your frontend technology stack, understanding the performance differences between frameworks helps inform architectural decisions that impact long-term maintainability.
Everything you need to build robust data layers
TypeScript Operations
Write data fetching logic in TypeScript with full type inference from your configured data sources.
Generated React Hooks
Automatically generated hooks provide type-safe data fetching with React Query conventions.
Multi-Source Federation
Unify GraphQL APIs, REST endpoints, and databases into a single type-safe interface.
Server-Side Rendering
Seamless integration with Next.js SSR and static generation patterns.
Built-in Authentication
Secure your operations with integrated authentication and authorization support.
Performance Optimization
Caching, request batching, and edge deployment support for optimal performance.
Getting Started with WunderGraph
Installation
Initialize a WunderGraph project with your preferred frontend framework using the CLI:
npx create-wundergraph-app my-project -E nextjs
This command scaffolds a complete project structure with the WunderGraph server and Next.js frontend configured together.
Project Structure
The generated project contains:
.wundergraph/- Configuration files and operation definitionspages/orapp/- Next.js application componentsoperations/- TypeScript Operation files
Configuring Data Sources
Define your data sources in wundergraph.config.ts using the introspection APIs. WunderGraph's comprehensive guide covers the configuration-as-code approach that makes managing multiple APIs straightforward:
const countries = introspect.graphql({
apiNamespace: "countries",
url: "https://countries.trevorblades.com/",
});
const graphbrainz = introspect.graphql({
apiNamespace: "graphbrainz",
url: "https://graphbrainz.fly.dev/",
});
configureWunderGraphApplication({
apis: [countries, graphbrainz],
});
This configuration-as-code approach means your data sources are explicitly defined and version-controlled, eliminating the confusion of hard-coded API endpoints scattered throughout your codebase. When you need to update an API endpoint or add a new data source, you make the change in one place, and WunderGraph automatically updates the generated types across your application.
Understanding TypeScript Operations
What Are TypeScript Operations?
TypeScript Operations are the core concept in WunderGraph. Unlike traditional GraphQL queries written in GraphQL syntax, TypeScript Operations let you write data fetching logic using TypeScript with full type inference. LogRocket's tutorial demonstrates practical patterns for implementing operations in production applications.
import { operation } from './.wundergraph/generated';
export default operation.query({
input: (input) => input.string().required(),
resolve: async ({ input, graph }) => {
const countryData = await graph.countries.query({
countryCode: input,
});
return {
country: countryData.country.name,
capital: countryData.country.capital,
};
},
});
Operation Benefits
- Type Safety: Compiler catches errors before they reach production
- IDE Support: Full autocomplete for queries and responses
- Composable: Combine multiple data sources in single operations
- Transformable: Perform server-side data transformations
Operation Types
- Queries: Fetch data (GET equivalent)
- Mutations: Modify data (POST/PUT/DELETE equivalent)
- Subscriptions: Real-time updates via WebSocket
Operation Composition
WunderGraph operations can aggregate data from multiple sources, reducing client-side complexity and improving performance:
export default operation.query({
resolve: async ({ graph }) => {
const [countries, artists] = await Promise.all([
graph.countries.query({ countryCode: 'US' }),
graph.graphbrainz.query({ query: 'music' }),
]);
return {
countryInfo: countries.country,
relatedArtists: artists.search.results,
};
},
});
By defining the aggregation logic server-side, you eliminate multiple round-trips from the client and keep your business logic organized in one place. This pattern is particularly valuable for applications built with our enterprise web development services, where performance and maintainability are critical. TypeScript's type system has become the industry standard for large-scale applications, and understanding why it's surpassing Python in adoption provides valuable context for technology decisions.
Integrating with React and Next.js
Generated React Hooks
WunderGraph automatically generates React hooks from your operations, providing full type safety and following React Query conventions:
function CountryInfo({ countryCode }) {
const { data, loading, error } = useCountryInfo({ input: countryCode });
if (loading) return <Loading />;
if (error) return <Error message={error.message} />;
return (
<div>
<h2>{data.country}</h2>
<p>Capital: {data.capital}</p>
</div>
);
}
Hook Features
- Type Safety: Full TypeScript inference from operations
- Loading States: Built-in loading indicators
- Error Handling: Automatic error capture and access
- Caching: React Query's intelligent caching
- Refetching: Background data refresh
Server-Side Rendering
For Next.js applications, use server-side hooks in getServerSideProps for optimal initial page load performance:
export async function getServerSideProps(context) {
const { data } = await ssrCountryInfo.getServerSideProps({
input: context.params.code,
});
return { props: { data } };
}
This approach improves initial page load performance and provides better SEO outcomes, as search engines receive fully rendered content. The dual approach of client and server hooks means you get the best of both worlds: fast initial loads with SSR and smooth subsequent navigation with client-side rendering. When building React applications, this integration pattern significantly reduces the boilerplate code needed for data fetching while maintaining full type safety throughout the component hierarchy.
For teams evaluating routing solutions, exploring alternatives to React Router can inform decisions about component architecture and data flow patterns.
1import { introspect, configureWunderGraphApplication } from '@wundergraph/sdk';2import { NextJS } from '@wundergraph/nextjs/files';3 4// Configure GraphQL data sources5const countriesAPI = introspect.graphql({6 apiNamespace: 'countries',7 url: 'https://countries.trevorblades.com/',8});9 10const musicAPI = introspect.graphql({11 apiNamespace: 'musicbrainz',12 url: 'https://graphbrainz.fly.dev/',13});14 15// Configure the WunderGraph application16configureWunderGraphApplication({17 name: 'music-explorer',18 apis: [countriesAPI, musicAPI],19 generate: {20 codeGenerator: {21 basePath: './.wundergraph/generated',22 },23 },24 server: {25 host: '0.0.0.0',26 port: 3001,27 },28 frontend: {29 // Generate Next.js integration30 integrations: {31 nextJs: {32 appDir: true,33 },34 },35 },36 experimental: {37 // Enable advanced features38 orm: true,39 },40});41 Performance and Best Practices
Caching Strategies
WunderGraph implements caching at multiple levels to optimize performance for frontend applications:
- Response Caching: Server-side caching with configurable TTL
- Client Caching: React Query's intelligent cache invalidation
- Edge Caching: Deploy to edge locations for global performance
Request Optimization
// Good: Single operation fetching from multiple sources
export default operation.query({
resolve: async ({ graph }) => {
// Batched server-side request
const data = await graph.countries.query({ ... });
return data;
},
});
// Avoid: Multiple client-side requests
async function fetchData() {
const result1 = await fetch('/api/data1'); // Round trip 1
const result2 = await fetch('/api/data2'); // Round trip 2
return combine(result1, result2);
}
Production Deployment
- Deploy WunderGraph Server
- Supports Node.js, Docker, AWS Lambda, Vercel
- Configure environment variables for production
- Set up monitoring and logging
- Deploy Frontend
- Deploy Next.js to Vercel or your preferred platform
- Set WUNDERGRAPH_API_URL environment variable
- Configure CDN and caching
- Security Considerations
- Use environment variables for secrets
- Implement authorization in operations
- Enable authentication for protected operations
By consolidating requests server-side and leveraging intelligent caching, WunderGraph applications typically see significant improvements in Core Web Vitals compared to traditional API integration approaches. This performance advantage is particularly important for SEO optimization, where page load speed directly impacts search rankings.
When evaluating frontend frameworks for your next project, consider whether Svelte is ready for production use alongside React and Next.js options to make informed technology choices.
Authentication and Authorization
Built-in Authentication
WunderGraph integrates with common authentication providers, generating secure, signed requests that include user identity information. Your operations can use this identity to enforce authorization rules, keeping your security logic centralized:
configureWunderGraphApplication({
// ... other config
authentication: {
cookieName: 'wg.auth',
hooks: {
postLogoutRedirect: '/',
},
},
});
Authorization in Operations
Implement authorization logic within operations for server-side enforcement:
export default operation.mutation({
input: (input) => input.object({ id: input.string() }),
resolve: async ({ input, context }) => {
// Check authorization
if (!context.user.hasPermission('edit_content')) {
throw new Error('Unauthorized');
}
// Perform the mutation
return database.updateContent(input.id, context.user.id);
},
});
This server-side enforcement ensures sensitive data never reaches unauthorized clients. The authorization code is type-checked alongside your business logic, so you can be confident that your security rules are correctly implemented. For applications requiring enterprise-grade security, this approach provides a solid foundation that can be extended to meet complex compliance requirements.
Frequently Asked Questions
How does WunderGraph differ from traditional API gateways?
WunderGraph generates type-safe operations and React hooks automatically, providing end-to-end type safety that traditional gateways don't offer. It also includes built-in React Query integration and supports both client-side and server-side rendering patterns.
Can WunderGraph integrate with REST APIs?
Yes, WunderGraph supports OpenAPI REST APIs through its introspection capabilities. You can define REST endpoints as data sources just like GraphQL APIs, and they will be included in the unified type-safe interface.
What databases does WunderGraph support?
WunderGraph supports PostgreSQL, MySQL, and other SQL databases through its database introspection. You can write TypeScript operations that query these databases directly, combining database queries with external API calls.
How does caching work in WunderGraph?
WunderGraph implements multi-level caching including server-side response caching with configurable TTL, and client-side caching through React Query integration. You can also deploy to edge locations for global caching.
Is WunderGraph suitable for small projects?
While WunderGraph's full capabilities shine in complex applications, it works well for projects of any size. The generated hooks and type safety benefit all projects, and you can start with simple operations before adopting advanced features.
Conclusion
Integrating WunderGraph into your frontend application transforms how you handle data fetching and API integration. The framework's type-safe operations, generated React hooks, and powerful configuration system reduce boilerplate while improving reliability and performance.
Key Takeaways
- Type Safety: End-to-end TypeScript from API to React components
- Unified API: Aggregate multiple data sources into one interface
- Generated Hooks: Automatic React hooks with React Query conventions
- Performance: Built-in caching and request optimization
- Security: Server-side authentication and authorization
Getting Started
Start by initializing a project with the CLI, define your data sources, and create your first TypeScript operation. The generated hooks will immediately provide type-safe data fetching in your React components. As you grow more comfortable, explore advanced features like operation composition, custom resolvers, and subscription-based real-time updates.
For teams building modern web applications, WunderGraph provides a significant improvement over traditional API integration approaches. The type safety alone eliminates an entire category of runtime errors, while the performance optimizations through caching and request batching deliver tangible improvements in user experience. WunderGraph's documentation provides comprehensive guidance for implementing these patterns in your specific use case.
Whether you're building a simple dashboard or a complex application that integrates multiple data sources, WunderGraph provides the tools to create a robust, maintainable data layer that scales with your needs. Our web development team has extensive experience implementing these patterns in production applications, and we're happy to help you get started with WunderGraph on your next project.