How to clear the whole cache #717
-
Hey everyone, I'm not sure if it's a proper place to ask this question, but I want to clear the whole cache with an API call in my next.js app. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hey @aryan-mehrabi! Currently, there's no direct way to clear the entire cache (cache from all Handlers simultaneously) from the Next.js API. However, you can implement a workaround. You can create an API route in your Next.js app, establish a direct connection to your cache stores, and clear them from there. Please use this approach carefully; do not expose this API to the public. Example for the Redis: import { createClient, RedisFlushModes } from 'redis';
export const dynamic = 'force-dynamic';
export async function GET(): Promise<Response> {
const client = createClient({
url: process.env.REDIS_URL,
});
await client.connect();
// Use one of the following methods to flush the cache
// Important: Use only with @neshca/cache-handler >= 1.6.0
await client.flushAll(RedisFlushModes.ASYNC);
// Works with any version of @neshca/cache-handler
for await (const k of client.scanIterator({ COUNT: 100 })) {
await client.unlink(k);
}
await client.quit();
return Response.json({ status: 'ok' });
} If you've got multiple Handlers, clear each one separately. The only exception is the local cache; you can't access through the Next.js API. |
Beta Was this translation helpful? Give feedback.
-
Here my example: //api/flush-cache/route.ts
import { NextRequest } from "next/server"
import { createClient, RedisFlushModes } from "redis"
export async function GET(req: NextRequest) {
const token = req.headers.get("x-api-key")
if (token === process.env.X_API_KEY) {
const client = createClient({
url: process.env.REDIS_URL,
})
await client.connect()
await client.flushAll(RedisFlushModes.ASYNC)
await client.quit()
return Response.json({ message: "Redis cleaned" }, { status: 200 })
}
return Response.json({ message: "Unauthorized" }, { status: 401 })
} |
Beta Was this translation helpful? Give feedback.
Hey @aryan-mehrabi! Currently, there's no direct way to clear the entire cache (cache from all Handlers simultaneously) from the Next.js API. However, you can implement a workaround. You can create an API route in your Next.js app, establish a direct connection to your cache stores, and clear them from there. Please use this approach carefully; do not expose this API to the public.
Example for the Redis: