iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌎

ISR in Next.js App Router when fetch cannot be used

に公開
2024/05/31

Introduction

The App Router provides a fetch function that enables ISR, but it only supports HTTP-based requests. I couldn't find any articles explaining how to handle data fetching from Firestore or Supabase, so I decided to post this.
If anyone knows a better way, please let me know. (That's actually the main point of this post.)

export default async function Page() {
 const res = await fetch('https://api.example.com/...', { next: { revalidate: 3600 } })
  const data = res.json()

  return <Home data={data} />
}

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch

Conclusion

By doing the following, you can achieve ISR.
Cached data will be served for 60 seconds, so no queries will be made to the database during that interval.

page.tsx
import { getData } from './utils'

export const revalidate = 60

export default async function Page() {
 const data = await getData('id')

  return <Home data={data} />
}
utils.tsx
import { cache } from 'react'

export const getData = cache(async (id: string) => {
  const data = await db.query('...')
  return data
})

It was mentioned on the following page:
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-third-party-libraries

If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment.

When a segment is static (the default), the output of the request will be cached and revalidated as part of the route segment.

If the size of the pages you are caching seems large, be sure to set cacheMaxMemorySize.
The default is 50M.

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  cacheMaxMemorySize: 50 * 1024 * 1024 // 50M
}

module.exports = nextConfig

cache

The official documentation mentions that using React's cache allows for data fetching from third-party libraries that cannot use fetch. Without using cache, data might be revalidated even if the time specified in revalidate has not yet passed, so I use it for better stability. I suspect that the revalidate specified in page.tsx represents the interval for caching the data used to generate the page, rather than the interval for the page generation itself.

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-third-party-libraries

By using cache, as shown below, data is cached even when fetching the same data in both layout.tsx and page.tsx, so a single query to the DB is sufficient. However, when using Dynamic Routes, the revalidate value is ignored and a query is executed on every page access.

app/item/[id]/layout.tsx
import { getData } from './utils'

export const revalidate = 60

export default async function Layout({
  params: { id },
}: {
  params: { id: string }
}) {
  const item = await getData(id)
  // ...
}
app/item/[id]/page.tsx
import { getData } from './utils'

export const revalidate = 60

export default async function Page({
  params: { id },
}: {
  params: { id: string }
}) {
 const data = await getData(id)

  return <ItemPage data={data} />
}

unstable_cache

This is the functionality I was looking for, but as noted in the official documentation, it is still under development.

https://nextjs.org/docs/app/building-your-application/caching#unstable_cache

I believe the usage is something like the following. When I actually tried it, it seemed to work correctly during local debugging, but once deployed to Vercel, it was only executed during build time and behaved as standard SSR.

import { unstable_cache } from 'next/cache'

export default async function Page() {
  const data = await unstable_cache(
    async () => {
      const data = await db.query('...')
      return data
    },
    ['cache-key'],
    {
      tags: ['a', 'b', 'c'],
      revalidate: 10,
    }
  )()
  return <Home data={data} />
}

Here is the site where I tried various things:

https://isr-test-bay.vercel.app/

Afterword

There weren't many articles summarizing this topic, and I ended up spending quite a bit of time on it, so I hope this helps someone.

Supplement

It seems better to set prefetch={false} for next/link when using ISR. If it's not specified, the page linked via Link will be revalidated when the current page is displayed, regardless of the period specified in revalidate.

In the example below, when the Home page is displayed, pageA and pageB are also revalidated.

import Link from "next/link";

export default function Home() {
  return (
    <main>
      <h1>Home</h1>
      <Link href='/pageA'>
       pageA
      </Link>
      <br />
      <Link href='/pageB'>
       pageB
      </Link>
    </main>
  )
}

As shown below, specifying prefetch={false} prevents the linked page from being revalidated.

import Link from "next/link";

export default function Home() {
  return (
    <main>
      <h1>Home</h1>
      <Link href='/pageA' prefetch={false}>
       pageA
      </Link>
      <br />
      <Link href='/pageB' prefetch={false}>
       pageB
      </Link>
    </main>
  )
}
GitHubで編集を提案

Discussion