All posts

How to Fix Undefined Variable in Nuxt

Learn how to diagnose and fix Undefined Variable errors in Nuxt. Step-by-step guide with code examples.

Fixing Undefined Variable in Nuxt

Nuxt's auto-import system and SSR model create unique opportunities for undefined variable errors. Variables might exist in the browser but fail during server rendering, or auto-imports might not resolve as expected.

Causes

  • Accessing browser globals (window, document) during SSR
  • Composables used outside of setup context
  • Auto-imported functions not available in certain contexts

How to Fix

Use Nuxt's built-in patterns for SSR safety:

<script setup>
// useRuntimeConfig is auto-imported by Nuxt
const config = useRuntimeConfig();

// Use process.client for browser-only code
const screenWidth = ref(0);

onMounted(() => {
  // Safe: onMounted only runs client-side
  screenWidth.value = window.innerWidth;
});

// Or use the <ClientOnly> component in template
const { data: posts } = await useFetch('/api/posts');
</script>

<template>
  <div>
    <div v-for="post in posts" :key="post.id">
      {{ post.title }}
    </div>
    <ClientOnly>
      <p>Screen: {{ screenWidth }}px</p>
    </ClientOnly>
  </div>
</template>

Wrap browser-dependent code in onMounted, process.client checks, or <ClientOnly> components.

Production Hardening

Beyond the immediate fix, consider adding circuit breakers and graceful degradation for this failure mode. Log structured error data so your observability stack can correlate this error with upstream causes. Set up dashboards to track error rates over time and catch regressions early.

Bugsly for Nuxt

Bugsly distinguishes between SSR and CSR errors in Nuxt apps, and tracks which auto-imported composable or variable was undefined — saving you from guessing which rendering context failed.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free