Next.js - fetch() Function



The fetch() Function

The Next.js fetch() function extents the built-in fetch API to allow each request on the server to set its own persistent caching and revalidation semantics. It can be used to fetch data from an API or server in server components.

Syntax

Following is the syntax of fetch() function:

export default async function Page() {
  let data = await fetch('link/to/api', options)
  let posts = await data.json()
  return (
    <ul>
        {posts.map((post) => (
            <li key={post.id}>{post.title}</li>
        ))}
    </ul>
  )
}

Parameters

The fetch() function takes a URL and an optional options object as parameters.

  • options.cache: A string representing the cache policy for the request. It can be set to 'no-cache', 'no-store', 'reload', 'force-cache', 'only-if-cached', or 'default'.
  • options.next.revalidate: A string "false" or a number representing the number of seconds after which the data should be revalidated. It can be set to a positive integer value.
  • options.next.tags: An array of strings representing the tags for the cached data. These tags can be used to invalidate the cache on-demand.

Return Value

The fetch() function returns a Promise that resolves to the response to the request. The response can be used to access the data returned by the server.

Example 1

The following example demonstrates how to use the fetch function to fetch data from an API and render it in a server component.

export default async function Page() {
    let data = await fetch('https://jsonplaceholder.typicode.com/posts')
    let posts = await data.json()
    return (
        <ul>
            {posts.map((post) => (
                <li key={post.id}>{post.title}</li>
            ))}
        </ul>
    )
}

Example 2

The following example demonstrates how to use the fetch function with caching and revalidation options.

export default async function Page() {
    let data = await fetch('https://jsonplaceholder.typicode.com/posts', {
        cache: 'no-cache',
        next: {
            revalidate: 60,
            tags: ['posts']
        }
    })
    let posts = await data.json()
    return (
        <ul>
            {posts.map((post) => (
                <li key={post.id}>{post.title}</li>
            ))}
        </ul>
    )
}
Advertisements