The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice - once in the generateMetadata function and again within the component itself.

Despite Next.JS's documentation stating that fetch requests are memoized throughout the request cycle, local testing reveals otherwise as the API endpoint logs show multiple hits. How can I ensure proper memoization for the fetch requests? Below is a simplified version of my component code:

// posts/[slug]/page.tsx

import {Metadata} from "next";
import {PostResponse} from "@/service/model/api";

export async function generateMetadata(props: PostPageProps): Promise<Metadata> {
    const response = await fetch(`${process.env.BASE_URL}/api/posts/slug?slug=${props.params.slug}`, {
        method: "GET",
        headers: {
            "Authorization": `Bearer ${process.env.API_KEY}`
        },
    });

    const posts: PostResponse = await response.json();

    return {
        title: posts.posts[0].title
    }
}

export default async function PostPage(props: PostPageProps) {
    const response = await fetch(`${process.env.BASE_URL}/api/posts/slug?slug=${props.params.slug}`, {
        method: "GET",
        headers: {
            "Authorization": `Bearer ${process.env.API_KEY}`
        },
    });
    const posts: PostResponse = await response.json();

    return (<div>
               <p>{posts.posts[0].title}</p>
           </div>);

}

export interface PostPageProps {
    params: PostPageParams;
}

interface PostPageParams {
    slug: string;
    text?: string;
}

Answer №1

Aha, I've finally cracked the code!

Interestingly, it seems that Next.JS/React does not cache fetch() calls when in development mode or running locally.

Once I switched to a production build, the caching worked flawlessly and only made one request to my API endpoint.

As for the why... it remains a mystery to me, but perhaps Next.JS should provide clearer documentation on this behavior.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Dragging the world map in D3 causes it to appear jumpy and erratic

I'm currently working on a Vue project to create an interactive world map that allows users to drag and zoom. I've attempted to integrate D3 for this purpose, but encountered an issue where the map jumps to the bottom right of the page whenever I ...

Encountered an error: "switch/mergeAll/flatten is not a valid function" when working with the http driver

As I delve into learning CycleJS, one thing that has caught my attention is the usage of Cycle's HTTP Driver. It seems that in order to reach the stream level, merging the response stream stream with RxJS switch/mergeAll is essential. However, when at ...

Encountering an issue with a MEAN application using Angular 2: The error message states "Cannot read property

As a first-time application developer, I am working on creating a system to manage Client profiles. Utilizing the Angular tour of heroes for the basic structure, I integrated mongodb and express components sourced from various online platforms. However, I ...

What is the correct way to assign a $scope variable after a successful ajax call?

Currently, I am working with Symfony and AngularJs 1.6.8 along with Symfony 3.4. Below is the configuration setup that I have: base.html.twig <html lang="en" data-ng-app="CeocApp" ng-controller="CeocController"> //css for the app <link id="ng ...

Obtain content from a div element using jQuery

Here is a snippet of HTML code that I am working with: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="jquery.js"></script> <scri ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

Having trouble with the margin for the first/last child in your Next.js and Tailwind CSS setup?

A similar situation arose in relation to this GitHub issue I came across. https://github.com/tailwindlabs/tailwindcss/issues/1930 In the context of Next.js and Tailwind CSS, there seems to be an issue with the First / Last child for margin not functionin ...

"Exploring the benefits of using nested mapping for res.json() in an Express application

I have been developing an express application (server-side) that offers movie information to users, and I am attempting to send a JSON response in the following format: { "title": "Star Trek: First Contact", "year": 1996, ...

Leveraging the power of Google Charts along with MySQL or

I've been working on this task for several days now and I'm still struggling to achieve the desired outcome. My goal is to dynamically create a column/bar chart using Google Charts, populated with data from my database. Here's my query: SE ...

The combination of Nest, Fastify, Fastify-next, and TypeOrm is unable to locate the next() function

In my attempt to set up Nest with Fastify and Next using the fastify-next plugin, everything went smoothly until I added TypeOrm for MongoDB integration. Upon loading the AppModule, Nest throws an error indicating that the .next() function cannot be found ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

How to change the focus on a Material UI input field

I am facing an issue with resetting/clearing an input field using a button click: Take a look at the code here for reference. const searchInput = useRef(null); const clearInput = () => { searchInput.current.value = ''; searchInput ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

Is it possible to adjust the block size for infinite scrolling in Ag-Grid?

Is there a way to adjust the block size in the scenario where the row model is set to "infinite" and a datasource is specified? For instance, when the getRows() function of the datasource is called, is it possible to define the startRow and/or endRow? The ...

Displaying JavaScript Countdown in PHP Table

I have a database table with multiple fields and I am looking to create a countdown using the integer value from one of the fields (in minutes). How can I loop through and display the countdown for each row in a PHP table utilizing these values, with the a ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...