Assets Handling

Nitro handles assets via the public/ directory.

Public Assets

All assets in public/ directory will be automatically served.

public/
  image.png     <-- /image.png
  video.mp4     <-- /video.mp4
  robots.txt    <-- /robots.txt
package.json
nitro.config.ts

When building with Nitro, it will copy the public/ directory to .output/public/ and create a manifest with metadata:

{
  "/image.png": {
    "type": "image/png",
    "etag": "\"4a0c-6utWq0Kbk5OqDmksYCa9XV8irnM\"",
    "mtime": "2023-03-04T21:39:45.086Z",
    "size": 18956
  },
  "/robots.txt": {
    "type": "text/plain; charset=utf-8",
    "etag": "\"8-hMqyDrA8fJ0R904zgEPs3L55Jls\"",
    "mtime": "2023-03-04T21:39:45.086Z",
    "size": 8
  },
  "/video.mp4": {
    "type": "video/mp4",
    "etag": "\"9b943-4UwfQXKUjPCesGPr6J5j7GzNYGU\"",
    "mtime": "2023-03-04T21:39:45.085Z",
    "size": 637251
  }
}

This allows Nitro to know the public assets without scanning the directory, giving high performance with caching headers.

Server Assets

All assets in assets/ directory will be added to the server bundle.

They can be addressed by the assets:server mount point using useStorage('assets:server')

Keys can be written assets/server/my_file_path or assets:server:my_file_path.

Custom Server Assets

In order to add assets from a custom directory, path will need to be defined in the nitro config:

nitro.config.ts
import { defineNitroConfig } from 'nitropack/config'

export default defineNitroConfig({
  serverAssets: [{
    baseName: 'my_directory',
    dir: './server/my_directory'
  }]
})
nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    serverAssets: [{
      baseName: 'my_directory',
      dir: './server/my_directory'
    }]
  }
})

They can be addressed by the key assets/my_directory/.

Examples

Example: Retrieving a json data from default assets directory:

export default defineEventHandler(async () => {
  const data = await useStorage().getItem(`assets/server/data.json`)
  return data
})

Example: Retrieving a html file from a custom assets directory:

nitro.config.ts
import { defineNitroConfig } from 'nitropack/config'

export default defineNitroConfig({
  serverAssets: [{
    baseName: 'templates',
    dir: './templates' // Relative to `srcDir` (`server/` for nuxt)
  }]
})
nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    serverAssets: [{
      baseName: 'templates',
      dir: './templates' // Relative to `srcDir` (`server/` for nuxt)
    }]
  }
})
// routes/success.ts
export default defineEventHandler(async (event) => {
  return await useStorage().getItem(`assets/templates/success.html`)
  // or
  return await useStorage('assets:templates').getItem(`success.html`)
})