here is how you can revalidate certain pages
in my scenario, I have the URL /jobs/[slug]
when I try to revalidate the jobs using path it also revalidates the /jobs/[slug]
now what do I do i use a tag for revalidating the /jobs and I use path for revalidating the only specific updated slug so it will not revalidate all the jobs slugs
here is the code :
create the API route in api/revalidate/route.ts:
use this code:
import { NextResponse, NextRequest } from "next/server";
import { revalidatePath, revalidateTag } from "next/cache";
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.nextUrl);
const path = searchParams.get("path");
const tag = searchParams.get("tag");
// const authHeader = req.headers.get('authorization');
// if (!isAuthorized(authHeader)) {
// return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
// }
if (!path && !tag) {
return NextResponse.json(
{ message: "Missing param path/tag" },
{ status: 400 }
);
}
try {
if (tag) {
revalidateTag(tag);
return NextResponse.json({ message: `Revalidated Tag: ${tag}` });
}
if (path) {
revalidatePath(path);
} else {
return NextResponse.json(
{ message: "Missing param path" },
{ status: 400 }
);
}
return NextResponse.json({ message: `Revalidated Path: ${path}` });
} catch (error: any) {
return NextResponse.json(
{ message: "Error revalidating", error: error.message },
{ status: 500 }
);
}
}
now in frontend where you need to call your API using fetch not Axios like this:
const url = process.env.NEXT_PUBLIC_API_URL;
export const getPublicSchema = async (tag: string) => {
try {
const response = await fetch(`${url}/your-api-end-point`, {
next: { tags: [tag] },
});
const data = await response.json();
return data;
} catch (error: any) {
console.error(error?.response?.data?.message);
return [];
}
};
now call the function in your page and make sure your page is async SSR:
like this:
const page = async () => {
const jobsData = await getPublicSchema("pass-your-tag");
return (
<>
<NewUiHomepageLayout>
<PreLoginJobs jobsData={jobsData} />
</NewUiHomepageLayout>
<FooterSection />
</>
);
};
export default page;
Now create a revalidated API in the backend:
in my, I am using nest js in the backend:
/**
* Triggers revalidation for a given path.
*
* This function initiates a revalidation process for the specified path.
* It is an asynchronous function and returns a promise that resolves when
* the revalidation is complete.
* @param path - The path to revalidate.
*/
export async function triggerRevalidation(path: string): Promise<void> {
// const revalidateUrl = `http://localhost:3000/api/revalidate?path=${path}`;
const revalidateUrl = `${process.env.FRONTEND_URL}/api/revalidate?path=${path}`;
try {
const response = await fetch(revalidateUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
console.log('Revalidation response:', await response.json());
if (!response.ok) {
console.error(`Revalidation failed: ${response.statusText}`);
} else {
console.log('Revalidation triggered successfully', path);
}
} catch (error) {
console.error('Error triggering revalidation:', error);
}
}
now call this API where you are calling your route:
like this:
/**
* Creates a new public jobs meta entry.
* @param createPublicJobsMetaDto - The data transfer object containing the details of the public jobs meta to create.
* @returns A promise that resolves to the created public jobs meta.
* @throws ConflictException if the slug is not unique.
*/
@Admin()
@Post()
async create(@Body() createPublicJobsMetaDto: CreatePublicJobsMetaDto): Promise<any> {
const newMeta = await this.publicJobsMetaService.create(createPublicJobsMetaDto);
await triggerRevalidation('/sitemap-job.xml');
await triggerRevalidationTag('public-jobs-meta-tag');
return newMeta;
}
want to hire me connect with me:
https://www.linkedin.com/in/saleem-raza/
email: [email protected]