Skip to content

Commit

Permalink
Merge pull request #368 from scottix/docs/handling-state-ssr
Browse files Browse the repository at this point in the history
docs: handling state with care
  • Loading branch information
Baroshem committed Feb 6, 2024
2 parents d296ee4 + eded747 commit da53a5d
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions docs/content/1.documentation/5.advanced/1.good-practices.md
Expand Up @@ -24,6 +24,43 @@ const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev
})
```

## Handling State with Care in Nuxt SSR

When developing applications with Nuxt.js in SSR mode, it's crucial to handle reactive state with care to avoid Cross-Request State Pollution. This issue arises when state is shared unintentionally between requests, leading to potential data leaks and inconsistent application behavior. Nuxt's documentation [here](https://nuxt.com/docs/getting-started/state-management#best-practices) provides best practices for state management in such scenarios.

Consider the issue with global ref in a composable.
```ts
const unsafeGlobal = ref<number>(1);

export function useSafeRef() {
const safeRef = ref<number>(2);

return {
unsafeGlobal,
safeRef
}
}
```

For enhanced safety and to adhere to Nuxt's best practices, it's recommended to manage state using abstractions with `useState`. This utility function is specifically designed for Nuxt applications to ensure state is isolated per request, effectively preventing cross-request state pollution:
```ts
const safeGlobal = useState<number>('safeGlobal', () => 5);

export function useSafeRef() {
const safeRef = useState<number>('safeRef', () => 2);

return {
safeGlobal,
safeRef
}
}
```
<i>Note: useState is global across components. Use a unique key if you want to keep them separate.</i>

::alert{type="info"}
ℹ Read more about Cross-Request State Pollution [here](https://vuejs.org/guide/scaling-up/ssr.html#cross-request-state-pollution)
::

## Use access control lists

Authorization prevents users from acting outside of their intended permissions. In order to do so, users and their roles should be determined with consideration of the principle of least privilege. Each user role should only have access to the resources they must use.
Expand Down

0 comments on commit da53a5d

Please sign in to comment.