Full-stack API for Nuxt 3.
- Add
nuxt-unapi
dependency to your project
# Using pnpm
pnpm add -D nuxt-unapi
# Using yarn
yarn add --dev nuxt-unapi
# Using npm
npm install --save-dev nuxt-unapi
- Add
nuxt-unapi
to themodules
section ofnuxt.config.ts
export default defineNuxtConfig({
modules: [
'nuxt-unapi'
],
// Required enable asyncContext
experimental: {
asyncContext: true,
},
})
✨✨✨
Expose server functions under api/**.ts
// api/user.ts
import { z } from 'zod'
export const getUser = defineApi({
props: z.number(),
// id type is number
async handler (id) {
return db.user.get(id)
},
})
export const updateUser = defineApi({
props: z.object({
id: z.number(),
name: z.string(),
age: z.number().optional()
}),
// props are secure data validated by Zod.
async handler (props) {
return db.user.update(props)
}
})
On the client side:
import { getUser, updateUser } from '~/api/user.ts'
const user = await getUser(1)
user.name = 'nuxt-unapi'
const result = await updateUser(user)
Client validate. Zod Docs
updateUser.props.parse(user)