Search code examples
githubvercel

Is it possible to connect a github repo to a vercel project via their API


I have a button on my website which says create website. I want it to clone a github repo, then link that github repo to a new vercel project and deploy.

I have a problem where I can clone the repo and create a vercel project fine via their API - the issue i have is trying to link that github repo to my vercel project so I can deploy it.

Is this possible ? Have read mixed things online and docs are not that clear. Here is my code - I have a function which creates a vercel project fine and i get a projectID back - feel i should be using this somewhere to deploy.

Not sure if my API call is correct?

async function triggerDeployment(projectName:string, githubRepoUrl:string) {
  const apiUrl = "https://api.vercel.com/v13/deployments";
  const vercelToken = process.env.VERCEL_TOKEN;
  const githubToken = process.env.GITHUB_TOKEN; 

  const requestBody = {
    name: projectName,
    gitSource: {
      type: "github",
      repoId: "",
      ref: "main",
    },
    gitMetadata: {
      remoteUrl: 'https://github.com/myusername/myreponame',
    },
  };

  const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${vercelToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
  });

  console.log(response)

  if (response.ok) {
    const data = await response.json();
    console.log("Deployment triggered successfully:", data);
  } else {
  
    console.error("Failed to trigger deployment:", response.status);
  }
}

Solution

  • I was able to create a linked project by using the api along with following installing this Vercel via https://github.com/apps/vercel, e.g. something like this:

    ## Create a project
    curl -X "POST" "https://api.vercel.com/v9/projects?teamId=team_XXXXX" \
         -H 'Authorization: Bearer AUTHORISATION_TOKEN' \
         -H 'Content-Type: text/plain; charset=utf-8' \
         -d $'{
      "framework": "nextjs",
      "gitRepository": {
        "repo": "vercel/next.js",
        "type": "github"
      },
      "serverlessFunctionRegion": ["syd1"],
      "name": "my-project-name"
    }'