placeholder

Headless wordpress + NextJs app

29 Sept 2024

Ernesto Ballon

Ernesto Ballon

5 min read

In this video we are gonna learn to configure nextjs to act as backend for nextjs blog, after video there is a extra content no describe in the video of how to configure hooks for wordpress.

Adding hook to wodpress

Here is the code to add to you functions.php file , inside your theme editor:

/**
 * web-hook for next js.
 */

function send_webhook_on_post_update($post_id, $post, $update) {
    // Only send webhook if this is an update, not a new post
    if (!$update) return;

    // Replace with your Next.js API route URL
    $webhook_url = 'https://www.ernestoballon.com/blog/api/revalidate';

    wp_remote_post($webhook_url, array(
        'body' => json_encode(array(
            'post_id' => $post_id,
			'post_slug'=> $post_slug,
            'secret' => 'secret_key'
        )),
        'headers' => array('Content-Type' => 'application/json'),
    ));
}

add_action('save_post', 'send_webhook_on_post_update', 10, 3);

Click in “Update File” and Done

Adding revalidation call to next.js for posts/[slug] route

Create a endpoint in Next.js, and add the following code:

import { revalidatePath } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { post_slug, secret } = body;
    // Check for secret to confirm this is a valid request
    if (secret !== "secret_key") {
      return NextResponse.json({ message: "Invalid token" }, { status: 401 });
    }
    // Revalidate the specific post
    if (!post_slug) {
      NextResponse.json({ message: "Need post_slug to update " }, { status: 400 });
    }
    // If no specific post_id, revalidate all posts
    revalidatePath(`/blog`);
    revalidatePath(`/blog/${post_slug}`);

    return NextResponse.json({ message: "Revalidation successful" }, { status: 200 });
  } catch (err) {
    // If there was an error, Next.js will continue
    // to show the last successfully generated page
    return NextResponse.json({ message: "Error revalidating" }, { status: 500 });
  }
}

Save and push and when you hit your new endpoint the content in that route show be revalidated.

Remenber this is a complement to the youtube video on top.

Happy coding!