nuxt-server-assets

Stars
4

Nuxt server files

[!NOTE] Examples in this guide are tailored for using with Vercel functions.

Using server assets

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
  }
})

Adding extra server assets

You can include more directories other than server/assets to the bundle using nuxt.config.

export default defineNuxtConfig({
  nitro: {
    serverAssets: [
      {
        baseName: 'templates',
        dir: './templates'
      }
    ]
  }
})

Using ESM imports

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
})

Auto traced node_module dependencies

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.

Writing files

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"),
  };
});