Finally, an edge runtime that works out-of-the-box with Next.js, Remix, Nuxt, and more. Check it out!

Guides & Tutorials

Create sites programmatically with the Netlify API

Guides & Tutorials

Create sites programmatically with the Netlify API

There's a few different ways to create a site on Netlify. You can do so by clicking a few buttons in the UI, drag and drop a folder on Netlify Drop, or running a few commands in the CLI. But there's one more way; you can also create new sites programmatically using the Netlify API, in a single command!

First, you need to start by installing and importing the netlify package.

To install it, run npm install netlify or yarn add netlify. Then, import it with import NetlifyAPI from "netlify".

Once this is done, you'll need to instantiate a new NetlifyAPI object and pass it a Netlify token to be able to authenticate.
To find your Netlify token, navigate to your user settings page in the Netlify UI, click on the "Applications" tab and under the "Personal access tokens" settings, generate a new access token.

const api = new NetlifyAPI(NETLIFY_TOKEN);

Once this is done, you can use the createSite method, passing it an account slug and body containing information about the repository you'd like to use and the name of your new site.

const site = await api.createSite({
account_slug: "my-awesome-team" // This should be the team you'd like your site to be under. If not specified, this will use your default team.
body: {
name: "my-new-awesome-site",
repo: {
provider: "github", // or "gitlab", "bitbucket"
repo: "username/repository",
private: false,
branch: "main",
},
}
});

The full code sample would look like this:

import NetlifyAPI from "netlify";

const api = new NetlifyAPI(NETLIFY_TOKEN);

const site = await api.createSite({
account_slug: "my-awesome-team"
body: {
name: "my-new-awesome-site",
repo: {
provider: "github",
repo: "username/repository",
private: true,
branch: "main",
},
}
});

That's it! You can use this code to create your own "Deploy to Netlify" button, or in a GitHub action to create a site automatically when you create a new repo; anything you can think of!

If you end up building anything fun, let us know!

Keep reading

Recent posts

Book cover with the title Deliver web project 10 times faster with Jamstack enterprise

Deliver web projects 10× faster

Get the whitepaper