Using Next.js Revalidate Functions to Invalidate Cache
Next.js provides several built-in functions that allow you to manage the cache of your application. One of these functions is revalidatePath, which can be used to invalidate the cache for a specific path.
Next.js provides several built-in functions that allow you to manage the cache of your application. One of these functions is revalidatePath
, which can be used to invalidate the cache for a specific path. This is useful when you have made changes to the data that your page depends on, and you want to make sure that the next visitor to the page sees the updated data.
Usage of revalidatePath
The revalidatePath
function is imported from the next/cache
module. It takes a single argument, which is the path of the page you want to revalidate. Here's an example of how you can use it:
// app/actions.js
'use server'
import { revalidatePath } from 'next/cache'
export async function createArticle(article, user_id) {
// Your existing logic here...
// After creating the article, revalidate the cache
revalidatePath('/home')
revalidatePath('/blog')
}
In this example, the revalidatePath
function is called with the paths of the pages you want to revalidate. The paths are relative to the root of your application. So, if your homepage is located in the main
directory, the path would be /home
, not /main/home
.
Revalidating a Specific URL
You can revalidate a specific URL on the next page visit. Here's an example:
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/post-1')
This will revalidate the /blog/post-1
page on the next page visit.
Revalidating a Layout Path
You can also revalidate any URL that matches a provided layout file on the next page visit. This will cause pages beneath with the same layout to revalidate on the next visit. Here's an example:
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'layout')
// or with route groups
revalidatePath('/(main)/post/[slug]', 'layout')
This will revalidate any URL that matches the provided layout file on the next page visit. For example, in the above case, /blog/[slug]/[another]
would also revalidate on the next visit.
Revalidating All Data
You can also purge the Client-side Router Cache, and revalidate the Data Cache on the next page visit. Here's an example:
import { revalidatePath } from 'next/cache'
revalidatePath('/', 'layout')
This will purge the Client-side Router Cache, and revalidate the Data Cache on the next page visit.
Server Actions
You can call revalidatePath
from a Server Action. Here's an example:
// app/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
export default async function submit() {
await submitForm()
revalidatePath('/')
}
In this example, after submitting a form, the revalidatePath
function is called to revalidate the cache for the root path.
Route Handlers
You can also call revalidatePath
from a Route Handler. Here's an example:
import { revalidatePath } from 'next/cache'
import { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (path) {
revalidatePath(path)
return Response.json({ revalidated: true, now: Date.now() })
}
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',
})
}
In this example, the revalidatePath function is called with the path obtained from the request parameters. If the path is provided, the function revalidates the cache for that path and returns a success response. Otherwise, it returns a failure response.
Working with Dynamic Routes in Next.js
Next.js offers powerful support for dynamic routes, allowing you to create pages that can handle different data based on the URL. Dynamic routes are denoted by wrapping a folder's name in square brackets: [folderName]. For example, [id] or [slug]. Dynamic segments are passed as the params prop to layout, page, route, and generateMetadata functions.
Here's an example of a dynamic route:
app/blog/[slug]/page.js
In this example, [slug] is a dynamic segment. It can be replaced with any value when navigating to the page. For example, navigating to /blog/my-first-post will render the page.js file in the app/blog/[slug] directory.
Accessing Dynamic Route Parameters
You can access the dynamic route parameters in your page component using the useRouter hook from next/router. Here's an example:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return <p>Post: {router.query.slug}</p>
}
In this example, router.query.slug contains the value of the [slug] dynamic segment.
Revalidating Dynamic Routes
When you revalidate a dynamic route, you need to specify the exact path you want to revalidate. For example, if you have a dynamic blog post page at /blog/[slug], you can revalidate a specific post like so:
revalidatePath('/blog/my-first-post')
This will revalidate the /blog/my-first-post page on the next page visit.
Defining Routes in Next.js
Next.js uses a file-system based router where folders are used to define routes. Each folder represents a route segment that maps to a URL segment. To create a nested route, you can nest folders inside each other. A special page.js file is used to make route segments publicly accessible.
Here's an example of defining routes:
pages/ ├── index.js └── blog/ ├── index.js └── [slug].js
In this example, pages/index.js corresponds to the / route, pages/blog/index.js corresponds to the /blog route, and pages/blog/[slug].js corresponds to the /blog/[slug] route.
Error Handling with Dynamic Routes
When working with dynamic routes, it's important to handle errors properly. If the dynamic segment does not match any data, you should return an error response. Here's an example:
export const getStaticProps: GetStaticProps = async (context) => {
const itemID = context.params?.something;
const data = await getData();
const foundItem = data.stars.find((item: starInterface) => itemID === item.id);
if (!foundItem) {
return {
props: { hasError: true },
}
}
return {
props: {
specificStarData: foundItem
}
}
}
In this example, if foundItem is undefined, the function returns { props: { hasError: true } }. This will cause Next.js to render a custom error page.
Incremental Static Regeneration in Next.js
Incremental Static Regeneration (ISR) is a feature in Next.js that allows you to create or update static pages after you've built your site. With ISR, you can retain the benefits of static generation while scaling to millions of pages. ISR enables you to use static-generation on a per-page basis, without needing to rebuild the entire site 5.
Here's an example of how to use ISR:
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
}
}
export async function getStaticPaths() {
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: 'blocking' } will server-render pages
// on-demand if the path doesn't exist.
return { paths, fallback: 'blocking' }
}
export default Blog
In this example, getStaticProps fetches the posts and sets revalidate to 10, which means that the page will be regenerated at most once every 10 seconds. getStaticPaths is used to generate the paths for all the posts. The fallback: 'blocking' option means that if a path doesn't exist, Next.js will server-render the page on-demand.
On-Demand Revalidation
Next.js also supports On-Demand Incremental Static Regeneration, which allows you to manually purge the Next.js cache for a specific page. This makes it easier to update your site when eCommerce metadata changes (price, description, category, reviews, etc.). If revalidate is omitted in getStaticProps, Next.js will use the default value of false (no revalidation) and only revalidate the page on-demand when revalidate() is called 5.
Self-hosting ISR
Incremental Static Regeneration (ISR) works on self-hosted Next.js sites out of the box when you use next start. By default, generated assets will be stored in-memory on each pod. This means that each pod will have its own copy of the static files. Stale data may be shown until that specific pod is hit by a request. To ensure consistency across all pods, you can disable in-memory caching. This will inform the Next.js server to only leverage assets generated by ISR in the file system 5.
Conclusion
With Next.js, you have powerful tools at your disposal to manage the cache of your application. By understanding how to use functions like revalidatePath, revalidateTag, and features like Incremental Static Regeneration, you can ensure that your users always see the most up-to-date content.
Related Tags
Recommended