> ## Documentation Index
> Fetch the complete documentation index at: https://cockroachlabs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy a Netlify App Built on CockroachDB

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

This tutorial shows you how to deploy a [Netlify](https://www.netlify.com/) web application that communicates with a CockroachDB Standard cluster.

The sample app used in this tutorial simulates [a gaming leaderboard](https://www.cockroachlabs.com/blog/react-typescript-cockroachdb-sample-app). The [Netlify functions](https://www.netlify.com/products/functions) used for the app are written in TypeScript. The functions use [Prisma](https://www.prisma.io/) to connect to CockroachDB. The app's frontend, also written in TypeScript, uses React, bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

The source code for the completed app is available on GitHub at [https://github.com/cockroachdb/cockroachdb-typescript](https://github.com/cockroachdb/cockroachdb-typescript).

## Before you begin

Before starting the tutorial, do the following:

1. Create a [CockroachDB Cloud](https://cockroachlabs.cloud/signup?referralId=docs_netlify) account.
2. Create a Starter [Netlify](https://app.netlify.com/signup) account. You can do this with your GitHub login credentials.

## Step 1. Create a CockroachDB Standard cluster

1. <InternalLink version="cockroachcloud" path="create-an-account">Create a CockroachDB Cloud account</InternalLink>. If this is your first CockroachDB Cloud organization, it will be credited with \$400 in <InternalLink version="cockroachcloud" path="free-trial">free trial credits</InternalLink> to get you started.
2. On the **Get Started** page, click **Create cluster**.
3. On the **Select a plan** page, select **Standard**.
4. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS).
5. In the **Regions** section, select a region for the cluster. Refer to <InternalLink version="cockroachcloud" path="regions">CockroachDB Cloud Regions</InternalLink> for the regions where CockroachDB Standard clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions.
6. Click **Next: Capacity**.
7. On the **Capacity** page, keep the <InternalLink version="cockroachcloud" path="plan-your-cluster">**Provisioned capacity**</InternalLink> at the default value of 2 vCPUs.

   Click **Next: Finalize**.
8. On the **Finalize** page, name your cluster. If an active free trial is listed in the right pane, you will not need to add a payment method, though you will need to do this by the <InternalLink version="cockroachcloud" path="free-trial#add-payment-methods">end of the trial</InternalLink> to maintain your organization's clusters.

   Click **Create cluster**.

   Your cluster will be created in a few seconds and the **Create SQL user** dialog will display.

<a id="connection-string" />

After the cluster is created, the **Connection info** window appears. Click the **Connection string** tab and copy the connection string to a secure location. You will use this connection string to connect to CockroachDB later in the tutorial.

<Note>
  The connection string is pre-populated with your username, cluster name, and other details, including your password. Your password, in particular, will be provided only once. Save it in a secure place (we recommend a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster/<CLUSTER ID>/users`.
</Note>

## Step 2. Get the code

1. Clone the code's GitHub repo:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ git clone git@github.com:cockroachdb/cockroachdb-typescript.git
   ```

   The project has the following directory structure:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   ├── LICENSE.md
   ├── README.md
   ├── netlify
   │   └── functions
   │       ├── addScore.ts
   │       ├── getPlayers.ts
   │       └── getScores.ts
   ├── package-lock.json
   ├── package.json
   ├── prisma
   │   ├── schema.prisma
   │   └── seed.ts
   ├── public
   ├── src
   └── tsconfig.json
   ```

   In this tutorial, we focus on the files in the `netlify` and `prisma` directories.
2. At the top of the repo directory, fork the repo:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ gh repo fork --remote
   ```

   To deploy your code to Netlify, you need to have your own repo or your own fork of the existing repo.

## Step 3. Initialize the database

1. In the `.env` file in your project, set the `DATABASE_URL` environment variable to [the connection string](#connection-string) you obtained earlier from the CockroachDB Cloud Console:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   DATABASE_URL=<connection-string
   ```

   Prisma loads the variables defined in `.env` to the project environment.
2. Install Prisma:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   npm install prisma --save-dev
   ```
3. Run [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate) to initialize the database with the schema defined in `prisma/prisma.schema`.

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ npx prisma migrate dev --name init
   ```

   You should see the following output:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   Your database is now in sync with your schema.
   ✔ Generated Prisma Client (3.11.0 | library) to ./node_modules/@prisma/client in 87ms

   Running seed command `ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts` ...
   {
     test_player_1: { id: 1n, name: 'Test Player 1', email: 'test_player_1@example.com' },
     test_player_2: { id: 2n, name: 'Test Player 2', email: 'test_player_2@example.com' },
     test_player_3: { id: 3n, name: 'Test Player 3', email: 'test_player_3@example.com' }
   }

   🌱  The seed command has been executed.
   ```

   This command initializes [Prisma Client](https://www.prisma.io/docs/concepts/components/prisma-client) to communicate with your CockroachDB cluster, based on the configuration in the `prisma/schema.prisma` file. The command also seeds your database with some sample data, using the script defined in `prisma/seed.ts`.

## Step 4. Deploy the application

You can deploy web applications directly from GitHub to Netlify. In this tutorial, we use the [Netlify CLI](https://docs.netlify.com/cli/get-started) to deploy the app.

1. Install the `netlify` CLI:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ npm install netlify-cli -g
   ```
2. Sign into your Netlify account:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ netlify login
   ```
3. Run the app server locally to preview your site:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ netlify dev
   ```

   If the local deployment succeeds, you should see the following message in your terminal:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   ┌─────────────────────────────────────────────────┐
   │                                                 │
   │   ◈ Server now ready on http://localhost:8888   │
   │                                                 │
   └─────────────────────────────────────────────────┘
   ```

   For a preview of the site, visit [http://localhost:8888](http://localhost:8888/).

   Interacting with the site triggers the Netlify functions defined in the `netlify/functions` directory. These functions use Prisma Client to run <InternalLink path="selection-queries">`SELECT`</InternalLink> and <InternalLink path="insert">`INSERT`</InternalLink> queries against the database:

   * [`getScores.ts`](https://raw.githubusercontent.com/cockroachdb/cockroachdb-typescript/master/netlify/functions/getScores.ts) reads all rows from the `player_scores` table and returns values in the `id`, `name`, and `score` columns.
   * [`getPlayers.ts`](https://raw.githubusercontent.com/cockroachdb/cockroachdb-typescript/master/netlify/functions/getPlayers.ts) reads and returns all rows from the `players` table.
   * [`addScore.ts`](https://raw.githubusercontent.com/cockroachdb/cockroachdb-typescript/master/netlify/functions/addScore.ts) writes new scores to the `player_scores` table.
4. Deploy your app with the Netlify CLI:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ netlify deploy
   ```

   Choose to create a new site, and then select the default options for each of the subsequent prompts. You will be required to authorize Netlify with GitHub.

   After the app is deployed, you should see the following message:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   ✔ Deploy is live!
   ```
5. Navigate to the admin URL for your site:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ netlify open
   ```

   From the **Site overview** page, you can manage your site. The **Site overview** page also provides you with a public URL for your site.

## See also

* [How to build a Complete Webapp with React, TypeScript & CockroachDB](https://www.cockroachlabs.com/blog/react-typescript-cockroachdb-sample-app#deploy-the-application-to-netlify)
* <InternalLink path="build-a-nodejs-app-with-cockroachdb-prisma">Build a Simple CRUD Node.js App with CockroachDB and Prisma Client</InternalLink>

You might also be interested in the following pages:

* <InternalLink path="connection-parameters">Client Connection Parameters</InternalLink>
* <InternalLink path="connection-pooling">Connection Pooling</InternalLink>
* <InternalLink path="demo-replication-and-rebalancing">Data Replication</InternalLink>
* <InternalLink path="demo-fault-tolerance-and-recovery">Fault Tolerance & Recovery</InternalLink>
* <InternalLink path="demo-replication-and-rebalancing">Replication & Rebalancing</InternalLink>
* <InternalLink path="demo-automatic-cloud-migration">Cross-Cloud Migration</InternalLink>
* <InternalLink path="orchestrate-a-local-cluster-with-kubernetes-insecure">Automated Operations</InternalLink>
