Skip to content

Commit

Permalink
Merge pull request #16 from Dexerto/update-readme-for-app-router
Browse files Browse the repository at this point in the history
Update README.md
  • Loading branch information
humet authored May 10, 2024
2 parents 44d18a6 + b342d6a commit 95d57b9
Showing 1 changed file with 107 additions and 1 deletion.
108 changes: 107 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
Next.js On-Demand Revalidation for Wordpress on the post update, revalidate specific paths on the post update.

## Installation

### Pages Router
- In your Next.js project add new file `/pages/api/revalidate.ts` with this code:
```
```ts
import { NextApiRequest, NextApiResponse } from "next"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
Expand Down Expand Up @@ -49,6 +51,110 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
}
```
### App Router (with tags support)
- In your Next.js project add new file `/app/api/revalidate/route.ts` with this code:
```ts
import { revalidatePath, revalidateTag } from 'next/cache';
import { headers } from 'next/headers';
import { NextRequest } from 'next/server';

/**
* Constants for HTTP Status codes.
*/
const STATUS_CODES = {
UNAUTHORIZED: 401,
PRECONDITION_FAILED: 412,
INTERNAL_SERVER_ERROR: 500,
};

const { REVALIDATE_SECRET_KEY } = process.env;

if (!REVALIDATE_SECRET_KEY) {
throw new Error('Missing REVALIDATE_SECRET_KEY environment variable');
}

export async function PUT(request: NextRequest) {
const { paths, tags }: { paths?: string[]; tags?: string[] } =
await request.json();

console.log('Received paths:', paths);
console.log('Received tags:', tags);

const headersList = headers();
const authorizationHeader = headersList.get('authorization');

console.log('Authorization header:', authorizationHeader);

if (authorizationHeader !== `Bearer ${REVALIDATE_SECRET_KEY}`) {
console.error(`Invalid token: ${authorizationHeader}`);
return new Response(`Invalid token`, { status: STATUS_CODES.UNAUTHORIZED });
}

if (!paths && !tags) {
console.error(`Precondition Failed: Missing paths and tags`);
return new Response(`Precondition Failed: Missing paths and tags`, {
status: STATUS_CODES.PRECONDITION_FAILED,
});
}

let revalidatePaths: string[] = [];
let correctTags: string[] = [];

if (paths) {
revalidatePaths = paths.filter((path) => path.startsWith('/'));

console.log('Filtered correct paths:', revalidatePaths);
}

if (tags) {
correctTags = tags.filter((tag) => typeof tag === 'string');
console.log('Filtered correct tags:', correctTags);
}

try {
revalidatePaths.forEach((path) => {
revalidatePath(path);
});

correctTags.forEach((tag) => {
revalidateTag(tag);
});

console.log(
`${new Date().toJSON()} - Paths and tags revalidated: ${revalidatePaths.join(
', '
)} and ${correctTags.join(', ')}`
);

return new Response(
JSON.stringify({
revalidated: true,
message: `Paths and tags revalidated: ${revalidatePaths.join(
', '
)} and ${correctTags.join(', ')}`,
}),
{
status: 200,
headers: {
'Content-Type': 'application/json',
},
}
);
} catch (err: unknown) {
let message: string;

if (err instanceof Error) {
message = err.message;
} else {
message = 'An error occurred';
}
console.error('Revalidation error:', message);
return new Response(message, {
status: STATUS_CODES.INTERNAL_SERVER_ERROR,
});
}
}
```
- Add `REVALIDATE_SECRET_KEY` env variable to your Next.js with Revalidate Secret Key value you added in the Plugin Settings.
___

Expand Down

0 comments on commit 95d57b9

Please sign in to comment.