Skip to content

Commit 628389d

Browse files
committed
Added revalidation docs
1 parent 9b74728 commit 628389d

File tree

1 file changed

+146
-1
lines changed

1 file changed

+146
-1
lines changed

docs/guides/frameworks/nextjs.mdx

Lines changed: 146 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,12 +248,156 @@ Here are the steps to trigger your task in the Next.js App and Pages router and
248248

249249
<DeployingYourTask />
250250

251-
## Troubleshooting
251+
## Troubleshooting & extra resources
252252

253253
<NextjsTroubleshootingMissingApiKey/>
254254
<NextjsTroubleshootingButtonSyntax/>
255255
<WorkerFailedToStartWhenRunningDevCommand/>
256256

257+
### Revalidation from your Trigger.dev tasks
258+
259+
[Revalidation](https://vercel.com/docs/incremental-static-regeneration/quickstart#on-demand-revalidation) allows you to purge the cache for an ISR route. To revalidate an ISR route from a Trigger.dev task, you have to set up a handler for the `revalidate` event. This is an API route that you can add to your Next.js app.
260+
261+
This handler will run the `revalidatePath` function from Next.js, which purges the cache for the given path.
262+
263+
The handlers are slightly different for the App and Pages router:
264+
265+
#### Revalidation helper: App Router
266+
267+
If you are using the App router, create a new revalidation route at `app/api/revalidate/path/route.ts`:
268+
269+
```ts app/api/revalidate/path/route.ts
270+
import { NextRequest, NextResponse } from "next/server";
271+
import { revalidatePath } from "next/cache";
272+
273+
export async function POST(request: NextRequest) {
274+
try {
275+
const { path, type, secret } = await request.json();
276+
// Create a REVALIDATION_SECRET and set it in your environment variables
277+
if (secret !== process.env.REVALIDATION_SECRET) {
278+
return NextResponse.json({ message: "Invalid secret" }, { status: 401 });
279+
}
280+
281+
if (!path) {
282+
return NextResponse.json({ message: "Path is required" }, { status: 400 });
283+
}
284+
285+
revalidatePath(path, type);
286+
287+
return NextResponse.json({ revalidated: true });
288+
} catch (err) {
289+
console.error("Error revalidating path:", err);
290+
return NextResponse.json({ message: "Error revalidating path" }, { status: 500 });
291+
}
292+
}
293+
```
294+
295+
#### Revalidation helper: Pages Router
296+
297+
If you are using the Pages router, create a new revalidation route at `pages/api/revalidate/path.ts`:
298+
299+
```ts pages/api/revalidate/path.ts
300+
import type { NextApiRequest, NextApiResponse } from "next";
301+
302+
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
303+
try {
304+
if (req.method !== "POST") {
305+
return res.status(405).json({ message: "Method not allowed" });
306+
}
307+
308+
const { path, secret } = req.body;
309+
310+
if (secret !== process.env.REVALIDATION_SECRET) {
311+
return res.status(401).json({ message: "Invalid secret" });
312+
}
313+
314+
if (!path) {
315+
return res.status(400).json({ message: "Path is required" });
316+
}
317+
318+
await res.revalidate(path);
319+
320+
return res.json({ revalidated: true });
321+
} catch (err) {
322+
console.error("Error revalidating path:", err);
323+
return res.status(500).json({ message: "Error revalidating path" });
324+
}
325+
}
326+
```
327+
328+
#### Revalidation task
329+
330+
This task takes a `path` as a payload and will revalidate the path you specify, using the handler you set up previously.
331+
332+
<Note>
333+
334+
To run this task locally you will need to set the `REVALIDATION_SECRET` environment variable in your `.env.local` file (or `.env` file if using Pages router).
335+
336+
To run this task in production, you will need to set the `REVALIDATION_SECRET` environment variable in Vercel, in your project settings, and also in your environment variables in the Trigger.dev dashboard.
337+
338+
</Note>
339+
340+
```ts trigger/revalidate-path.ts
341+
import { logger, task } from "@trigger.dev/sdk/v3";
342+
343+
const NEXTJS_APP_URL = process.env.NEXTJS_APP_URL; // e.g. "http://localhost:3000" or "https://my-nextjs-app.vercel.app"
344+
const REVALIDATION_SECRET = process.env.REVALIDATION_SECRET; // Create a REVALIDATION_SECRET and set it in your environment variables
345+
346+
export const revalidatePath = task({
347+
id: "revalidate-path",
348+
run: async (payload: { path: string }) => {
349+
const { path } = payload;
350+
351+
try {
352+
const response = await fetch(`${NEXTJS_APP_URL}/api/revalidate/path`, {
353+
method: "POST",
354+
headers: {
355+
"Content-Type": "application/json",
356+
},
357+
body: JSON.stringify({
358+
path: `${NEXTJS_APP_URL}/${path}`,
359+
secret: REVALIDATION_SECRET,
360+
}),
361+
});
362+
363+
if (response.ok) {
364+
logger.log("Path revalidation successful", { path });
365+
return { success: true };
366+
} else {
367+
logger.error("Path revalidation failed", {
368+
path,
369+
statusCode: response.status,
370+
statusText: response.statusText,
371+
});
372+
return {
373+
success: false,
374+
error: `Revalidation failed with status ${response.status}: ${response.statusText}`,
375+
};
376+
}
377+
} catch (error) {
378+
logger.error("Path revalidation encountered an error", {
379+
path,
380+
error: error instanceof Error ? error.message : String(error),
381+
});
382+
return {
383+
success: false,
384+
error: `Failed to revalidate path due to an unexpected error`,
385+
};
386+
}
387+
},
388+
});
389+
```
390+
391+
#### Testing the revalidation task
392+
393+
You can test your revalidation task in the Trigger.dev dashboard on the testing page, using the following payload.
394+
395+
```json
396+
{
397+
"path": "<path-to-revalidate>" // e.g. "blog"
398+
}
399+
```
400+
257401
## Additional resources for Next.js
258402

259403
<Card
@@ -265,3 +409,4 @@ Here are the steps to trigger your task in the Next.js App and Pages router and
265409
</Card>
266410

267411
<UsefulNextSteps />
412+
```

0 commit comments

Comments
 (0)