Add feature flags in Astro apps using Xata and Vercel
Tags: astro, vercel, database, webdev
Published: 2023-12-12 21:07:33

In this tutorial, we're going to show you how to incorporate feature flags into your Astro app using Xata and Vercel. Imagine you're working on a feature, and you want to use email addresses to define the controlled rollout of the feature. We'll guide you through setting up these feature flags in Xata, allowing for a controlled rollout of new features. This enables you to gather feedback from a select group of users before launching it more broadly. So, let's get started on enhancing your app's functionality.

### What are feature flags?

In this tutorial, we'll show you how to use feature flags in your Astro app with Xata and Vercel. Imagine you're working on a feature and want to control its release using email addresses. We'll guide you through setting up these feature flags in Xata, allowing for a controlled rollout of new features. This way, you can gather feedback from a select group of users before a broader release. Let's get started:

### Before you begin

#### Prerequisites

| Tool                                     | Description                                                                                          |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| [Xata](https://xata.io)                  | A serverless database platform for data management.                                                  |
| [Astro](https://astro.build)             | A framework that combines frontend and serverless backend capabilities for building modern web apps. |
| [Tailwind CSS](https://tailwindcss.com/) | A CSS framework for rapid and responsive styling.                                                    |
| [Vercel](https://vercel.com/)            | A cloud platform for deploying and scaling web applications.                                         |

- You will need a [Xata account](https://app.xata.io/signin)
- [Node.js 18](https://nodejs.org/en/blog/announcements/v18-release-announce) or later

### Configuring Xata

Start by [creating a Xata account](https://app.xata.io/signin), then log in to create a database.

![Sign in window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jccd6ko9hd68bwpk5tcf.png)

After creating your database, you'll need to make a table for your feature flag attributes.

![Create database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/he7y50da2hxizw8n6f6y.png)

Great! Now that you've completed that step, you should see the table in its default state, as shown below 👇🏻

![Table created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cl231tq9ac8pz3ecq2i4.png)

Let's move on to adding the feature flag with it’s relevant properties in the table you’ve created.

### Creating feature flags in Xata

In this particular example, you’ll create a feature flag that allows us to process email domains, such as `@someone.com`, `@gmail.com`, etc. and define a percentage number so that the feature flag can be rolled back whenever required.

First, add the `percentage` attribute. Click **+** and select **Integer**.

![Create feature flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu8679yl06pyayg82edj.png)

Set the column name to `percentage` and avoid any null values. Select the **Not null** option and set the default value to 51.

![Create feature flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erf8r4cwsklr0es2f48b.png)

Great! Now, let’s add the `contains` attribute. By setting up a `contains` attribute, you can target specific conditions or criteria within your app. For instance, if the attribute is set to `@someone.com`, you can tailor the app's behavior for users with email addresses containing this domain. To add the attribute, click **+** and select **String** from the dropdown.

![Create feature flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aooyq9z7j8swc18uyoz0.png)

Set the column name to `contains` and again avoid any null values. Select the `Not null` option. Choosing the string data type allows you to specify text-based conditions. Marking the field as `Not null` ensures that every record in the database has a value for this attribute, maintaining the consistency and reliability of your data. Set a default value of, for example, `@someone.com`.

![Create feature flags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9pxi7770wptmu4l0l44g.png)

Awesome! We’re now done with configuring the feature flag table and now can use it in your frontend to customize the onboarding flow.

### Setting up the project

Fork the repository by navigating to the original GitHub repository at https://github.com/rishi-raj-jain/adding-feature-flags-to-your-astro-app-with-xata-and-vercel.
Click **Fork** at the top right corner of the page. This creates a copy of the repository in your GitHub account.

Once the repository is forked, clone it to your local machine. Replace `your-username` with your GitHub username in the following command:

```sh
git clone https://github.com/rishi-raj-jain/adding-feature-flags-to-your-astro-app-with-xata-and-vercel
cd adding-feature-flags-to-your-astro-app-with-xata-and-vercel
npm install
```

## Configure Xata with Astro

To use Xata with Astro, install the Xata CLI globally:

```sh
npm install @xata.io/cli -g
```

Authorize the Xata CLI to associate with the logged in account:

```sh
xata auth login
```

![Add API key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zpfntzfvze6h4pbg11v.png)

Great! Initialize the project locally with the Xata CLI command with something like what is presented below:

```sh
xata init --db https://Rishi-Raj-Jain-s-workspace-80514q.us-east-1.xata.sh/db/feature-flags-with-astro
```

Lastly, answer some quick prompts to make the integration with Astro seamless for you.

![Terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dp22o1evuxmz3w2dqru.png)

### Configure the Astro frontend

In this section, you'll learn how to customize an onboarding flow using feature flags set in Xata. You'll implement form actions in Astro routes, fetch feature flag from Xata, and define your own onboarding logic.

#### Implement form actions in Astro

With Astro, you can also allow [transitions on form submissions](https://docs.astro.build/en/guides/view-transitions/#transitions-with-forms).

Enable form actions with view transitions in `src/layouts/Layout.astro`:

```astro
---
import { ViewTransitions } from "astro:transitions";
---

<html>
  <head>
    <ViewTransitions handleForms />
  </head>
  <body>
    <!-- Added info here -->
  </body>
</html>
```

This setup allows you to combine both backend and frontend flows for a page in Astro. Suppose you want to handle a form submission that includes the user's email, process it server-side, and display various outcomes based on your logic, all on the homepage. You can achieve this seamlessly within a single Astro route, like `src/pages/index.astro`:

```astro
---
const response = { form: false }

if (Astro.request.method === 'POST') {
  try {
    // Indicate that the request is being processed
    response.form = true

    // Get the user email from the form submissions
    const data = await Astro.request.formData()
    const userEmail = data.get('email') as string

		// Fetch feature flag from Xata

		// Define our own processing logic
  } catch (e) {
    // pass
  }
}
---

{response.form && <DisplayLogicComponent />}

<form method="post" autocomplete="off">
  <input
    required
    name="email"
    type="email"
    placeholder="Email Address (a demo)"
  />
  <button type="submit">
    Proceed &rarr;
  </button>
</form>
```

### Fetch the feature flag object from Xata

To customize the onboarding flow, the first step is to fetch the feature flag object from Xata. In this example, we’re gonna be using the `percentage` and `contains` properties of the feature flag to define our processing logic further. Using [Xata Read](https://xata.io/docs/sdk/get#getting-a-record-by-id), you can retrieve a record with a given ID, `the-flag` and destructure the relevant properties.

```astro
---
// Import the Xata Client created by Xata CLI in src/xata.js
import { XataClient } from '@/xata';

if (Astro.request.method === 'POST') {
  // ...
  // Fetch Feature from Xata

  // Create a Xata Client to fetch the flag from
  const xata = new XataClient({
    apiKey: import.meta.env.XATA_API_KEY,
    branch: import.meta.env.XATA_BRANCH
  });

  // Get the percentage property set in the flag
  // Get the contains property set in the flag
  const { percentage, contains } = await xata.db['my-flag-name'].read('the-flag');

  // Define your processing logic
  // ...
}
---
```

### Implementing your own onboarding logic

Based on the extracted values from the feature flag object, we'll onboard users whose emails end with `@someone.com`, as specified in the `contains` variable, only if the `percentage` value for this feature flag in Xata is over 30. By adjusting the `percentage` value in the \[Xata dashboard] to be above or below 30, you can effectively switch this feature flag on or off.

```astro
---
const response = { form: false, onboarded: false, userEmail: '' }

if (Astro.request.method === 'POST') {

	// ...
	// Define our processing logic

  if (userEmail) {
    response.userEmail = userEmail

    // Check if email contains the expected,
    // if yes onboard the user to a new flow
    if (percentage > 30 && userEmail.endsWith(contains)) {
      response.onboarded = true
    }

    // If not, let's not onboard the user to the new flow
    else {
      response.onboarded = false
    }
  }

}
---
<!-- Render conditional states using the onboarded flag -->
{response.form && <>{response.onboarded ? <Success /> : <Failure />}</>}
```

### Deploy to Vercel

The repository, is now ready to deploy to Vercel. Use the following steps to deploy: 👇🏻

1.  Start by creating a GitHub repository containing your app's code.
2.  Then, navigate to the Vercel Dashboard and create a **New Project**.
3.  Link the new project to the GitHub repository you just created.
4.  In **Settings**, update the _Environment Variables_ to match those in your local `.env` file.
5.  Deploy! 🚀

Way to go! You've now successfully added feature flags to you Astro app with Xata and Vercel, equipping your app for further development and success!

### What's next??

We'd love to hear from you if you have any feedback on this tutorial, if you'd like to know more about Xata, or if you would like to contribute a community blog or tutorial.
Reach out to us on [Discord](https://xata.io/discord) or join us on [X | Twitter](https://twitter.com/xata). Happy building 🦋