#revalidateTag with external API

1 messages · Page 1 of 1 (latest)

fallow monolithBOT
#

Hi @hasty saffron. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, using revalidateTag with server actions in Next.js is a good approach for managing data revalidation with external APIs. This approach allows you to control when and how your data is revalidated, providing more flexibility and efficiency in your application.

Here's a basic example of how you can use revalidateTag in a server action:

'use server'
 
import { revalidateTag } from 'next/cache'
 
export default async function action() {
 revalidateTag('collection')
}

In this example, revalidateTag is used to revalidate all entries associated with the tag 'collection'. This tag is associated with a fetch request in your application:

export default async function Page() {
 const res = await fetch('<https://...',> { next: { tags: ['collection'] } })
 const data = await res.json()
 // ...
}

When you call revalidateTag('collection') in your server action, it will revalidate all the data fetched with the tag 'collection'. This means that the next time you visit a page that uses this data, it will fetch the latest data from the server.

Remember, revalidateTag only invalidates the cache when the path is next visited. This means calling revalidateTag with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.

You can learn more about on-demand revalidation in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching#on-demand-revalidation).

#

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith I have a page which does multiple fetches, when using revalidateTag it revalidates all fetches.

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, that's correct. When you use revalidateTag with a specific tag, it will revalidate all fetch requests that are associated with that tag. This is a feature of Next.js's cache tagging system, which allows you to invalidate fetch requests across routes.

Here's an example:

export default async function Page() {
 const res = await fetch('<https://...',> { next: { tags: ['collection'] } })
 const data = await res.json()
 // ...
}

In this example, the fetch request is tagged with 'collection'. If you have multiple fetch requests in your page that are all tagged with 'collection', calling revalidateTag('collection') will revalidate all of these requests.

'use server'
 
import { revalidateTag } from 'next/cache'
 
export default async function action() {
 revalidateTag('collection')
}

This can be useful when you want to ensure that all data associated with a specific tag is up-to-date. However, if you want to revalidate fetch requests individually, you would need to use different tags for each request.

You can learn more about on-demand revalidation in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching#on-demand-revalidation).

#

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith but the rest of the fetches do not have any tag yet they still get revalidated

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

If fetch requests without any tags are getting revalidated when you call revalidateTag with a specific tag, it might be due to the way Next.js handles revalidation for fetch requests in a route.

According to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#time-based-revalidation), if you have multiple fetch requests in a statically rendered route, and each has a different revalidation frequency, the lowest time will be used for all requests. This means that if one fetch request is revalidated, all other fetch requests in the same route will also be revalidated, regardless of their individual revalidation settings or tags.

If you want to control the revalidation of each fetch request independently, you might need to consider dynamically rendered routes, where each fetch request will be revalidated independently.

Here's an example of how you can set the revalidation time for a fetch request:

fetch('<https://...',> { next: { revalidate: 3600 } })

In this example, the fetch request will be revalidated every 3600 seconds (1 hour).

#

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith how to prevent the revalidation entirely for specific fetches

#

@fallow monolith how to prevent the revalidation entirely for specific fetches

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To prevent revalidation entirely for specific fetch requests in Next.js, you can opt out of caching by setting the cache option in fetch to 'no-store'. This will fetch data dynamically, on every request, and won't store the data in cache, thus no revalidation will occur.

Here's an example:

fetch('<https://...',> { cache: 'no-store' })

Alternatively, you can set the revalidate option to 0 in individual fetch requests. This will also prevent the data from being revalidated.

fetch('<https://...',> { next: { revalidate: 0 } })

Remember, these options should be used carefully, as they can increase the load on your server and potentially slow down your application if you're making a lot of requests.

You can learn more about opting out of data caching in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching).

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith Explain each one of the following:

cache: 'default'
cache: 'force-cache'
cache: 'no-cache'
cache: 'no-store'
cache: 'only-if-cached'
cache: 'reload'
fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The cache option in fetch is used to control how the request interacts with the cache. Here's what each option means:

  • default: This is the default value if no cache option is provided. In Next.js, if no cache option is provided, it will default to force-cache, unless a dynamic function such as cookies() is used, in which case it will default to no-store (source (https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options)).

  • force-cache: Next.js looks for a matching request in its Data Cache. If there is a match and it is fresh, it will be returned from the cache. If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource (source (https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options)).

  • no-cache: In Next.js, the no-cache option behaves the same way as no-store. It fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource (source (https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options)).

  • no-store: Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource (source (https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options)).

  • only-if-cached: This option is not mentioned in the provided extracts, so I can't provide a confident answer about how it behaves in Next.js. In the standard Fetch API, it means that the browser should use a cached response, if one exists, and fail if there is no cached response. However, the behavior in Next.js might be different.

#
  • reload: This option is also not mentioned in the provided extracts, so I can't provide a confident answer about how it behaves in Next.js. In the standard Fetch API, it means that the browser should bypass the cache and send a fresh request to the server. Again, the behavior in Next.js might be different.

For more information about how caching works in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith When using generateStaticParams while developing on build time it uses the cached fetches

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, that's correct. When you use generateStaticParams during development, Next.js uses cached fetches to improve performance and reduce the number of requests to your server or external APIs.

The generateStaticParams function is used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time. If content is fetched within the generateStaticParams function using a fetch request, the requests are automatically memoized. This means a fetch request with the same arguments across multiple generateStaticParams, Layouts, and Pages will only be made once, which decreases build times.

Here's an example from the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#generating-static-params):

export async function generateStaticParams() {
 const posts = await fetch('<https://.../posts'>).then((res) => res.json())
 
 return posts.map((post) => ({
 slug: post.slug,
 }))
}

In this example, the fetch request is made once and the result is used to generate the static parameters for the dynamic routes.

However, if you want to bypass the cache and fetch fresh data every time you make a build, you can instruct Next.js to not cache the response to fetch by adding a { cache: 'no-store' } option to the fetch, as mentioned in this Github issue comment (https://github.com/vercel/next.js/issues/47218):

export async function generateStaticParams() {
  const posts = await fetch(
    '<https://...',> {
      cache: 'no-store'
    }
  ).then((res) => res.json());

  // ...
}
#

In this modified example, the fetch request will bypass the cache and fetch fresh data from the server every time you make a build.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith I have this code, fix it it should generate static pages on build time, cache should be bypesd on every build:

import Container from '@/components/Layout/Layout';
import Product from '@/components/Product/Product';
import { handleError } from '@/utils/GlobalUtils';
import { getProductsCategories, getProductsByCategory, ECategories } from '@local-packages/commerce';
import { notFound } from 'next/navigation';

// Dynamic segments not included in generateStaticParams will return a 404
export const dynamicParams = false;
// export const dynamic = 'auto'

export async function generateStaticParams() {
const categories = await getProductsCategories().catch(err => {
handleError(err);
return [];
});

return categories.map((category) => ({
category: category.slug,
}));
}

export default async function page({ params }: { params: { category: string } }) {
const categories = await getProductsCategories().catch(err => {
handleError(err);
return [];
});

const categoryId = categories?.find(item => item.slug === params.category)?.id;

if(!categoryId) {
notFound();
}

const products = await getProductsByCategory(categoryId).catch(err => {
handleError(err);
return [];
});

return (
<div>
<Container>
<div className="mx-auto max-w-2xl px-4 py-16 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8">
<div className="mt-6 grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4 xl:gap-x-8">
{products?.map(product => {
return <Product key={product.id} product={product} />;
})}
</div>
</div>
</Container>
</div>
);
}

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Your code seems to be mostly correct for generating static pages at build time. However, to ensure that the cache is bypassed on every build, you should add the cache: 'no-store' option to your fetch requests.

However, the fetch requests are abstracted away in your getProductsCategories and getProductsByCategory functions, so you would need to modify these functions to include the cache: 'no-store' option.

Here's an example of how you can modify a fetch request to bypass the cache:

const res = await fetch('<https://...',> { cache: 'no-store' });

In this example, the fetch request will bypass the cache and fetch fresh data from the server every time you make a build.

Unfortunately, without seeing the implementation of your getProductsCategories and getProductsByCategory functions, I can't provide a more specific solution. You would need to modify these functions to include the cache: 'no-store' option in their fetch requests.

For more information about how caching works in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith I added cache: 'no-store' but now the fetches are triggered on every page reload

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, that's the expected behavior when you set cache: 'no-store' in your fetch requests. The no-store option tells Next.js to bypass the cache and fetch fresh data from the server on every request. This means that the data will be fetched again every time the page is reloaded.

If you want to cache the data and only re-fetch it when the page is reloaded, you can use the default or force-cache options instead. These options tell Next.js to look for a matching request in its cache and use the cached data if it's fresh. If there's no match or the cached data is stale, Next.js will fetch the data from the server and update the cache.

Here's an example:

const res = await fetch('<https://...',> { cache: 'default' });

In this example, Next.js will use the cached data if it's fresh, and fetch the data from the server if it's not.

For more information about how caching works in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith I want a static page generated which does the fetch only on build time

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To generate a static page that fetches data only at build time, you can use the getStaticProps function in Next.js. This function runs at build time in production, and fetches the data you need to pre-render your page.

Here's an example:

export async function getStaticProps() {
  const res = await fetch('<https://.../posts'>)
  const posts = await res.json()

  return {
    props: {
      posts,
    },
  }
}

export default function Page({ posts }) {
  // Render your page with the fetched posts
}

In this example, getStaticProps fetches data from an external API at build time, and passes this data to your page as a prop. The page is then pre-rendered with this data and served as a static page.

Remember, getStaticProps runs only on the server-side, which means it will never be run on the client-side and won't be included in the JS bundle for the browser. This means you can safely write server-side code directly in getStaticProps.

For more information about getStaticProps and data fetching in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/data-fetching#getstaticprops-static-generation).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith explain .next folder for me

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The .next folder is a directory that Next.js generates automatically when you run next build or next dev. It contains the built output of your Next.js application and is essential for the functioning of your Next.js app.

Here's a brief overview of what you might find in the .next folder:

  • cache: This directory is used by webpack to cache intermediate results for faster rebuilds. It's only created during development.

  • server: This directory contains the server-side render (SSR) versions of your pages, which are used when a request is made to a page.

  • static: This directory contains chunks, images, and other static resources that are created during the build process.

  • routes-manifest.json and build-manifest.json: These are metadata files that Next.js uses internally.

Remember, you should not manually alter or use the files in the .next folder in your code, as Next.js manages this folder automatically. Also, you typically don't commit this folder to version control. It's common to add .next to your .gitignore file.

For more information about the build process in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/api-reference/cli#build).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty saffron kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty saffron
#

@fallow monolith is the .next folder and cache folder created on production

fallow monolithBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, the .next folder is created in both development and production environments when you run next build. It contains the built output of your Next.js application, which is essential for running your app.

However, the cache folder inside .next is typically only created during development. This directory is used by webpack to cache intermediate results for faster rebuilds.

In a production environment, you would typically run next build to generate the .next folder and then next start to start the application. The next start command starts the application in production mode, using the built output in the .next folder.

For more information about the build process in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs/api-reference/cli#build).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: