{"meta":{"title":"Automatically redelivering failed deliveries for a GitHub App webhook","intro":"You can write a script to handle failed deliveries of a GitHub App webhook.","product":"Webhooks","breadcrumbs":[{"href":"/en/webhooks","title":"Webhooks"},{"href":"/en/webhooks/using-webhooks","title":"Using webhooks"},{"href":"/en/webhooks/using-webhooks/automatically-redelivering-failed-deliveries-for-a-github-app-webhook","title":"Automatically redeliver for GitHub App"}],"documentType":"article"},"body":"# Automatically redelivering failed deliveries for a GitHub App webhook\n\nYou can write a script to handle failed deliveries of a GitHub App webhook.\n\n## About automatically redelivering failed deliveries\n\nThis article describes how to write a script to find and redeliver failed deliveries for a GitHub App webhook. For more information about failed deliveries, see [Handling failed webhook deliveries](/en/webhooks/using-webhooks/handling-failed-webhook-deliveries).\n\nThis example shows you:\n\n* A script that will find and redeliver failed deliveries for a GitHub App webhook\n* What credentials your script will need, and how to store the credentials securely as GitHub Actions secrets\n* A GitHub Actions workflow that can securely access your credentials and run the script periodically\n\nThis example uses GitHub Actions, but you can also run this script on your server that handles webhook deliveries. For more information, see [Alternative methods](#alternative-methods).\n\n## Storing credentials for the script\n\nThe endpoints to find and redeliver failed webhooks require a JSON web token, which is generated from the app ID and private key for your app.\n\nThe endpoints to fetch and update the value of environment variables require a personal access token, GitHub App installation access token, or GitHub App user access token. This example uses a personal access token. If your GitHub App is installed on the repository where this workflow will run and has permission to write repository variables, you can modify this example to create an installation access token during the GitHub Actions workflow instead of using a personal access token. For more information, see [Making authenticated API requests with a GitHub App in a GitHub Actions workflow](/en/apps/creating-github-apps/authenticating-with-a-github-app/making-authenticated-api-requests-with-a-github-app-in-a-github-actions-workflow).\n\n1. Find the app ID for your GitHub App. You can find the app ID on the settings page for your app. The app ID is different from the client ID. For more information about navigating to the settings page for your GitHub App, see [Modifying a GitHub App registration](/en/apps/maintaining-github-apps/modifying-a-github-app-registration#navigating-to-your-github-app-settings).\n2. Store the app ID from the previous step as a GitHub Actions secret in the repository where you want the workflow to run. For more information about storing secrets, see [Using secrets in GitHub Actions](/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets).\n3. Generate a private key for your app. For more information about generating a private key, see [Managing private keys for GitHub Apps](/en/apps/creating-github-apps/authenticating-with-a-github-app/managing-private-keys-for-github-apps).\n4. Store the private key, including `-----BEGIN RSA PRIVATE KEY-----` and `-----END RSA PRIVATE KEY-----`, from the previous step as a GitHub Actions secret in the repository where you want the workflow to run.\n5. Create a personal access token with the following access. For more information, see [Managing your personal access tokens](/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).\n   * For a fine-grained personal access token, grant the token:\n     * Write access to the repository variables permission\n     * Access to the repository where this workflow will run\n   * For a personal access token (classic), grant the token the `repo` scope.\n6. Store your personal access token from the previous step as a GitHub Actions secret in the repository where you want the workflow to run.\n\n## Adding a workflow that will run the script\n\nThis section demonstrates how you can use a GitHub Actions workflow to securely access the credentials that you stored in the previous section, set environment variables, and periodically run a script to find and redeliver failed deliveries.\n\nCopy this GitHub Actions workflow into a YAML file in the `.github/workflows` directory in the repository where you want the workflow to run. Replace the placeholders in the `Run script` step as described below.\n\n```yaml copy annotate\n#\nname: Redeliver failed webhook deliveries\n\n# This workflow runs every 6 hours or when manually triggered.\non:\n  schedule:\n    - cron: '40 */6 * * *'\n  workflow_dispatch:\n\n# This workflow will use the built in `GITHUB_TOKEN` to check out the repository contents. This grants `GITHUB_TOKEN` permission to do that.\npermissions:\n  contents: read\n\n#\njobs:\n  redeliver-failed-deliveries:\n    name: Redeliver failed deliveries\n    runs-on: ubuntu-latest\n    steps:\n      # This workflow will run a script that is stored in the repository. This step checks out the repository contents so that the workflow can access the script.\n      - name: Check out repo content\n        uses: actions/checkout@v6\n\n      # This step sets up Node.js. The script that this workflow will run uses Node.js.\n      - name: Setup Node.js\n        uses: actions/setup-node@v7\n        with:\n          node-version: '20.x'\n\n      # This step installs the octokit library. The script that this workflow will run uses the octokit library.\n      - name: Install dependencies\n        run: npm install octokit\n\n      # This step sets some environment variables, then runs a script to find and redeliver failed webhook deliveries.\n      # - Replace `YOUR_APP_ID_SECRET_NAME` with the name of the secret where you stored your app ID.\n      # - Replace `YOUR_PRIVATE_KEY_SECRET_NAME` with the name of the secret where you stored your private key.\n      # - Replace `YOUR_TOKEN_SECRET_NAME` with the name of the secret where you stored your personal access token.\n      # - Replace `YOUR_LAST_REDELIVERY_VARIABLE_NAME` with the name that you want to use for a configuration variable that will be stored in the repository where this workflow is stored. The name can be any string that contains only alphanumeric characters and `_`, and does not start with `GITHUB_` or a number. For more information, see [AUTOTITLE](/actions/learn-github-actions/variables#defining-configuration-variables-for-multiple-workflows).\n      \n      - name: Run script\n        env:\n          APP_ID: ${{ secrets.YOUR_APP_ID_SECRET_NAME }}\n          PRIVATE_KEY: ${{ secrets.YOUR_PRIVATE_KEY_SECRET_NAME }}\n          TOKEN: ${{ secrets.YOUR_TOKEN_SECRET_NAME }}\n          LAST_REDELIVERY_VARIABLE_NAME: 'YOUR_LAST_REDELIVERY_VARIABLE_NAME'\n          \n          WORKFLOW_REPO: ${{ github.event.repository.name }}\n          WORKFLOW_REPO_OWNER: ${{ github.repository_owner }}\n        run: |\n          node .github/workflows/scripts/redeliver-failed-deliveries.mjs\n```\n\n## Adding the script\n\nThis section demonstrates how you can write a script to find and redeliver failed deliveries.\n\nCopy this script into a file called `.github/workflows/scripts/redeliver-failed-deliveries.mjs` in the same repository where you saved the GitHub Actions workflow file above.\n\n```javascript copy annotate\n// This script uses GitHub's Octokit SDK to make API requests. For more information, see [AUTOTITLE](/rest/guides/scripting-with-the-rest-api-and-javascript).\nimport { App, Octokit } from \"octokit\";\n\n//\nasync function checkAndRedeliverWebhooks() {\n  // Get the values of environment variables that were set by the GitHub Actions workflow.\n  const APP_ID = process.env.APP_ID;\n  const PRIVATE_KEY = process.env.PRIVATE_KEY;\n  const TOKEN = process.env.TOKEN;\n  const LAST_REDELIVERY_VARIABLE_NAME = process.env.LAST_REDELIVERY_VARIABLE_NAME;\n  \n  const WORKFLOW_REPO_NAME = process.env.WORKFLOW_REPO;\n  const WORKFLOW_REPO_OWNER = process.env.WORKFLOW_REPO_OWNER;\n\n  // Create an instance of the octokit `App` using the app ID and private key values that were set in the GitHub Actions workflow.\n  //\n  // This will be used to make API requests to the webhook-related endpoints.\n  const app = new App({\n    appId: APP_ID,\n    privateKey: PRIVATE_KEY,\n  });\n\n  // Create an instance of `Octokit` using the token values that were set in the GitHub Actions workflow.\n  //\n  // This will be used to update the configuration variable that stores the last time that this script ran.\n  const octokit = new Octokit({ \n    auth: TOKEN,\n  });\n\n  try {\n    // Get the last time that this script ran from the configuration variable. If the variable is not defined, use the current time minus 24 hours.\n    const lastStoredRedeliveryTime = await getVariable({\n      variableName: LAST_REDELIVERY_VARIABLE_NAME,\n      repoOwner: WORKFLOW_REPO_OWNER,\n      repoName: WORKFLOW_REPO_NAME,\n      octokit,\n    });\n    const lastWebhookRedeliveryTime = lastStoredRedeliveryTime || (Date.now() - (24 * 60 * 60 * 1000)).toString();\n\n    // Record the time that this script started redelivering webhooks.\n    const newWebhookRedeliveryTime = Date.now().toString();\n\n    // Get the webhook deliveries that were delivered after `lastWebhookRedeliveryTime`.\n    const deliveries = await fetchWebhookDeliveriesSince({lastWebhookRedeliveryTime, app});\n\n    // Consolidate deliveries that have the same globally unique identifier (GUID). The GUID is constant across redeliveries of the same delivery.\n    let deliveriesByGuid = {};\n    for (const delivery of deliveries) {\n      deliveriesByGuid[delivery.guid]\n        ? deliveriesByGuid[delivery.guid].push(delivery)\n        : (deliveriesByGuid[delivery.guid] = [delivery]);\n    }\n\n    // For each GUID value, if no deliveries for that GUID have been successfully delivered within the time frame, get the delivery ID of one of the deliveries with that GUID.\n    //\n    // This will prevent duplicate redeliveries if a delivery has failed multiple times.\n    // This will also prevent redelivery of failed deliveries that have already been successfully redelivered.\n    let failedDeliveryIDs = [];\n    for (const guid in deliveriesByGuid) {\n      const deliveries = deliveriesByGuid[guid];\n      const anySucceeded = deliveries.some(\n        (delivery) => delivery.status === \"OK\"\n      );\n      if (!anySucceeded) {\n        failedDeliveryIDs.push(deliveries[0].id);\n      }\n    }\n\n    // Redeliver any failed deliveries.\n    for (const deliveryId of failedDeliveryIDs) {\n      await redeliverWebhook({deliveryId, app});\n    }\n\n    // Update the configuration variable (or create the variable if it doesn't already exist) to store the time that this script started.\n    // This value will be used next time this script runs.\n    await updateVariable({\n      variableName: LAST_REDELIVERY_VARIABLE_NAME,\n      value: newWebhookRedeliveryTime,\n      variableExists: Boolean(lastStoredRedeliveryTime),\n      repoOwner: WORKFLOW_REPO_OWNER,\n      repoName: WORKFLOW_REPO_NAME,\n      octokit,\n      });\n\n    // Log the number of redeliveries.\n    console.log(\n      `Redelivered ${\n        failedDeliveryIDs.length\n      } failed webhook deliveries out of ${\n        deliveries.length\n      } total deliveries since ${Date(lastWebhookRedeliveryTime)}.`\n    );\n  } catch (error) {\n    // If there was an error, log the error so that it appears in the workflow run log, then throw the error so that the workflow run registers as a failure.\n    if (error.response) {\n      console.error(\n        `Failed to check and redeliver webhooks: ${error.response.data.message}`\n      );\n    }\n    console.error(error);\n    throw(error);\n  }\n}\n\n// This function will fetch all of the webhook deliveries that were delivered since `lastWebhookRedeliveryTime`.\n// It uses the `octokit.paginate.iterator()` method to iterate through paginated results. For more information, see [AUTOTITLE](/rest/guides/scripting-with-the-rest-api-and-javascript#making-paginated-requests).\n//\n// If a page of results includes deliveries that occurred before `lastWebhookRedeliveryTime`,\n// it will store only the deliveries that occurred after `lastWebhookRedeliveryTime` and then stop.\n// Otherwise, it will store all of the deliveries from the page and request the next page.\nasync function fetchWebhookDeliveriesSince({lastWebhookRedeliveryTime, app}) {\n  const iterator = app.octokit.paginate.iterator(\n    \"GET /app/hook/deliveries\",\n    {\n      per_page: 100,\n      headers: {\n        \"x-github-api-version\": \"2026-03-10\",\n      },\n    }\n  );\n\n  const deliveries = [];\n\n  for await (const { data } of iterator) {\n    const oldestDeliveryTimestamp = new Date(\n      data[data.length - 1].delivered_at\n    ).getTime();\n\n    if (oldestDeliveryTimestamp < lastWebhookRedeliveryTime) {\n      for (const delivery of data) {\n        if (\n          new Date(delivery.delivered_at).getTime() > lastWebhookRedeliveryTime\n        ) {\n          deliveries.push(delivery);\n        } else {\n          break;\n        }\n      }\n      break;\n    } else {\n      deliveries.push(...data);\n    }\n  }\n\n  return deliveries;\n}\n\n// This function will redeliver a failed webhook delivery.\nasync function redeliverWebhook({deliveryId, app}) {\n  await app.octokit.request(\"POST /app/hook/deliveries/{delivery_id}/attempts\", {\n    delivery_id: deliveryId,\n  });\n}\n\n// This function gets the value of a configuration variable.\n// If the variable does not exist, the endpoint returns a 404 response and this function returns `undefined`.\nasync function getVariable({ variableName, repoOwner, repoName, octokit }) {\n  try {\n    const {\n      data: { value },\n    } = await octokit.request(\n      \"GET /repos/{owner}/{repo}/actions/variables/{name}\",\n      {\n        owner: repoOwner,\n        repo: repoName,\n        name: variableName,\n      }\n    );\n    return value;\n  } catch (error) {\n    if (error.status === 404) {\n      return undefined;\n    } else {\n      throw error;\n    }\n  }\n}\n\n// This function will update a configuration variable (or create the variable if it doesn't already exist). For more information, see [AUTOTITLE](/actions/learn-github-actions/variables#defining-configuration-variables-for-multiple-workflows).\nasync function updateVariable({\n  variableName,\n  value,\n  variableExists,\n  repoOwner,\n  repoName,\n  octokit,\n}) {\n  if (variableExists) {\n    await octokit.request(\n      \"PATCH /repos/{owner}/{repo}/actions/variables/{name}\",\n      {\n        owner: repoOwner,\n        repo: repoName,\n        name: variableName,\n        value: value,\n      }\n    );\n  } else {\n    await octokit.request(\"POST /repos/{owner}/{repo}/actions/variables\", {\n      owner: repoOwner,\n      repo: repoName,\n      name: variableName,\n      value: value,\n    });\n  }\n}\n\n// This will execute the `checkAndRedeliverWebhooks` function.\n(async () => {\n  await checkAndRedeliverWebhooks();\n})();\n\n```\n\n## Testing the script\n\nYou can manually trigger your workflow to test the script. For more information, see [Manually running a workflow](/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow) and [Using workflow run logs](/en/actions/how-tos/monitor-workflows/use-workflow-run-logs).\n\n## Alternative methods\n\nThis example used GitHub Actions to securely store credentials and to run the script on a schedule. However, if you prefer to run this script on your server than handles webhook deliveries, you can:\n\n* Store the credentials in another secure manner, such as a secret manager like [Azure key vault](https://azure.microsoft.com/products/key-vault). You will also need to update the script to access the credentials from their new location.\n* Run the script on a schedule on your server, for example by using a cron job or task scheduler.\n* Update the script to store the last run time somewhere that your server can access and update. If you choose not to store the last run time as a GitHub Actions secret, you do not need to use a personal access token, and you can remove the API calls to access and update the configuration variable."}