revalidatePath not working as expected?
Unanswered
American Sable posted this in #help-forum
American SableOP
Anyone able to help me figure out why my api route isn't revalidating my path when called?
I have a route /api/v1/revalidate/collection-item, which when called does
An example path would be /blogs/my-blog
in my project this is a dynamic route /blogs/[slug]
This is my hook in my blogs collection. (Payload)
I perfectly fine recieve the request, and i can see in my logs that both console.log(Revalidating path: ${path}); and console.log(Revalidation request sent for /blogs/${slug}); are called.
I have a route /api/v1/revalidate/collection-item, which when called does
import { revalidatePath } from 'next/cache';
import type { NextRequest } from 'next/server';
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path');
if (path) {
console.log(`Revalidating path: ${path}`);
revalidatePath(path);
return Response.json({ revalidated: true, now: Date.now() });
}
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',
});
}
An example path would be /blogs/my-blog
in my project this is a dynamic route /blogs/[slug]
This is my hook in my blogs collection. (Payload)
hooks: {
afterChange: [
// async call baseurl/api/v1/revalidate/collection-item?path=/blogs/${slug}
async ({ doc }) => {
try {
const document = doc as Blog | null;
const documentStatus = document?._status;
if (documentStatus === 'published') {
const slug = doc?.slug?.toString();
console.log(`Revalidating blog: /blogs/${slug}`);
if (slug) {
const response = await fetch(`${baseUrl}/api/v1/revalidate/collection-item?path=/blogs/${slug}`, {
method: 'GET',
});
if (!response.ok) {
console.error('Failed to revalidate:', response.statusText);
}
console.log(`Revalidation request sent for /blogs/${slug}`);
}
}
} catch (error) {
console.error('Error in afterChange hook for blogs:', error);
}
},
],
},
I perfectly fine recieve the request, and i can see in my logs that both console.log(Revalidating path: ${path}); and console.log(Revalidation request sent for /blogs/${slug}); are called.
3 Replies
American SableOP
My page (left out imports cause too long message :D)
export const revalidate = 600;
export async function generateStaticParams() {
return await GetStaticParams({
collection: 'blogs',
});
}
export async function generateMetadata({ params: paramsPromise }: { params: Promise<{ blog: string }> }) {
const { blog } = await paramsPromise;
const blogData = (await getCachedCollectionData({
slug: blog,
collection: 'blogs',
})()) as Blog;
return getMetaData(blogData?.meta as Meta);
}
export default async function PageComponent({ params: paramsPromise }: { params: Promise<{ blog: string }> }) {
const { isEnabled: draft } = await draftMode();
const { blog } = await paramsPromise;
const blogData = (await getCachedCollectionData({
slug: blog,
collection: 'blogs',
})()) as Blog;
console.log('Blog data:', blogData);
if (!blogData) {
console.warn(`Blog with slug "${blog}" not found.`);
return <Redirects url={`/blogs/${blog}`} />;
}
const { heroFields, articles } = blogData;
const articlesData = (articles?.docs as Article[]) || [];
const jsonLdWebPageSchema = JsonLdService.generateWebPageSchema(blogData.meta as Meta);
return (
<main>
<Redirects
url={`/blogs/${blog}`}
disableNotFound
/>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLdWebPageSchema) }}
/>
<Hero content={heroFields} />
<ArticlesOverview
articles={articlesData}
blogSlug={blog}
/>
{draft && <LivePreviewListener />}
</main>
);
}
American SableOP
Update. Seems to be working fine locally with npm run build and npm run start.
Just does not work when my app is deployed
Just does not work when my app is deployed
American SableOP
I figured it out.
It was due to some weird caching with digital ocean. I had to set cache control: no-store in my middleware to get my revalidation to work.
Not perfect, however now it works.
Just need to figure out the best way to set the header conditionally now
It was due to some weird caching with digital ocean. I had to set cache control: no-store in my middleware to get my revalidation to work.
Not perfect, however now it works.
Just need to figure out the best way to set the header conditionally now