Documentation

API Usage

Learn how to work with APIs and integrate external services.

By default, the application uses static JSON files located in app/mocks. These serve as static data sources that can be replaced with real API endpoints in production.

Data Files

products.json

Contains data for the products items.

promocodes.json

Contains the list of promocodes.

How It Works

There are no real API requests to a server. The application reads data directly from these static JSON files. You can modify or extend them as needed.

All JSON files are exported through a single entry point — app/mocks/index.ts:

app/mocks/index.ts
export { default as products } from "./products.json";
export { default as promocodes } from "./promocodes.json";

Pages import data directly from this file:

import { products } from "~/mocks";
import { promocodes } from "~/mocks";

To switch to a real backend, follow the steps below. The approach uses Nuxt's useRuntimeConfig for environment variables and a shared useApi composable as a single entry point for all requests.

Connecting a Real API

Set Your API Base URL

Add your backend URL to .env at the project root:

.env
NUXT_PUBLIC_API_BASE=https://api.yourserver.com

Then expose it in nuxt.config.ts:

nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: "",
    },
  },
});

Variables under public are available both on the server and in the browser.

Create a Base API Composable

Create one shared composable that all others will use. It automatically picks up the base URL and attaches an authorization header if a token is present:

app/composables/useApi.ts
export const useApi = <T>(endpoint: string) => {
  const {
    public: { apiBase },
  } = useRuntimeConfig();
  const token = useCookie("auth_token");

  return useFetch<T>(`${apiBase}${endpoint}`, {
    headers: token.value ? { Authorization: `Bearer ${token.value}` } : {},
  });
};

Replace JSON Sources with Real Endpoints

Instead of pointing to app/mocks/products.json, call your real endpoint through useApi:

app/composables/useProducts.ts
export const useProducts = () => useApi("/products");

All other composables follow the same pattern — one line each.

Use the Composable in a Component

Nuxt auto-imports everything from app/composables/ — no manual imports needed:

app/components/ProductList.vue
<script setup lang="ts">
const { data: products, pending, error } = await useProducts();
</script>

<template>
  <div v-if="pending">Loading...</div>
  <div v-else-if="error">Error: {{ error }}</div>
  <ul v-else>
    <li v-for="product in products" :key="product.id">{{ product.name }}</li>
  </ul>
</template>

Summary

Keep .env out of version control — add it to .gitignore. Store your real API base URL there and access it via useRuntimeConfig. Use a single useApi composable as the base for all data fetching so that auth headers, base URLs, and other settings are defined in one place.