aditya rai
aditya rai

Reputation: 77

How does ISR (Incremental Static Regeneration) work in the app directory in Next.js?

In the pages directory we had ISR, which we can use to generate static pages at build time. I would like to do the same in the app directory. Is it possible? If not, can I use the pages directory alongside the app directory and do ISR in there?

Upvotes: 3

Views: 3906

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45855

As you can read on the migration guide, in the app directory, data fetching with fetch() can use the revalidate option to make ISR:

// app/page.js

export default async function Page() {
  const res = await fetch(`https://.../posts`, { next: { revalidate: 60 } })
  const posts = await res.json()
 
  return posts.map((post) => <div>{post.name}</div>)
}

And if you are not using fetch(), but something like Axios, or an ORM like Prisma, the doc suggests using route segment config, as an example like so:

// app/page.js

export const revalidate = 60 // revalidate this page every 60 seconds

export default async function Page {
  return "..."
}

Also, data can be revalidated on-demand by path with revalidatePath or by cache tag with revalidateTag. For example using Route Handler:

// app/api/revalidate/route.js

import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
 
export async function GET(request) {
  const path = request.nextUrl.searchParams.get('path') || '/'
  revalidatePath(path)
  return NextResponse.json({ revalidated: true, now: Date.now() })
}

Upvotes: 11

Related Questions