How to Use GitHubโs Async Merge API in JavaScript
GitHubโs async merge API is now generally available. Learn how to submit, poll, and safely handle pull-request merges in JavaScript.
On this page
GitHub made its asynchronous merge API generally available on October 1, 2026, changing how applications should handle programmatic pull-request merges. Instead of waiting for one request to finish a potentially complicated merge, your application submits the merge, receives a request identifier, and checks that identifier until GitHub reports the final state. This tutorial shows how to build that flow in JavaScript without putting a GitHub token in browser code.
The API is now GitHubโs recommended programmatic merge path. It also supports stacked pull requests and merge queues, which the older synchronous merge endpoint does not support.
The async merge API changes the shape of a merge request
The older approach treated a merge like a single operation: send a request and wait for GitHub to return the result. That works when the operation finishes quickly, but it is awkward for automation when a repository has more complicated merge processing. The asynchronous API separates submission from completion, so your application can continue doing other work while GitHub processes the merge.
The basic sequence is straightforward. Your application sends a PUT request to the pull request's merge-async endpoint. A newly accepted operation normally returns HTTP 202 together with a UUID, which is the identifier for that particular merge request. Your application then uses a GET request containing that UUID to retrieve the current result.
What you need before writing the JavaScript
You need a repository containing a pull request that your authenticated account or application is allowed to merge. For a fine-grained personal access token, GitHub documents the Contents: write repository permission for both submitting an asynchronous merge and retrieving its result. Keep that token on your server rather than putting it in frontend JavaScript, because anything shipped to a browser can be inspected by the user.
You should also know the pull request number and, preferably, the current head commit SHA. The SHA is Git's identifier for the exact commit at the tip of the pull request. Supplying it gives your automation an explicit condition: if the pull request changes before the asynchronous merge is executed, GitHub can cancel the operation instead of silently merging a newer commit.
Create the server-side GitHub request
For a small JavaScript service, Node.js can make the request using its built-in HTTPS module. This keeps the example dependency-free and makes the important pieces visible: the GitHub host, API path, authentication header, request body, and response status.
const https = require("node:https");
function githubRequest(method, path, token, body = null) {
return new Promise((resolve, reject) => {
const request = https.request(
{
hostname: "api.github.com",
path,
method,
headers: {
"Accept": "application/vnd.github+json",
"Authorization": Bearer ${token},
"X-GitHub-Api-Version": "2026-03-10",
"User-Agent": "async-merge-example",...(body? {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}: {})
}
},
response => {
let data = "";
response.setEncoding("utf8");
response.on("data", chunk => {
data += chunk;
});
response.on("end", () => {
let parsed;
try {
parsed = data? JSON.parse(data): null;
} catch {
parsed = data;
}
resolve({
status: response.statusCode,
body: parsed
});
});
}
);
request.on("error", reject);
if (body) {
request.write(body);
}
request.end();
});
}The API version header in GitHub's current documentation is 2026-03-10, and GitHub recommends the application/vnd.github+json media type. Keeping both explicit makes the request easier to understand and reduces surprises when API defaults change.
GitHub Docs
Submit the pull request for asynchronous merging
The submission endpoint follows the pull-request route and ends with merge-async. The request body can contain the expected head SHA, merge method, merge action, and optional commit information for direct merges. GitHub supports merge, squash, and rebase as direct-merge methods.
async function startMerge({ owner, repo, pullNumber, token, headSha }) { const path = `/repos/${owner}/${repo}/pulls/${pullNumber}/merge-async`;
const body = JSON.stringify({
sha: headSha,
merge_method: "squash",
merge_action: "direct_merge"
});
return githubRequest("PUT", path, token, body);
}
const result = await startMerge({
owner: "OWNER",
repo: "REPOSITORY",
pullNumber: 42,
token: process.env.GITHUB_TOKEN,
headSha: "CURRENT_PULL_REQUEST_HEAD_SHA"
});
console.log(result);For a direct squash merge, this asks GitHub to merge the pull request without using a merge queue. If you want GitHub to use a configured merge queue when available, use default instead. The merge_queue option explicitly adds the pull request to a merge queue.
GitHub Docs
Read the UUID before deciding that the merge worked
A 202 response does not mean that the pull request has already been merged. It means GitHub accepted the asynchronous operation and will process it in the background. The response contains a UUID that your application needs for the next request.
if (result.status === 202) { const uuid = result.body.details.uuid;
console.log("Merge request accepted:", uuid);
} else if (result.status === 200) {
console.log("GitHub returned an immediate result:", result.body);
} else {
throw new Error(
Merge request failed with HTTP ${result.status}
);
}There are important exceptions to the normal 202 path. GitHub can return 200 when the pull request is already merged or already in a merge queue. A 409 means another asynchronous merge request is already pending for that pull request and the response provides its UUID. A 400 indicates that the pull request is not currently ready for merging, while 403, 404, and 422 represent other authorization, resource, or validation conditions.
GitHub Docs
Poll the merge result instead of waiting on the first request
Once you have the UUID, call the result endpoint with GET. A pending response tells you that GitHub is still processing the request. Your application should wait before checking again rather than hammering the endpoint continuously.
async function getMergeResult({ owner, repo, pullNumber, uuid, token }) { const path = `/repos/${owner}/${repo}/pulls/${pullNumber}/merge-async/${uuid}`;
return githubRequest("GET", path, token);
}A simple polling loop can now stop only when the operation reaches a terminal state. The documented result states are pending, merged, enqueued, and failed. An enqueued result is especially important: it means the pull request entered the merge queue, not that the merge has already happened.
GitHub Docs
async function waitForMerge(options) {
for (;;) {
const result = await getMergeResult(options);
if (result.status!== 200) {
throw new Error(
`Status check failed with HTTP ${result.status}`
);
}
const state = result.body.status;
if (state === "pending") {
await new Promise(resolve => setTimeout(resolve, 3000));
continue;
}
return result.body;
}
}The three-second delay here is an application choice rather than a GitHub requirement. In production, you can choose a longer interval or use an increasing delay when repeated checks are not time-sensitive. The important part is that the polling loop treats pending as an intermediate state rather than success.
Use the pull request SHA as a safety check
The sha field is more useful than it first appears. Suppose your automation checks a pull request, approves it, and then another commit is pushed before the merge worker runs. Without an explicit expected SHA, your automation risks acting on a different pull-request state than the one it inspected. GitHub's asynchronous endpoint lets you provide the SHA that the pull request head must match. If the pull request is pushed between the request and execution, GitHub cancels the merge operation.
You can obtain the current head SHA before submitting the merge and then pass that exact value into sha. For security-sensitive deployment automation, this is a much clearer boundary than assuming that a pull request number alone identifies the code you reviewed.
Understand direct merges, queues, and stacked pull requests
The merge_action field controls what GitHub should do. direct_merge requests a direct merge, merge_queue places the pull request into the merge queue, and default lets GitHub use a merge queue when one is configured for the target branch and otherwise merge directly. The choice affects what your application should consider a successful final state.
Stacked pull requests are another reason to use this API. A stacked pull request depends on other open pull requests beneath it, and GitHub says the asynchronous merge API is the required API for merging stacked pull requests. The older synchronous merge endpoint does not support stacked pull requests or merge queues.
Do not confuse accepted, merged, and enqueued
A reliable automation should report these states separately. Accepted means GitHub has received the asynchronous request. Pending means processing is still underway. Merged means the pull request reached the merged state and the response includes the merge commit SHA. Enqueued means GitHub placed the pull request into a merge queue, so another check is needed later if your application cares about the eventual merge. Failed means GitHub completed processing without merging the pull request.
This distinction matters in deployment systems. If your application starts a production deployment whenever it sees an HTTP 202, it can deploy before the merge actually exists. The deployment trigger should instead react to the terminal state that matches the workflow you are building.
Handle the response with a small state machine
Once the basic requests work, the cleanest design is to treat the merge operation as a small state machine rather than one large function. Submission creates an asynchronous operation, polling observes it, and your application maps the final state to its own workflow. This keeps HTTP errors, merge failures, and successful queueing from becoming indistinguishable.
async function mergePullRequest(options) { const submission = await startMerge(options);
if (submission.status === 200) {
return submission.body;
}
if (submission.status === 409) {
return waitForMerge({...options,
uuid: submission.body.details.uuid
});
}
if (submission.status!== 202) {
throw new Error(
Merge submission failed with HTTP ${submission.status}
);
}
return waitForMerge({...options,
uuid: submission.body.details.uuid
});
}This pattern also handles the case where another asynchronous merge is already pending. Instead of creating a second operation, the code uses the UUID returned by the 409 response and follows the existing operation.
Know what the async API does not guarantee
The asynchronous API does not turn every merge failure into a successful background job. GitHub performs basic pull-request state checks when the operation is accepted, while branch protection and repository rules are handled as part of the later merge processing. A request can therefore be accepted and subsequently fail.
The result is also temporary. GitHub retains an asynchronous merge result for 24 hours after its most recent update. After that period, the result endpoint can return 404 because the request has expired. If your application needs a permanent audit trail, store the relevant request identifier, pull request number, submitted SHA, timestamps, and final result in your own system.
There is also no reason to expose this polling machinery to a browser. A frontend can ask your backend to merge an authorized pull request, while the backend keeps the GitHub credential private and performs the asynchronous workflow. That separation also gives you a natural place to enforce your own approval checks before a merge request is submitted.
Test the workflow without assuming HTTP 202 means success
Start with a pull request that is already in a state where your account is allowed to merge it. Submit the asynchronous request and record the returned UUID. Then poll the result endpoint and verify that your application handles pending before accepting merged as a completed merge. If you are testing a merge queue, verify that enqueued is handled separately from merged.
Finally, test a stale SHA deliberately in a safe repository. This checks that your automation notices when the pull request head no longer matches the commit it intended to merge. That test is more valuable than simply confirming that a successful merge works, because it verifies the condition that prevents an asynchronous operation from acting on a changed pull request.
What to change in existing merge automation
If an application currently calls GitHub's synchronous pull-request merge endpoint and waits for the response, the main architectural change is to split that operation into submission and observation. GitHub now recommends the asynchronous endpoint instead of the synchronous REST endpoint or GraphQL mutations for programmatic merging, and it is the only merge API that supports stacked pull requests.
For a straightforward direct merge, the migration is small: send PUT to merge-async, save the UUID, poll the corresponding result endpoint, and act only on the final state. For larger automation systems, keep the UUID and expected SHA in persistent job state so a worker restart does not cause the application to lose track of an in-progress merge.
The useful mental model is simple: submitting an asynchronous merge starts a job; it does not finish one. Once your JavaScript treats the UUID as a job identifier and distinguishes pending, merged, enqueued, and failed, GitHub's new merge model becomes much easier to integrate into deployment tools, repository bots, and other developer workflows.
Share this post
Written by



