Note
Examples in this guide are tailored for using with Vercel functions.
You can use server assets to include files into the production bundle.
Any file inside server/assets/
is by default included. You can access server assets using storage api.
Tip
Using this method is recommanded to access server assets.
Example:
export default defineEventHandler(async () => {
// https://nitro.unjs.io/guide/assets#server-assets
const assets = useStorage('assets:server')
const users = await assets.getItem('users.json')
return {
users
}
})
You can include more directories other than server/assets
to the bundle using nuxt.config
.
export default defineNuxtConfig({
nitro: {
serverAssets: [
{
baseName: 'templates',
dir: './templates'
}
]
}
})
You can use esm imports (or require
while not recommanded) to import server assets.
Important
Please prefer using storage api unless you need to directly import assets.
Example:
// import testHtml from 'server/assets/test.html'
export default defineEventHandler(async () => {
const testHtml = process.dev ? undefined : await import('server/assets/test.html').then(r=>r.default)
return testHtml
})
If you use dependencies that use filesystem access to read some files, nitro automatically detects usage using vercel/nft and copy them to the lambda files.
Example: (a commonjs dependency)
const { join } = require("path")
const { readFileSync } = require("fs")
module.exports = readFileSync(join(__dirname, "test.txt"), "utf-8")
When building with --preset verrcel
or using vercel CI, you will have .vercel/output/functions/__nitro.func/node_modules/test_dep/test.txt
in the build output which is auto traced.
If you need to force track a dependency, you can use nitro.externals.traceInclude
config:
export default defineNuxtConfig({
nitro: {
externals: {
traceInclude: ['test_dep']
}
}
})
Note
Nitro by default treeshakes dependencies and only includes used files from node_modules
so normally you don't need to manually exclude files from tracing.
You can mount a KV storage using Vercel KV driver to have read/write access to server files.
export default defineNuxtConfig({
$production: {
nitro: {
storage: {
data: { driver: 'vercelKV' }
}
}
}
})
Example:
export default defineEventHandler(async (event) => {
const dataStorage = useStorage("data");
await dataStorage.setItem("hello", "world");
return {
hello: await dataStorage.getItem("hello"),
};
});