Course
Third-Party Request Libraries on the Server Side
Next.js Mastery: From Fundamentals to Full-Stack
Unlock the power of Next.js with this comprehensive course! Starting with the basics, you’ll learn essential skills such as routing, data fetching, and styling. Progress through practical projects, including building your own React Notes app, to gain hands-on experience. Dive into the source code to understand the inner workings and core principles of Next.js. Perfect for developers with a basic knowledge of React and Node.js, this course ensures you’ll be ready to create high-performance full-stack applications efficiently. Join us and master Next.js, backed by industry experts and a supportive learning community.
Third-Party Request Libraries on the Server Side
Sometimes you may need to use third-party libraries that don't support or expose the fetch method (e.g., databases, CMS, or ORM clients). If you still want to leverage the caching mechanism, you can use React's cache function along with route segment options to implement request caching and revalidation.
Example:
// app/utils.jsimport { cache } from 'react';
export const getItem = cache(async (id) => { const item = await db.item.findUnique({ id }); return item;});
Now let's call getItem twice:
// app/item/[id]/layout.jsimport { getItem } from '@/utils/get-item';
export const revalidate = 3600;
export default async function Layout({ params: { id } }) { const item = await getItem(id); // ...}
// app/item/[id]/page.jsimport { getItem } from '@/utils/get-item';
export const revalidate = 3600;
export default async function Page({ params: { id } }) { const item = await getItem(id); // ...}
In this example, although getItem is called twice, it will result in only one database query.
Note: This code snippet is not fully functional. To understand the characteristics of the React Cache function in detail, refer to the article: When Next.js encounters frequent repeated database operations, remember to use React's cache function.