Strapi - Build a Blog Using Strapi and Next.js

I had issues using the front end and publishing, unpublishing, or deleting an entry… I suspect the next router is the issue… But I’m not skilled in NextJS. I wrote a webhook to rebuild the next server, and restart the PM2 service. The webhook is setup in the strapi admin settings.

Set up as an express route endpoint…

import { exec } from "child_process"
import { Request, Response } from "express"
import pm2 from "pm2"

const CMD = "yarn build"
const CWD = "/CHANGE/ME"
const PM2_SERVICE_NAME = "CHANGE_ME"

let isBuilding = false

export default class WebhookController {
  // Get all crash reports
  public async blogWebHook(req: Request, res: Response): Promise<Response> {
    const { authorization } = req.headers
    if (!authorization || authorization !== process.env.BLOG_WEBHOOK_SECRET) {
      return res.status(401).json({ message: "Unauthorized" })
    }
    if (isBuilding) {
      // Return Unavailable
      return res.status(503).json({ message: "Unavailable" })
    }
    const { event } = req.body
    if (
      event === "entry.publish" ||
      event === "entry.unpublish" ||
      event === "entry.delete"
    ) {
      // Set the building flag
      isBuilding = true

      // Rebuild the blog's next server
      exec(
        CMD,
        {
          cwd: CWD,
        },
        (error, stdout, stderr) => {
          if (error) {
            console.error(error.message)
            return
          }

          if (stderr) {
            console.error(stderr)
            return
          }

          console.log(stdout)
        }
      ).addListener("exit", (code) => {
        // Unset the building flag
        isBuilding = false

        if (code === 0) {
          // Restart the blog's next server
          pm2.connect((err) => {
            if (err) {
              console.error(err)
              res
                .status(500)
                .json({ message: "PM2 Connection Error", error: err })
            }
            pm2.restart(PM2_SERVICE_NAME, (err, proc) => {
              if (err) {
                console.error(err)
                res
                  .status(500)
                  .json({ message: "PM2 Restart Error", error: err })
              }
              console.log("Next server was restarted")
              pm2.disconnect()
            })
          })
        } else {
          // Return Internal Server Error
          return res
            .status(500)
            .json({ message: "Internal Server Error", error: "Build failed" })
        }
      })
    }
    return res.status(200)
  }
}