Overview
The Nuxt Server Functions is a feature in Nuxt 3 that allows server functions to be used on the client side. It is an experimental feature, meaning that the APIs may change in the future.
Features
- Server Functions: Server functions can be exposed under the server/functions/ directory.
- Client Functions: Client functions can be used by importing and using the useServerFunctions() function.
- Caching: By default, server function calls are aggressively cached using the useState() hook. The same result is reused across the client and server sides for hydration.
Installation
To use Nuxt Server Functions, follow these steps:
- Install the NPM package for Nuxt Server Functions.
- Expose your server functions by placing them under the server/functions/ directory.
- Use the useServerFunctions() function on the client side to import and use the server functions.
Here is an example of how to use the Nuxt Server Functions:
// Import the useServerFunctions() function
import { useServerFunctions } from 'nuxt-server-fn'
// Use the server function
const { data, error } = useServerFunctions().myServerFunction({ arg: value })
To opt-out of caching, you can pass cache: false as an option:
const { data, error } = useServerFunctions().myServerFunction({ arg: value }, { cache: false })
You can also use the $cached or $cacheless property to toggle caching for each function call:
const { data, error } = useServerFunctions().myServerFunction.$cached({ arg: value })
const { data, error } = useServerFunctions().myServerFunction.$cacheless({ arg: value })
Summary
Nuxt Server Functions is an experimental feature in Nuxt 3 that allows server functions to be used on the client side. It provides an easy way to expose and use server functions in a Nuxt app. However, since it is still experimental, the APIs may change in future versions of Nuxt.