---
title: "File Storage"
description: "Enable Convex storage scaffolding in nuxt-convex and use the Nuxt storage helpers in app code."
canonical_url: "https://nuxt-convex.onmax.me/nuxt-module/file-storage"
---
# File Storage

> Enable Convex storage scaffolding in nuxt-convex and use the Nuxt storage helpers in app code.

Use this guide when you want the module to scaffold the base Convex storage functions and expose the Nuxt storage helpers.

## Before you begin

Make sure:

- the core module is already installed
- your app can resolve `#convex/api`
- users can sign in, through [Better Auth](https://nuxt-convex.onmax.me/integrations/better-auth) or [your own provider](https://nuxt-convex.onmax.me/nuxt-module/authenticated-ssr#custom-providers)
- you have run `npx convex dev` in the project that owns the `convex/` directory

## Enable storage

Turn on the storage feature in `nuxt.config.ts`.

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['nuxt-convex'],
  convex: {
    storage: true,
  },
})
```

When `storage: true` is enabled, `nuxt-convex`:

- adds the `#convex/storage` alias
- auto-imports `useConvexStorage` and `useConvexUpload`
- scaffolds `convex/_hub/storage.ts` if it does not already exist

## Review the generated scaffold

The module writes `convex/_hub/storage.ts` once and never overwrites it. It's yours to edit:

```ts [convex/_hub/storage.ts]
// Auto-generated by nuxt-convex - feel free to customize
import type { UserIdentity } from 'convex/server'
import type { MutationCtx, QueryCtx } from '../_generated/server'
import { ConvexError, v } from 'convex/values'
import { mutation, query } from '../_generated/server'

// Every function requires a signed-in user. Any signed-in user can still read or delete
// any file: store the uploader next to the storage id and check ownership before production.
async function requireIdentity(ctx: QueryCtx | MutationCtx): Promise<UserIdentity> {
  const identity = await ctx.auth.getUserIdentity()
  if (!identity)
    throw new ConvexError('Unauthenticated')
  return identity
}

export const generateUploadUrl = mutation({
  args: {},
  handler: async (ctx) => {
    await requireIdentity(ctx)
    return await ctx.storage.generateUploadUrl()
  },
})

export const getUrl = query({
  args: { storageId: v.id('_storage') },
  handler: async (ctx, { storageId }) => {
    await requireIdentity(ctx)
    return await ctx.storage.getUrl(storageId)
  },
})

export const remove = mutation({
  args: { storageId: v.id('_storage') },
  handler: async (ctx, { storageId }) => {
    await requireIdentity(ctx)
    await ctx.storage.delete(storageId)
  },
})
```

Each function requires a signed-in user, so storage needs [auth](https://nuxt-convex.onmax.me/nuxt-module/authenticated-ssr) set up. That isn't enough for production: any signed-in user can still read or delete any file whose id they know. Record the owner in a table of your own, next to the storage id, and check it in `getUrl` and `remove`. The [playground](https://github.com/onmax/nuxt-convex/blob/main/playground/convex/_hub/storage.ts) does this with an `uploads` table.

<warning>

Scaffolds from older releases didn't check auth, so anyone could upload and delete files. The module warns at startup when it finds one. Delete `convex/_hub/storage.ts` to have it regenerated, or add the checks yourself.

</warning>

The scaffold covers upload URLs, file URLs and deletion. Add your own table and mutation for filenames, MIME types, ownership, or domain rules.

## Upload a file from Nuxt

Use `useConvexUpload` for the upload flow and your own mutation to persist metadata, for example:

```ts [convex/schema.ts]
files: defineTable({
  storageId: v.id('_storage'),
  name: v.string(),
  type: v.string(),
  userId: v.string(),
}).index('by_user', ['userId']),
```

```ts [convex/files.ts]
import { ConvexError, v } from 'convex/values'
import { mutation } from './_generated/server'

export const saveUpload = mutation({
  args: { storageId: v.id('_storage'), name: v.string(), type: v.string() },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity()
    if (!identity)
      throw new ConvexError('Unauthenticated')
    return await ctx.db.insert('files', { ...args, userId: identity.subject })
  },
})
```

```vue [app/components/FileUpload.vue]
<script setup lang="ts">
import type { Id } from '~~/convex/_generated/dataModel'
import { isConvexError } from '#convex'
import { api } from '#convex/api'

const { mutate: saveUpload } = useConvexMutation(api.files.saveUpload)
const { upload, isUploading, progress, error } = useConvexUpload({
  onSuccess: async (storageId, file) => {
    await saveUpload({
      storageId: storageId as Id<'_storage'>,
      name: file.name,
      type: file.type,
    })
  },
})

async function onSelect(event: Event) {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file)
    await upload(file)
}
</script>

<template>
  <input type="file" :disabled="isUploading" @change="onSelect">
  <progress v-if="isUploading" :value="progress" max="100" />
  <p v-if="error">
    {{ isConvexError(error) ? error.data : 'Upload failed' }}
  </p>
</template>
```

`upload()` resolves with the storage id, or `null` when it fails. Uploads only run in the browser.

## Show a stored file

`useConvexStorage().getUrl()` returns a ref that follows the file's URL:

```vue [app/components/StoredImage.vue]
<script setup lang="ts">
const props = defineProps<{ storageId: string }>()
const url = useConvexStorage().getUrl(() => props.storageId)
</script>

<template>
  <img v-if="url" :src="url" alt="">
</template>
```

## Verify the result

The setup is working when:

- the module generates `convex/_hub/storage.ts`
- `useConvexUpload` is auto-imported
- a selected file uploads successfully and your follow-up mutation stores the metadata you expect

## Next steps

- Read [Cloudflare R2](https://nuxt-convex.onmax.me/nuxt-module/cloudflare-r2) if you want bucket-backed uploads instead of Convex storage
- Read [`useConvexStorage`](https://nuxt-convex.onmax.me/api-reference/use-convex-storage) for the low-level storage helper
- Read [`useConvexUpload`](https://nuxt-convex.onmax.me/api-reference/use-convex-upload) for the upload wrapper API


## Sitemap

See the full [sitemap](https://nuxt-convex.onmax.me/sitemap.md) for all pages.
