GraphQL + Apollo + Next.js: A Lovely Trio

Rate this content
Bookmark

Modern frontend applications want to efficiently query data on page load and navigate, format the data with TypeScript, and cache data between repeat requests. Setting that all up on your own is a chore... but with Apollo and Next.js, you can set up your client to auto-generate TypeScript types, cache query results intelligently, and generally be a breeze to work with.

This talk has been presented at GraphQL Galaxy 2021, check out the latest edition of this Tech Conference.

FAQ

The goal of Josh Goldberg's talk is to provide an overview of GraphQL Apollo Next.js and to get the audience excited about the technology. It covers auto-generating types, introspection, and other cool features, targeting people new to Next.js or those familiar with GraphQL who want to learn how to use it with Next.js.

The target audience includes individuals who are new to Next.js and those who may already know GraphQL and want a primer on how to use Next.js with GraphQL.

Josh Goldberg's talk highlights Next.js's ability to scaffold data loading and routing for React website pages. It also mentions features like great builds, optimization, and single-page app style navigations using the Link component.

Next.js handles static data loading using the GetStaticProps function. This function can be asynchronous and fetches data for a page, which is then returned as props to the page's default component. In development, this function is called every time the page loads, but in production, the page is pre-built with HTML and the data is cached.

Incremental Static Regeneration (ISR) in Next.js allows pages to be built on-demand rather than upfront. When a page is requested that hasn't been built yet, the data for that page is fetched and cached for a specified number of seconds. This approach saves time and optimizes performance, especially for sites with numerous pages or translations.

Apollo Client integrates with GraphQL in a Next.js application by managing GraphQL requests and caching responses. It provides tools like Apollo Provider, which sets up a React context for Apollo Client, and hooks like useQuery to fetch data. The integration also supports auto-generating types and components from GraphQL queries using GraphQL code generators.

GraphQL Code Generator is a tool that generates TypeScript types, hooks, and components from GraphQL schemas and queries. It helps automate the creation of code, reducing boilerplate and ensuring type safety. The generator uses configuration files to define schemas and plugins, which then produce the necessary code artifacts.

Josh Goldberg recommends resources such as nextjs.org for Next.js, graphql-code-generator.com for GraphQL Code Generator, and apollographql.com for Apollo. He also mentions Blitz.js and RemixRun as additional frameworks, and TypeScriptBlind.org for learning TypeScript.

More information about Josh Goldberg and his work can be found on his Twitter account @JoshuaKGoldberg and his website JoshuaKGoldberg.com.

Josh Goldberg uses GraphiQL for previewing GraphQL queries and endpoints, and the Apollo Client for managing GraphQL requests and caching in his demonstrations.

Josh Goldberg
Josh Goldberg
21 min
10 Dec, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This talk provides an overview of using GraphQL, Apollo, and Next.js together. It covers Next.js' data loading and routing capabilities, code generation with GraphQL, and generating TypeScript types. The talk also explores Apollo Client and its integration with GraphQL code generation. The speaker recommends checking out companion repositories and resources for more information.

1. Introduction to GraphQL Apollo Next.js

Short description:

Hello, and welcome to GraphQL Apollo Next.js, a lovely trio, with me, Josh Goldberg. This is going to be a quick talk, so I like to think of this one as an overview. The goal of it is to get you hyped. This is really cool technology. We're going to be auto-generating types and looking at introspection and cool stuff. The target audience for all these nifty things are folks who are new to Next.js, maybe know GraphQL and want a primer of how to use Next.js with GraphQL. Next.js scaffolds data loading and routing for React website pages. It does a lot of other cool stuff for us, like really great builds and optimization, but for the purposes of this overview talk, it's really just the data loading and routing that we care about.

Hello, and welcome to GraphQL Apollo Next.js, a lovely trio, with me, Josh Goldberg. This is going to be a quick talk, so I like to think of this one as an overview. The goal of it is to get you hyped. This is really cool technology. We're going to be auto-generating types and looking at introspection and cool stuff.

The target audience for all these nifty things are folks who are new to Next.js, maybe know GraphQL and want a primer of how to use Next.js with GraphQL. Little bit about me, this stuff is near and dear to my heart because I do it for work. I'm on the web platform team as a front-end developer at Codecademy, a great place to learn how to code. I work on our shared tooling across all of our front-end apps, such as our recent and ongoing move from our custom React, Rails, webpack architecture to Next.js, which does a lot more for us and helps us use things like Apollo and GraphQL. On the side, I'm also working on an O'Reilly-type-kit book. So, hit me up if you're interested about that. The way you can hit me up is on my Twitter at Joshua K Goldberg or my website, JoshuaKGoldberg.com.

Let's dive in. Next.js, delightful React scaffolding. In a nutshell, Next.js scaffolds data loading and routing for React website pages. It does a lot of other cool stuff for us, like really great builds and optimization, but for the purposes of this overview talk, it's really just the data loading and routing that we care about. There's a great tool, Create Next App, that the Next folks made, similar to Create React app. They've gone ahead and done that for us at GitHub.com slash Joshua K. Goldberg slash GrapQL. A Galaxy, a lovely trio. Again, shout out to my website, JoshuaKGoldberg.com. If you want to get these things, I'm going to be going through these slides kind of quickly. So to start, I have already Git cloned and yarned. So if we do yarn dev, Next.js starts a remarker really quickly and then when we first visit a URL, it starts loading the page, which might take a little bit first. So I'll just go ahead and look at the page. Pages slash index. Every file under the pages directory, which can be in your roots or under source, default exports a component for the page. In the case that we're looking at on the slide here, you don't have to return much, just some JSX, and then Next.js will build the page for you based on that path. The contents of the page are entirely up to you. You can use whatever HTML contents, whatever style you want, so long as it's a React component.

2. Next.js Routing and Data Fetching

Short description:

Next.js provides a link component for SPA-style navigation, eliminating the need for full page refreshes. It can prefetch data for links within the viewport. Next.js allows exporting a GetStaticProps function to fetch data for static pages, improving performance. The DevTools panel in React browser DevTools provides a tree view of components. Incremental static regeneration (ISR) allows on-demand page building.

Voila, here we go, we can see that this Next beautiful starter component is now rendering all of a sudden. Good for us. A little bit of cool stuff from Next to start us off is its routing logic. Next supports SPA or single page app style navigations. Instead of having the browser fetch an entirely new HTML page every time you want to navigate, Next provides a link component that wraps and takes over the linking behavior of your normal anchor tags. Let's go to a quick page, pages slash with link, which means that if we go to slash with link, we get the corresponding page in our browser for this component and file. Now this one uses the link component as seen on the slide, which means that if I click home, which is an anchor tag, notice how the page will not refresh, there's no new HTML file, it just directly quickly brings me to the home component. Awesome. And if I go back and forth in the browser URL bar, it's able to do spot-style navigations without a full refresh. Fantastic, fan diddly-tastic, thanks Next.

Now I have seen rumors online and some substantiation of this idea that Next will actually prefetch data for links that appear within your viewport, if it's a link to a Next page using this link, which I think is just the coolest darn feature in the world. Now the way Next is able to do that is not just by controlling your page generation and the linking, but also the data that's used to power those pages. If you have a static page, meaning a page that gets built into a static HTML file that can be immediately served, very good for performance, highly recommend when possible. Next lets you export a GetStaticProps function from that file, which can be async, and in some way finds the data for that page, then returns the data as props to be passed to that page's default component. In development, this GetStaticProps function will be called every time you try to load the page, but in production, the page is pre-built with HTML and then this data is cached so you don't have to keep querying for it over and over again. Just quickly looking at a page pages slash with static props. Here we see the GetStaticProps function, which calls some stub API setup, which just waits 2.5 seconds then returns some data. Let's bring that down there. And then the component itself just uses that as a prop and then maps over to render a list. Let's look at with static props, wait 2.5 seconds to simulate the API call and voila, we have our static data. Awesome. That's all you got to do to pass data to next components. Now I just opened the DevTools and I highly recommend if you haven't yet installed the React browser DevTools, they give you this awesome components panel which shows you a tree view of all your components. And I'm going to use it just to show that React is getting the exact array that we expected from ColSum API. Love it. Thanks Next JS. You might have noticed in the code, I actually had this re-validate member here. You don't have to build all your static pages upfront with Next JS. You can use incremental static regeneration or ISR. It says instead of building these things up front, whenever someone requests a page that isn't already built, for the next X number of seconds, use a particular piece of data which you will then fetch now.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
A Practical Guide for Migrating to Server Components
React Advanced 2023React Advanced 2023
28 min
A Practical Guide for Migrating to Server Components
Top Content
Watch video: A Practical Guide for Migrating to Server Components
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.
The New Next.js App Router
React Summit 2023React Summit 2023
27 min
The New Next.js App Router
Top Content
Watch video: The New Next.js App Router
Today's Talk is about the Next.js App Router, which has evolved over the years and is now a core feature of Next.js. The Talk covers topics such as adding components, fetching remote data, and exploring layouts. It also discusses submitting form data, simplifying code, and reusing components. The App Router allows for coexistence with the existing pages router and enables data fetching at the layout level using React Server Components.
You Don’t Know How to SSR
DevOps.js Conf 2024DevOps.js Conf 2024
23 min
You Don’t Know How to SSR
The Talk covers the speaker's personal journey into server-side rendering (SSR) and the evolution of web development frameworks. It explores the use of jQuery for animations in SSR, the challenges faced in integrating React with Umbraco, and the creation of a custom SSR framework. The Talk also discusses the benefits of Next.js and the use of serverless artifacts for deployment. Finally, it highlights the features of Astro, including its function per route capability.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
AI for React Developers
React Advanced 2024React Advanced 2024
142 min
AI for React Developers
Featured Workshop
Eve Porcello
Eve Porcello
Knowledge of AI tooling is critical for future-proofing the careers of React developers, and the Vercel suite of AI tools is an approachable on-ramp. In this course, we’ll take a closer look at the Vercel AI SDK and how this can help React developers build streaming interfaces with JavaScript and Next.js. We’ll also incorporate additional 3rd party APIs to build and deploy a music visualization app.
Topics:- Creating a React Project with Next.js- Choosing a LLM- Customizing Streaming Interfaces- Building Routes- Creating and Generating Components - Using Hooks (useChat, useCompletion, useActions, etc)
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced 2022React Advanced 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.