Server Utils
Auto imports
When reading the rest of the docs, you might notice that there are no imports
in examples for using utilities.
It is because Nitro uses unimport to auto import utilities when used with full tree-shaking support so you don't have to!
H3 utils
Nitro enables all h3 utils as auto imports so you can use defineEventHandler
, readBody
, etc. without manually importing them.
utils
directory
You can add your application specific utils inside server/utils/
directory and they will be auto-imported when used.
Every export in the utils
directory and its subdirectories will become available globally in your application.
Example: Create a server/utils/sum.ts
file where a function useSum
is exported:
export function useSum(a: number, b: number) { return a + b }
Use it in your server/routes/index.ts
file without importing it:
export default defineEventHandler(() => {
const sum = useSum(1, 2) // auto-imported
return { sum }
})
Nitro utils
Nitro also exposes several built-in utils:
defineCachedFunction(fn, options)
/cachedFunction(fn, options)
defineCachedEventHandler(handler, options)
/cachedEventHandler(handler, options)
defineRenderHandler(handler)
defineRouteMeta(options)
(experimental)useRuntimeConfig(event?)
useAppConfig(event?)
useStorage(base?)
useNitroApp()
defineNitroPlugin(plugin)
nitroPlugin(plugin)
getRouteRules(event)
prepare
or dev
command. See TypeScript guide, for IDE support.Manual imports
For some edge cases (IDE support and libraries in node_modules
) it is impossible to rely on auto imports.
You can explicitly import them from virtual #imports
file.
#imports
still has benefits of tree-shaking.import { useStorage } from '#imports'
Async Context (Experimental)
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 access a shared context (request event) without needing it to be passed along. This pattern is inspired from Vue Composition API and powered by unctx.
AsyncLocalStorage
interface.In order to enable async context feature, you have to enable asyncContext
flag:
export default defineNitroConfig({
experimental: {
asyncContext: true
}
});
export default defineNuxtConfig({
nitro: {
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:
// server/routes/index.ts
export default defineEventHandler(async () => {
const user = await useAuth()
})
// server/utils/auth.ts
export function useAuth() {
return useSession(useEvent())
}
// server/routes/index.ts
export default defineEventHandler(async (event) => {
const user = await useAuth(event)
})
// server/utils/auth.ts
export function useAuth(event) {
return useSession(event)
}