Utils
Nitro helps you to stay organized allowing you to take advantage of the auto-imports
feature.
Every export in the utils
directory and its subdirectories will become available globally in your application.
Example: Create a utils/sum.ts
file where a function useSum
is exported:
export function useSum(a: number, b: number) { return a + b }
Use it in your routes/index.ts
file without importing it:
export default defineEventHandler(() => { const sum = useSum(1, 2) // auto-imported return { sum }})
Experimental Composition API
Nitro (2.6+) enables a new server development experience in order to split application logic into smaller "composable" utilities that are fully decoupled from each other and can directly assess to a shared context (request event) without needing it to be passed along. This pattern is inspired from Vue Composition API and powered by unjs/unctx.
This feature is currently supported for Node.js and Bun runtimes and also coming soon to other presets that support AsyncLocalStorage
interface.
In order to enable composition API, you have to enable asyncContext
flag:
export default defineNitroConfig({ experimental: { asyncContext: true }});
After enabling this flag, you can use useEvent()
(auto imported) in any utility or composable to access the request event without manually passing it along:
// routes/index.tsexport default defineEventHandler(async () => { const user = await useAuth()})// utils/auth.tsexport function useAuth() { return useSession(useEvent())}