Next.js Discord

Discord Forum

Revalidating GET route handler

Unanswered
Siberian posted this in #help-forum
Open in Discord
Avatar
SiberianOP
Hey!

Does anyone know how to revalidate a cached GET endpoint in Next? With this basic code

cached/route.ts
export const GET = async (request: NextRequest) => {
  console.log("Getting /cached");
  const date = new Date();
  return NextResponse.json({ date });
};


reval/route.ts
export const dynamic = "force-dynamic";

export const GET = (req: NextRequest) => {
  console.log("Revalidating /cached");
  revalidatePath("/cached");
  revalidatePath("/cached-page");
  return NextResponse.json({ done: true });
};


cached-page/page.ts
export default function Page() {
  const date = new Date();
  return <div>{date.toString()}</div>;
}


The cached page revalidates fine, however the route handler does not.
even calling revalidatePath("/", "layout") which should revalidate everything only does so for the page.

3 Replies

Avatar
Pixiebob
export const GET = async (request: NextRequest) => {
console.log("Getting /cached");
const date = new Date();
return NextResponse.json({ date });
};
reval/route.ts:

typescript
Copy code
import { revalidatePath } from "path-to-your-utils"; // Import the revalidatePath function from your utility

export const dynamic = "force-dynamic";

export const GET = (req: NextRequest) => {
console.log("Revalidating /cached");
revalidatePath("/cached");
revalidatePath("/cached-page");
return NextResponse.json({ done: true });
};
cached-page/page.tsx:

typescript
Copy code
import { GetStaticProps } from "next";

export const getStaticProps: GetStaticProps = async () => {
// Fetch data or perform operations
const date = new Date();

return {
props: {
date: date.toString(),
},
revalidate: 1, // Revalidate the page after 1 second
};
};

const Page = ({ date }: { date: string }) => {
return <div>{date}</div>;
};

export default Page;
Avatar
risky
route handlers don't use the layout, so it probably isn't affected by it i suppose
Avatar
SiberianOP
True, but even revalidating the exact path does not work. Is there no way to do this?