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.

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
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
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
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
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
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
The New Next.js App Router
React Summit 2023React Summit 2023
27 min
The New Next.js App Router
Next.js 13.4 recently released the stable version of the "App Router" – a transformative shift for the core of the framework. In this talk, I'll share why we made this change, the key concepts to know, and why I'm excited about the future of React.
A Practical Guide for Migrating to Server Components
React Advanced Conference 2023React Advanced Conference 2023
28 min
A Practical Guide for Migrating to Server Components
Server Components are the hot new thing, but so far much of the discourse around them has been abstract. Let's change that. This talk will focus on the practical side of things, providing a roadmap to navigate the migration journey. Starting from an app using the older Next.js pages router and React Query, we’ll break this journey down into a set of actionable, incremental steps, stopping only when we have something shippable that’s clearly superior to what we began with. We’ll also discuss next steps and strategies for gradually embracing more aspects of this transformative paradigm.
You Don’t Know How to SSR
DevOps.js Conf 2024DevOps.js Conf 2024
23 min
You Don’t Know How to SSR
A walk-through of the evolution of SSR in the last twelve years. We will cover how techniques changed, typical problems, tools you can use and various solutions, all from the point of view of my personal experience as a consumer and maintainer.

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
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 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.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura