A Nuxt front end and a Laravel API make a comfortable pair. Laravel owns the data and the rules; Nuxt renders pages on the server so they arrive as real HTML. Between them is a boundary, and most of the problems people hit with this stack happen at that boundary rather than on either side of it.
This is a walk through the decisions that keep it quiet: where configuration lives, how data is fetched once instead of twice, how errors and forms cross the gap, and what to do about CORS and images.
Two applications, one contract
Treat the two halves as separate products that happen to be developed together. They deploy independently, they can live on different servers, and they talk only over HTTP. The contract between them is the API's response shape.
If every endpoint answers with the same envelope —
{ "success": true, "data": {}, "message": null }
— then the front end needs to know that shape in exactly one place. Describe it once in TypeScript:
export interface ApiEnvelope<T> {
success: boolean
data: T
message: string | null
errors?: Record<string, string[]>
}
Configuration belongs in the environment
The API's address differs between your laptop, staging and production. Hard-coding it is how a production site ends up calling localhost. In Nuxt, runtime config is the right home:
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// Server-only: an internal address the browser never sees.
apiBaseServer: '',
public: {
apiBase: 'http://localhost:8000/api/v1',
siteUrl: 'http://localhost:3000',
},
},
})
Each key can be overridden at runtime by an environment variable — NUXT_PUBLIC_API_BASE, NUXT_API_BASE_SERVER — without rebuilding.
The server-only key is worth having. During server-side rendering, Nuxt and Laravel are often on the same machine or the same private network. Letting the Nuxt server call the API over that internal address avoids a round trip out to the public internet and back.
One composable for every request
Wrap fetching once, so pages never deal with base URLs or envelopes:
export function useApi<T>(path: string, key?: string) {
const config = useRuntimeConfig()
const baseURL = (import.meta.server && config.apiBaseServer) || config.public.apiBase
return useAsyncData<T>(key ?? `api:${path}`, async () => {
const response = await $fetch<ApiEnvelope<T>>(path, {
baseURL,
headers: { Accept: 'application/json' },
})
return response.data
})
}
A page then reads like a description of what it needs:
<script setup lang="ts">
const { data: projects, error } = await useApi<Project[]>('/projects')
</script>
Three things are happening that are easy to miss.
The data is fetched once. useAsyncData runs on the server during rendering, serialises the result into the HTML, and the browser picks it up from there during hydration instead of calling the API again. Using a bare $fetch in setup would make the request twice — once on each side.
The key matters. Two components asking for /site with the same key share one request and one cached result. A detail page should include its identifier in the key (project:${slug}), or navigating between two projects will briefly show the wrong one.
Accept: application/json matters too. Without it Laravel may answer a validation failure or a 404 with an HTML page or a redirect, and the front end will be parsing markup.
Missing records should be real 404s
When the API says a record does not exist, the page must say so with the correct status code — not render an empty template with a 200.
const { data: project, error } = await useApi<ProjectDetail>(`/projects/${slug}`, `project:${slug}`)
if (error.value || !project.value) {
const notFound = error.value?.statusCode === 404
throw createError({
statusCode: notFound ? 404 : 503,
statusMessage: notFound ? 'Project not found' : 'Project unavailable',
fatal: true,
})
}
Distinguishing the two cases is deliberate. "This does not exist" is a 404 and search engines should drop the URL. "The API is down" is a 503 and they should come back later. Treating an outage as a 404 can get good pages removed from an index.
Forms: validate twice, trust once
Validate in the browser for speed and on the server for truth. The browser check gives instant feedback; the server check is the only one that counts.
The useful part is mapping the server's answer back onto the same fields. Laravel returns validation errors keyed by field name, so one function handles every form:
try {
await $fetch<ApiEnvelope<null>>('/contact', { baseURL, method: 'POST', body: form })
status.value = 'sent'
} catch (error) {
const response = error as { statusCode?: number; data?: ApiEnvelope<null> }
if (response.statusCode === 422 && response.data?.errors) {
errors.value = Object.fromEntries(
Object.entries(response.data.errors).map(([field, messages]) => [field, messages[0]]),
)
} else if (response.statusCode === 429) {
feedback.value = 'Too many submissions. Please try again in a minute.'
} else {
feedback.value = 'This could not be sent. Please try again.'
}
}
Handle 429 explicitly. A public form should be rate-limited, and a visitor who trips the limit deserves a clearer message than "something went wrong".
CORS, without guessing
Server-side requests are not subject to CORS — only the browser enforces it. That is why a page can render perfectly on the server and then fail when a form is submitted from the browser.
The fix is on the Laravel side: allow the front end's origin, and only that origin.
// config/cors.php
return [
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'OPTIONS'],
'allowed_origins' => array_filter(array_map('trim', explode(',', env('FRONTEND_URL', '')))),
'allowed_headers' => ['Content-Type', 'Accept'],
'supports_credentials' => false,
];
Resist 'allowed_origins' => ['*']. It works immediately and means any website can call your API from its visitors' browsers.
If the API is public and token-less, as a content API usually is, leave credentials off. Cookie-based authentication across two domains is a larger topic with its own rules about same-site cookies and CSRF.
Images from another origin
Content images usually live with the API, on a different origin from the site. Nuxt Image can resize and convert them, but it must be told the host is allowed:
const apiUrl = new URL(process.env.NUXT_PUBLIC_API_BASE || 'http://localhost:8000/api/v1')
export default defineNuxtConfig({
image: {
domains: [apiUrl.host, apiUrl.hostname],
format: ['avif', 'webp'],
},
})
This value is read when the site is built, not when it runs — a common surprise. Set the environment variable before nuxt build, or production images will return errors that never appeared in development.
Have the API return absolute image URLs. A relative path means every client has to know where the API's storage lives.
SEO needs the data too
Server rendering only helps search engines if the page's metadata is rendered on the server as well. Compute it from the same fetched data:
useSeoMeta({
title: () => project.value?.seo.title || project.value?.title,
description: () => project.value?.seo.description || project.value?.short_description,
ogImage: () => project.value?.seo.og_image,
})
Give the canonical URL a single source — the configured site URL plus the route path — so that the same page reached with a trailing slash or a tracking parameter still names one address.
Caching, where it is safe
Most of a content site is read far more often than it changes. Cache on the API side, keyed by endpoint, and clear the cache when the content is saved. The front end then stays simple: it asks, and the answer is fast.
Avoid caching in two places with two lifetimes. When an editor publishes a change and it does not appear, the hunt for which layer is stale costs more than the second cache ever saved.
The short version
- Configuration in the environment; nothing about addresses in code.
- One composable that knows the base URL and the envelope.
useAsyncDatawith meaningful keys, so data is fetched once.- Real status codes for missing and unavailable content.
- Server validation errors mapped back onto form fields.
- CORS limited to the front end's own origin.
- Image hosts declared at build time.
None of this is sophisticated. It is the boundary between two applications, drawn carefully once, so that neither side has to think about it again.
