Allow for scheduled cache refresh?
Answered
Ichneumonid wasp posted this in #help-forum
Ichneumonid waspOP
I am working on adding a blog to my personal website and I have a separate locally hosted "admin website" for the blog page that I can add and modify the blogs from (blogs are hosted on mongoDB). This works great in development when there is no cache and everything updates accordingly on my personal website (when locally hosted) but when I build my website on Heroku where I am hosting it for production and I then go to add another blog, the production release won't take into account this new blog and only shows blogs up to the time it was built. Using postman I can that sending request to domain.com/api/blog hits the nextjs cache and only returns blogs up to the time is was deployed. I was wondering how I can allow for scheduled cache updates or no cache at all?
Here is an example of the code that is supposed to be returning all blog entries from the database:
export const GET = async (req: Request, res: NextResponse) => {
try {
await connectDB();
const post = await prisma.post.findMany();
return NextResponse.json({message: "Data fetched successfully", post}, {status: 200})
} catch (err) {
return NextResponse.json({message: "Error fetching data", err}, {status: 500})
} finally{
await disconnectDB();
}
};
Here is an example of the code that is supposed to be returning all blog entries from the database:
export const GET = async (req: Request, res: NextResponse) => {
try {
await connectDB();
const post = await prisma.post.findMany();
return NextResponse.json({message: "Data fetched successfully", post}, {status: 200})
} catch (err) {
return NextResponse.json({message: "Error fetching data", err}, {status: 500})
} finally{
await disconnectDB();
}
};
Answered by joulev
Scheduled updates every 10 seconds:
export const revalidate = 10
No cache at all:
export const revalidate = 0
export const revalidate = 10
No cache at all:
export const revalidate = 0
5 Replies
Ichneumonid waspOP
Thanks for the response! Just to clarify, would I add export const revalidate = 10 route.ts file in my api or would I add it when I call get in my page.tsx file (see code for that below)
async function fetchBlogs(): Promise<Post[]> {
const res = await fetch("/api/blog", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
const data = await res.json();
return data.post;
}
async function fetchBlogs(): Promise<Post[]> {
const res = await fetch("/api/blog", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
const data = await res.json();
return data.post;
}
Also this refreshes the X-Nextjs-Cache and gets new information from the database and not just asks the page to pull from domain.com/api/blog again?
Ichneumonid waspOP
That worked thank you!