My application has an API that has dice roll function it works as intended when running in development mode but when I build for production the data in the first API call becomes cached and the data on the page is not updated when the API is called for a second time.
Dice roll function/API
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const diceRollCalc = (min: number, max: number): number => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
};
const result = diceRollCalc(1, 6);
const response = NextResponse.json(result);
response.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate');
return response;
}
This is the react component that fetches the API
'use client'
import { useEffect, useState } from 'react';
function diceRoll() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('/api/diceRoll', {
cache: 'no-store',
headers: {
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
"CacheControl": "no-cache",
}
} );
const data = await response.json();
setData(data);
};
fetchData();
}, []);
const handleButtonClick = async () => {
const response = await fetch('/api/diceRoll');
const data = await response.json();
setData(data);
};
return (
<div>
{data && <p>Result: {data}</p>}
<button onClick={handleButtonClick}>Click me</button>
</div>
);
}
export default diceRoll;
This is my page
import React from 'react';
import DiceRoll from './diceRollClient';
export default function page() {
return (
<div id='main'>
<h1>Dice</h1>
<DiceRoll/>
</div>
);
}
I apologise if this is trivial as I am still learning.
Here are the response headers in the API Request for Development mode and Production Build
Development Mode
Connection keep-alive
Keep-Alive timeout=5
Transfer-Encoding chunked
cache-control no-cache, no-store, must-revalidate
content-type application/json
vary RSC, Next-Router-State-Tree, Next-Router-Prefetch
Production Build
Connection keep-alive
Keep-Alive timeout=5
Transfer-Encoding chunked
cache-control no-cache, no-store, must-revalidate
content-type application/json
vary RSC, Next-Router-State-Tree, Next-Router-Prefetch
x-nextjs-cache HIT
let data = await fetch('https://api.vercel.app/blog', { cache: 'no-store' })
For more details checkout official documentation