Strategies for Reducing the Cache in Next Js API calling(Data fetching)

import { NextResponse } from "next/server"; 
 
export const GET = async (req, res) => { 
// Add cache-busting query string or HTTP headers as needed 
const url = new URL(req.url); 
url.searchParams.set('t', Date.now()); // Optional: Cache busting 
 
try { 
const response = await fetch(url, { 
headers: { 
'Cache-Control': 'max-age=3600, must-revalidate', // Example header 
}, 
}); 
 
if (!response.ok) { 
throw new Error('API request failed'); 
} 
 
const data = await response.json(); 
 
// Optional: Cache response at server level using Next.js mechanisms 
// ... 
 
return NextResponse.json({ message: "Ok", data }, { status: 200 }); 
} catch (error) { 
return NextResponse.json({ message: "Error", err }, { status: 500 }); 
} 
}; 

 

Remember to test your changes thoroughly across different browsers and scenarios to ensure the desired caching behavior. If you require more specific guidance, feel free to provide details about your API’s usage and update frequency. 

Leave a comment

Your email address will not be published. Required fields are marked *