File Storage
Docs menu

Framework guides

Nuxt guide

Nuxt 3/4: a client-only plugin exposes $fileStorage.mount() to every component.

What you will build

A Nuxt app with the File Storage file manager on /files, connected to your storage, with tests that prove it mounts, licenses and uploads. The steps work the same way in an existing app; skip the scaffolding step.

Prerequisites

  • Node.js 20 LTS or newer.
  • A production API key (fs_live_…) from Dashboard → Keys. Keys only work on an active plan.
  • Your page hosts registered under Dashboard → Websites. Once any website is registered, the key only works on those hosts, so add localhost for development alongside your production domain.
  • A storage backend: your own S3 proxy or Managed storage (Free includes 1 GB). See Choose storage.

1. Create the project

Skip this if you already have a Nuxt app.

Terminal
npx nuxi@latest init my-files-app
cd my-files-app

2. Add runtime config

Declare the public keys in nuxt.config.ts, then set real values in .env. Nuxt maps fileStorageApiKey to NUXT_PUBLIC_FILE_STORAGE_API_KEY.

nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      fileStorageApiKey: '',
      fmProxyUrl: '',
    },
  },
})
.env
NUXT_PUBLIC_FILE_STORAGE_API_KEY=fs_live_…
NUXT_PUBLIC_FM_PROXY_URL=http://localhost:3847

3. Type the global

Nuxt’s generated tsconfig includes every .d.ts in the project.

types/filestorage.d.ts
export {}

declare global {
  interface FileStorageMountOptions {
    el: string | HTMLElement
    apiKey: string
    s3?: {
      proxyBaseUrl: string
      publicObjectBaseUrl?: string
      headers?: () => Record<string, string>
    }
    http?: {
      baseUrl: string
      headers?: () => Record<string, string>
    }
    widget?: 'full' | 'picker' | 'upload' | 'media'
    accessMode?: 'full' | 'read-only' | 'upload-only'
  }

  interface Window {
    FileStorageSDK?: {
      mount(options: FileStorageMountOptions): { unmount(): void }
    }
  }
}

4. Create the plugin

The .client suffix keeps it out of server rendering. It loads the CDN on first use (once per app) and provides $fileStorage.mount(). Passing http or store replaces the default s3 proxy.

plugins/filestorage.client.ts
type SDK = NonNullable<Window['FileStorageSDK']>

export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig().public
  let loading: Promise<SDK> | undefined

  const load = () =>
    (loading ??= new Promise<SDK>((resolve, reject) => {
      if (window.FileStorageSDK) return resolve(window.FileStorageSDK)

      const css = document.createElement('link')
      css.rel = 'stylesheet'
      css.href = 'https://cdn.filestorage.io/file-storage.css'
      document.head.appendChild(css)

      const script = document.createElement('script')
      script.src = 'https://cdn.filestorage.io/file-storage.min.js'
      script.onload = () =>
        window.FileStorageSDK
          ? resolve(window.FileStorageSDK)
          : reject(new Error('FileStorageSDK missing after load'))
      script.onerror = () => reject(new Error('Could not load the File Storage CDN'))
      document.head.appendChild(script)
    }))

  return {
    provide: {
      fileStorage: {
        async mount(el: HTMLElement, options: Partial<FileStorageMountOptions> = {}) {
          const sdk = await load()
          const storage =
            options.http || options.s3
              ? {}
              : { s3: { proxyBaseUrl: String(config.fmProxyUrl) } }
          return sdk.mount({
            el,
            apiKey: String(config.fileStorageApiKey),
            ...storage,
            ...options,
          })
        },
      },
    },
  }
})

5. Create the component

Also client-only. Loading is async, so if the user leaves before the SDK finishes loading, the late mount is undone straight away.

components/FileManager.client.vue
<script setup lang="ts">
const host = ref<HTMLElement | null>(null)
const { $fileStorage } = useNuxtApp()
let handle: { unmount(): void } | undefined
let disposed = false

onMounted(async () => {
  if (!host.value) return
  const mounted = await $fileStorage.mount(host.value)
  if (disposed) mounted.unmount()
  else handle = mounted
})

onBeforeUnmount(() => {
  disposed = true
  handle?.unmount()
})
</script>

<template>
  <div ref="host" style="height: 70vh" />
</template>

6. Add a page

Components are auto-imported. A fresh project renders <NuxtWelcome /> in app.vue; replace it with <NuxtPage /> so files in pages/ become routes.

app.vue
<template>
  <NuxtPage />
</template>
pages/files.vue
<template>
  <main>
    <h1>Files</h1>
    <FileManager />
  </main>
</template>

Choose storage

The UI is the same either way; only the mount option changes.

Your S3 proxy

The examples above already use this: s3.proxyBaseUrl points at a small server you run that holds the AWS credentials. Locally that is usually http://localhost:3847. The routes it must implement are in the S3 proxy contract; for PHP, Laravel or other stacks see Backends & cloud.

Allow your app origin on the proxy (http://localhost:3000 in development) or uploads will fail with CORS errors.

Managed storage

File Storage provisions an isolated prefix for your account on our AWS bucket, so there is no proxy to run and no AWS keys to hold. Pass http when mounting; the plugin then skips the s3 default:

components/FileManager.client.vue
const apiKey = String(useRuntimeConfig().public.fileStorageApiKey)

const mounted = await $fileStorage.mount(host.value, {
  http: {
    baseUrl: 'https://api.filestorage.io/v1/managed',
    headers: () => ({ 'X-FileStorage-Api-Key': apiKey }),
  },
})

The exact base URL and your tenant status are shown in Dashboard → Managed storage.

Run it locally

Terminal
npm run dev

Open http://localhost:3000/files. You should see a short license check, then the file manager listing the root folder.

Test

Manual checklist

With DevTools open on the Network tab, reload http://localhost:3000/files and confirm:

  1. POST https://api.filestorage.io/v1/license/validate returns 200 with "valid": true.
  2. The first list call returns 200: /list on your proxy, or /v1/managed/api/files/list on Managed.
  3. Upload a file, then rename it, move it into a new folder, and delete it. Each action should succeed without a console error.
  4. Reload the page. The folder you created is still there, which proves the files reached storage.
  5. Navigate away and back (or unmount the component). Exactly one file manager appears.

End-to-end (Playwright)

This runs your real app in a browser against the real license API and storage, so it catches what unit tests cannot: CDN loading, domain registration, CORS and uploads.

Terminal
npm init playwright@latest -- --quiet --lang=ts --gha
playwright.config.ts
import { defineConfig } from '@playwright/test'

export default defineConfig({
  testDir: './e2e',
  use: { baseURL: 'http://localhost:3000' },
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
})
e2e/file-manager.spec.ts
import { expect, test } from '@playwright/test'

test('File Storage mounts with a valid license', async ({ page }) => {
  const license = page.waitForResponse((r) => r.url().includes('/v1/license/validate'))
  await page.goto('/files')

  expect((await license).status()).toBe(200)
  await expect(page.locator('[data-filestorage-license="denied"]')).toHaveCount(0)
  await expect(page.getByRole('button', { name: 'Upload', exact: true })).toBeVisible()
})

test('uploads a file into the current folder', async ({ page }) => {
  const name = `e2e-${Date.now()}.txt`
  await page.goto('/files')

  await page.getByRole('button', { name: 'Upload', exact: true }).click()
  const dialog = page.getByRole('dialog', { name: 'Upload files' })
  await dialog.locator('input[type="file"]').setInputFiles({
    name,
    mimeType: 'text/plain',
    buffer: Buffer.from('hello from playwright'),
  })
  await dialog.getByRole('button', { name: /^Upload \(1\)$/ }).click()

  await expect(page.getByText(name).first()).toBeVisible()
})
Terminal
npx playwright test

Go to production

  1. Add your production domain under Dashboard → Websites.
  2. Set the production API key and storage URL in your host’s environment settings.
  3. Build with npm run build and deploy the output.
  4. If you use a Content Security Policy, allow cdn.filestorage.io in script-src and style-src, and api.filestorage.io plus your proxy origin in connect-src.
  5. Run the Playwright suite against the deployed URL (set baseURL) as a smoke test.

Troubleshooting

SymptomFix
window is not defined / hydration mismatchKeep the .client suffix on both the plugin and the component file names.
API key is an empty stringThe env name must match the camelCase key: fileStorageApiKey → NUXT_PUBLIC_FILE_STORAGE_API_KEY.
/files shows the Nuxt welcome screenReplace <NuxtWelcome /> with <NuxtPage /> in app.vue.
FileStorageSDK is undefinedThe CDN script did not load before mount. Check the Network tab for a 200 on file-storage.min.js and any Content Security Policy errors.
DOMAIN_NOT_ALLOWEDThe page host is not in Dashboard → Websites. Add localhost for local work and your production domain before deploying.
UNPAID_PLAN or INVALID_API_KEYUse a non-revoked production key from an account with an active plan.
CORS error on /list or /uploadYour proxy must allow the app origin (http://localhost:3000 locally) for POST with Content-Type and multipart bodies.
File manager renders with zero heightThe host element needs an explicit height (the examples use 70vh).

All mount options, store contracts and widget modes are in the integration guide.