Vue Tutorial
How to Use a Mock API in Vue While Your Backend Is Being Built
Connect Vue to a hosted Forge API endpoint, keep the backend URL in a Vite environment variable, and replace it when your production API is ready.
You can build API-driven Vue components without waiting for the production backend. Forge API provides the hosted endpoint while Vue keeps the API location configurable through your Vite environment.
What we are building
Vue component
↓
getApiRes()
↓
VITE_API_BASE_URL
↓
Forge API
1. Create a Forge API endpoint
Create a project with a /products endpoint and use the JSON structure from the previous framework tutorials, or your own production-shaped response.
https://apis.getforgeapi.com/YOUR_PROJECT_KEY/productsNeed a hosted endpoint?
Create your mock API and use its hosted URL while developing the Vue frontend.
Create your mock API2. Store the URL in a Vite environment variable
VITE_API_BASE_URL=https://apis.getforgeapi.com/YOUR_PROJECT_KEYVITE_ variables
Vite exposes client-side environment variables using the VITE_ prefix.
3. Create the reusable API helper
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
export async function getApiRes(endpoint: string) {
const path = endpoint.replace(/^\/+/, "");
const response = await fetch(`${API_BASE_URL}/${path}`);
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
return response.json();
}The same helper can call products, users, orders and other routes without duplicating the API host.
4. Fetch products from a Vue component
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getApiRes } from "./services/api";
type Product = {
id: number;
name: string;
price: number;
inStock: boolean;
};
const products = ref<Product[]>([]);
const loading = ref(true);
const error = ref("");
onMounted(async () => {
try {
products.value = await getApiRes("products");
} catch {
error.value = "Could not load products.";
} finally {
loading.value = false;
}
});
</script>
<template>
<main>
<h1>Products</h1>
<p v-if="loading">Loading products...</p>
<p v-else-if="error">{{ error }}</p>
<ul v-else>
<li v-for="product in products" :key="product.id">
<strong>{{ product.name }}</strong>
— ${{ product.price }}
</li>
</ul>
</main>
</template>Vue can keep moving
Your components now have predictable API data while backend development continues independently.
5. Switch to your production API
VITE_API_BASE_URL=https://api.example.comKeep the same endpoint paths and response contract and the Vue component does not need to know that the backend changed.
Next steps
Use this approach with composables, Pinia stores, router-driven pages, or any other part of your Vue application that depends on API data.