DEV Community

Forge API
Forge API

Posted on Originally published at getforgeapi.com

How to Connect a Lovable, Bolt or v0 Frontend to a Mock API

Disclosure: I work on Forge API, the hosted mock API service used in this tutorial. The pattern itself works with any mock or real API.

AI app builders such as Lovable, Bolt and v0 are good at producing a working UI quickly. The catch is that the data is usually hard-coded inside the component:

const products = [
  { id: 1, name: "Wireless Headphones", price: 79.99 },
  { id: 2, name: "Mechanical Keyboard", price: 109.99 },
];

export function ProductList() {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

That looks fine in the preview, but you can't test loading, error or empty states, and swapping in a real backend later means rewriting components. The fix is to put the data behind a URL now and have the component fetch it.

1. Turn the array into an endpoint

Take the same JSON your component already uses:

[
  { "id": 1, "name": "Wireless Headphones", "price": 79.99 },
  { "id": 2, "name": "Mechanical Keyboard", "price": 109.99 }
]
Enter fullscreen mode Exit fullscreen mode

Create a GET /products endpoint that returns it. With Forge API you can do this from the homepage builder without an account, and you get a URL in this format:

https://apis.getforgeapi.com/YOUR_PROJECT_KEY/products
Enter fullscreen mode Exit fullscreen mode

A no-account demo endpoint is temporary. Creating a free account keeps it.

2. Put the base URL in an environment variable

Don't paste the URL into components. Keep only the base in one variable, so switching to a real backend later is a one-line change.

What your variable is called depends on the framework the tool generated:

  • Vite projects (Lovable's default): the variable must start with VITE_.
  • Next.js projects (v0's default): browser code can only read variables starting with NEXT_PUBLIC_.
  • Bolt: its docs mention a .env file or its Secrets menu but don't name a prefix, so check package.json to see whether it's a Vite or Next.js project.
# Vite
VITE_API_BASE_URL=https://apis.getforgeapi.com/YOUR_PROJECT_KEY

# Next.js
NEXT_PUBLIC_API_BASE_URL=https://apis.getforgeapi.com/YOUR_PROJECT_KEY
Enter fullscreen mode Exit fullscreen mode

These are public values that end up in the browser bundle, so never put a real secret in them.

3. Ask the AI tool to make the change

Instead of rewriting the component yourself, give the tool a precise prompt:

Move the hard-coded product data out of this app and load it from an API.

- The API base URL is in an environment variable: VITE_API_BASE_URL
  (use NEXT_PUBLIC_API_BASE_URL instead if this is a Next.js project).
- GET {base URL}/products returns the same JSON array as the current data.
- Create one small fetch helper in src/lib/api.ts that throws an error with
  the HTTP status when response.ok is false.
- In the component, show a loading message, an error message with a
  "Try again" button, an empty state, and the list.
- Keep the existing types, field names and styling. Do not add a backend,
  a database or any API keys.
Enter fullscreen mode Exit fullscreen mode

The result should look like this. First the helper:

// src/lib/api.ts
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

export class ApiError extends Error {
  constructor(
    readonly status: number,
    message: string,
  ) {
    super(message);
    this.name = "ApiError";
  }
}

export async function getJson<T>(path: string, signal?: AbortSignal): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${path}`, { signal });

  if (!response.ok) {
    const body = await response.json().catch(() => null);
    throw new ApiError(
      response.status,
      body?.error?.message ?? `Request failed with status ${response.status}`,
    );
  }

  return (await response.json()) as T;
}
Enter fullscreen mode Exit fullscreen mode

In a Next.js project, read the URL with process.env.NEXT_PUBLIC_API_BASE_URL instead of import.meta.env.

Then the component:

// src/components/ProductList.tsx
import { useEffect, useState } from "react";

import { ApiError, getJson } from "../lib/api";

type Product = {
  id: number;
  name: string;
  price: number;
};

export function ProductList() {
  const [products, setProducts] = useState<Product[] | null>(null);
  const [error, setError] = useState("");
  const [reloadKey, setReloadKey] = useState(0);

  useEffect(() => {
    const controller = new AbortController();

    setProducts(null);
    setError("");

    getJson<Product[]>("/products", controller.signal)
      .then(setProducts)
      .catch((caught: unknown) => {
        if (controller.signal.aborted) return;
        setError(
          caught instanceof ApiError && caught.status === 404
            ? "We could not find any products."
            : "Something went wrong. Please try again.",
        );
      });

    return () => controller.abort();
  }, [reloadKey]);

  if (error) {
    return (
      <div role="alert">
        <p>{error}</p>
        <button type="button" onClick={() => setReloadKey((key) => key + 1)}>
          Try again
        </button>
      </div>
    );
  }

  if (!products) return <p role="status">Loading products…</p>;

  if (products.length === 0) return <p>No products yet.</p>;

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name} — ${product.price.toFixed(2)}
        </li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

4. Test the failure states

The point of a mock API is that you can check what your UI does when things go wrong. Create extra endpoints that return a 404 and a 500, then ask the AI tool to point the list at each one:

Add handling for API failures to the product list:

- 404 from GET /products-missing: show "We could not find any products."
- 500 from GET /products-error: show "Something went wrong" and a retry button.
- Never show raw error objects or stack traces to the user.

Temporarily point the list at each path so I can check every state, then
switch it back to /products.
Enter fullscreen mode Exit fullscreen mode

5. Switch to the real backend

When your real API is ready and serves the same paths and JSON shapes, change only the environment variable for production builds:

Our real backend is ready at https://api.example.com. It serves the same
paths and JSON shapes as the mock API. Update the environment variable for
production builds only, and do not change any component code.
Enter fullscreen mode Exit fullscreen mode

No component changes are needed, which is the whole reason for the helper and the variable.

Where to go next

The full version of this tutorial, with a table of what each tool's docs say about environment variables and an FAQ, is on the Forge API site: Connect an AI-Built Frontend to a Mock API.

If you've hit a different snag moving AI-generated code to a real data source, tell me in the comments and I'll cover it.

Top comments (0)