惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

Maxime Heckel's Blog

On Rendering the Sky, Sunsets, and Planets - The Blog of Maxime Heckel Shades of Halftone - The Blog of Maxime Heckel Field Guide to TSL and WebGPU - The Blog of Maxime Heckel On Shaping Light: Real-Time Volumetric Lighting with Post-Processing and Raymarching for the Web - The Blog of Maxime Heckel Speaking at Figma Config 2025 - The Blog of Maxime Heckel Post-Processing Shaders as a Creative Medium - The Blog of Maxime Heckel On Crafting Painterly Shaders - The Blog of Maxime Heckel The Art of Dithering and Retro Shading for the Web - The Blog of Maxime Heckel Moebius-style post-processing and other stylized shaders - The Blog of Maxime Heckel Shining a light on Caustics with Shaders and React Three Fiber - The Blog of Maxime Heckel Real-time dreamy Cloudscapes with Volumetric Raymarching - The Blog of Maxime Heckel Painting with Math: A Gentle Study of Raymarching - The Blog of Maxime Heckel Building a magical AI-powered semantic search from scratch - The Blog of Maxime Heckel Beautiful and mind-bending effects with WebGL Render Targets - The Blog of Maxime Heckel Refraction, dispersion, and other shader light effects - The Blog of Maxime Heckel The magical world of Particles with React Three Fiber and Shaders - The Blog of Maxime Heckel The Study of Shaders with React Three Fiber - The Blog of Maxime Heckel Building a Design System from scratch - The Blog of Maxime Heckel Everything about Framer Motion layout animations - The Blog of Maxime Heckel Building a Vaporwave scene with Three.js - The Blog of Maxime Heckel Cubic Bézier: from math to motion - The Blog of Maxime Heckel First steps with GPT-3 for frontend developers - The Blog of Maxime Heckel Building the perfect GitHub CI workflow for your frontend team - The Blog of Maxime Heckel Migrating to Next.js - The Blog of Maxime Heckel Static Tweets with MDX and Next.js - The Blog of Maxime Heckel Advanced animation patterns with Framer Motion - The Blog of Maxime Heckel Scrollspy demystified - The Blog of Maxime Heckel The Power of Composition with CSS Variables - The Blog of Maxime Heckel My first failed SwiftUI project - The Blog of Maxime Heckel Guide to creating animations that spark joy with Framer Motion - The Blog of Maxime Heckel Using Shortcuts and serverless to build a personal Apple Health API - The Blog of Maxime Heckel SEO mistakes I've made and how I fixed them - The Blog of Maxime Heckel Going native: SwiftUI from the perspective of a React developer - The Blog of Maxime Heckel Build your own preview deployment service - The Blog of Maxime Heckel The little guide to CI/CD for frontend developers - The Blog of Maxime Heckel Immigrating to the US - The Blog of Maxime Heckel The physics behind spring animations - The Blog of Maxime Heckel Generate screenshots of your code with a serverless function - The Blog of Maxime Heckel How to use Framer Motion with Emotion styled-components - The Blog of Maxime Heckel Learning in public - The Blog of Maxime Heckel Fixing the dark mode flash issue on server rendered websites - The Blog of Maxime Heckel How to fix NPM link duplicate dependencies issues - The Blog of Maxime Heckel Running scheduled cross-browser end-to-end tests on Github CI - The Blog of Maxime Heckel How I built my first custom ESLint rule - The Blog of Maxime Heckel React Lazy: a take on preloading views - The Blog of Maxime Heckel Automated UI accessibility testing with Cypress - The Blog of Maxime Heckel Building a GraphQL wrapper for the Docker API - The Blog of Maxime Heckel Switching off the lights - Adding dark mode to your React app - The Blog of Maxime Heckel Getting started with Typescript on Gatsby - The Blog of Maxime Heckel Rebuilding Redux with Hooks and Context - The Blog of Maxime Heckel Asynchronous rendering with React - The Blog of Maxime Heckel Using Flow generics to type generic React components - The Blog of Maxime Heckel How to efficiently type your styled-components with Flow - The Blog of Maxime Heckel How I got started with Kubernetes on GKE - The Blog of Maxime Heckel React sub-components Part 3: Whitelisting sub-components with flow - The Blog of Maxime Heckel React sub-components Part 2: Using the new Context API - The Blog of Maxime Heckel React sub-components - The Blog of Maxime Heckel Running Golang tests with Jest - The Blog of Maxime Heckel No title No title
Data Fetching with NextJS: What I learned - The Blog of Maxime Heckel
Maxime Heckel · 2020-05-05 · via Maxime Heckel's Blog

As I wrote in my blog post titled Learn In Public, I recently brought my attention to learning more about NextJS. Throughout my entire career as a Frontend engineer, I've solely focused on building client-side React applications without much looking at other solutions. NextJS, in the meantime, became very popular and I kept hearing good things about it and when seeing the different use cases of server-side rendering. I can now see myself using it in several projects, or for my potential future business endeavors.

If like me, you started learning NextJS, or need a refresher on the latest features, this article is for you!

Wrapping my head around data fetching

One aspect that struck me the most when I started to learn the framework, was data fetching. NextJS provides different functions to get data asynchronously, and when to use each function can seem tricky at first, as it all depends on different use cases:

  • the pre-rendering type desired: server-side rendered or static

  • the data: are we loading static or dynamic data? Is that data accessible ahead of a user request

Additionally, you can see this in the title of this post, the names of these functions look quite similar which can be confusing at first, but bear with me, at the end of this article it will be clearer.

Pre-Rendering types with NextJS

As mentioned above, NextJS provides support for server-side rendering (SSR) and static-site generation (SSG) which are both pre-rendering types, and aim for the same result (i.e. better performance, no client-side rendering) but differ in when the HTML pages are being pre-rendered:

  • For SSG, the HTML pages are rendered at build time. When you're done building, the result is a set of static files. This is the method I prefer because it allows me to cache my website on a CDN and offers better performance

  • For SSR, the site is generated by a server on each request. That means your website is dependent on some code running on a server, not simply static files.

Now let's look at the difference between these two pre-rendering methods when it comes to data fetching

getStaticProps

This function is the first one I encountered when I started to learn NextJS. It's an asynchronous function that fetches the data at build time, which means according to the definitions we just saw above that it's used for SSG.

It takes a context as an argument (more on that later) and will return an object with a props field. This prop field contains all the props we'll end up passing down to a page.

This function can be used to :

  1. call an API / external endpoint and retrieve some data

  2. read a local file

  3. query a database

as long as the data to be retrieved is not user-related or a specific entity linked to the client as, again, this function will be triggered at build time. It also means that each time the data changes, we would have to rebuild.

Example showcasing a use case of getStaticProps for a sample /todos API

1

import { NextPage, GetStaticProps } from 'next';

2

import Link from 'next/link';

3

import fetch from 'node-fetch';

5

const TodosPage: NextPage<{

6

todos: { title: string; userId: string; id: string; completed: boolean }[];

11

<Link href="/">Home</Link>

13

{props.todos.map((x) => {

15

<li key={`/todos/${x.id}`}>

16

<Link as={`/todos/${x.id}`} href={`/todos/[id]`}>

27

export const getStaticProps: GetStaticProps = async () => {

28

const todos = await fetch(

29

'https://jsonplaceholder.typicode.com/todos'

30

).then((response) => response.json());

37

export default TodosPage;

getStaticPaths

NextJS gives the ability for the developer to create statically generated dynamic routes, e.g. /products/:id or /users/:name/:comment. To have access to the path of these dynamic routes we use getStaticPaths. Same as the function we introduced earlier, this one is an asynchronous function that returns an object with a paths field. That paths field contains all the paths that need to pre-rendered at build time, which means it's used for SSG. There's also another field called fallback, I haven't used it yet, the only thing I know is that if it's set to false and a user tries to access a path that is not returned by getStaticPaths, it will result in a 404.

getStaticPaths can be used in conjunction with getStaticProps. The paths returned are then present in the "context" of the page, which can be read by the getStaticProps function. As an example, we could consider a static product page with a dynamic route representing a route to a given product:

Example showcasing a use case of getStaticPaths for a sample /todos/:id API

1

import { NextPage, GetStaticPaths, GetStaticProps } from 'next';

2

import Link from 'next/link';

3

import fetch from 'node-fetch';

5

const TodoPage: NextPage<{ title: string }> = (props) => {

9

<Link href="/todos">Todos</Link>

14

export const getStaticPaths: GetStaticPaths = async () => {

15

const todos = await fetch(

16

'https://jsonplaceholder.typicode.com/todos'

17

).then((response) => response.json());

19

const ids = todos.map((todo) => todo.id);

20

const paths = ids.map((id) => ({ params: { id: id.toString() } }));

28

export const getStaticProps: GetStaticProps = async ({ params: { id } }) => {

29

const todos = await fetch(

30

'https://jsonplaceholder.typicode.com/todos'

31

).then((response) => response.json());

32

const todo = todos.find((x) => x.id == id);

41

export default TodoPage;

getServerSideProps

Sometimes static-side generation is not what we need. If we want to be able to fetch data and render dynamic content on the fly getServerSideProps is what we need. Like getStaticProps, this function is asynchronous and allows us to fetch some data and returns an object with a props field that will be passed down to a page. However, the main difference here is that getServerSideProps allows us to pre-render a page on each request, thus we can consider that this is a use case for SSR. This means that thanks to this function, I can go fetch some non-static data that is tied to a request.

Example showcasing a use case of getServerSideProps for a sample /todos/:id API

1

import { GetServerSideProps, NextPage } from 'next';

2

import ErrorPage from 'next/error';

3

import fetch from 'node-fetch';

12

const Todo: NextPage<{ data: Data }> = (props) => {

14

return <ErrorPage statusCode={404} />;

19

<p>{props.data.id}</p>

20

<p>{props.data.title}</p>

21

<p>{props.data.userId}</p>

22

<p>{props.data.completed}</p>

27

export const getServerSideProps: GetServerSideProps = async ({

32

const { id } = params;

33

const result = await fetch(

34

`https://jsonplaceholder.typicode.com/todos/${id}`

35

).then((response) => response.json());

What about data fetching on "non-page" components

I felt that one of the most confusing aspect of NextJS when having worked only on more classic client side rendered app, is the distinction between pages and "non-pages" components. Thankfully, I'm a heavy gatsbyJS user so I was already familiar with these concepts when I started learning about NextJS, hence, just in case I want to write a few word about it for anyone who might still be confused about pages vs components.

The functions featured above only work on pages. Which means the following:

  • you can only use them in files under the /pages folder

  • they can't be used on components

  • components will have to rely on client-side fetching if we want them to fetch data.

So when building your first NextJS app, you'll have to carefully architect your app and think about data beforehand and ask yourself:

  • what can and should be fetched at build time?

  • what can and should be server-rendered?

  • which components need to have access to data and do they need to trigger some client-side fetching.

These ways of thinking about where the data comes from in these different use cases are unusual to me since I only worked on client-side apps in the past, but I feel ready to do that kind of gymnastic in my future projects as I feel these NextJS functionalities have a lot of potentials when it comes to building more efficient applications.