Nuxt
nuxt/no-browser-api-in-setup
Never touch window, document, localStorage or navigator at the top of script setup; it also runs on the server.
seriousstaticfe-nuxt
Why
With server rendering, <script setup> runs first on the server, where window, document and localStorage do not exist: the page answers with a 500 error, or, when the access is guarded badly, the server and browser render different HTML and hydration throws the server's markup away.
Fix
Read browser state after mounting (onMounted(() => { theme.value = localStorage.getItem('theme') })), guard with if (import.meta.client), use a cookie that both sides can read (useCookie('theme')), or render the part only in the browser (<ClientOnly> or a *.client.vue component).
Examples
// bad
const theme = ref(localStorage.getItem('theme') ?? 'light')
// good
const theme = useCookie('theme', { default: () => 'light' })Sources
Facts
- Id
nuxt/no-browser-api-in-setup- Severity
- serious
- Check
- static checked in the source by
audit - Applies to
vue- Only in projects with
nuxt- Taught by the skill
fe-nuxtNuxt apps- Since version
- 0.1.0
Read it in the terminal
npx github:dawidolko/frontend-skills explain nuxt/no-browser-api-in-setup