Storage URLs
Resolve a Convex storage ID with an ordinary typed query.
Store Convex storage IDs in product data. Resolve a URL with useConvexQuery when the UI needs it.
A storage URL works for anyone who has it, and it does not expire. Convex revokes it only when the file is deleted. When access to a file must end, for example when a member leaves a workspace, serve it through a private download route instead.
Backend query
import { v } from 'convex/values'
import { query } from './_generated/server'
import { auth } from './auth'
export const getFileUrl = query({
args: { documentId: v.id('documents') },
handler: async (ctx, args) => {
const user = await auth.requireUser(ctx)
const document = await ctx.db.get(args.documentId)
// The same result for a missing document and for a document of another user.
if (!document || document.ownerId !== user.id || !document.storageId) return null
return await ctx.storage.getUrl(document.storageId)
},
})The query takes a document ID, not a storage ID. Anyone who knows a storage ID could otherwise read the file. The query checks the owner of the document and then resolves the URL of its file.
Reactive URL
import type { Id } from '#convex/dataModel'
const documentId = ref<Id<'documents'> | undefined>()
const urlArgs = computed(() => (documentId.value ? { documentId: documentId.value } : 'skip'))
const {
data: imageUrl,
status,
error,
} = useConvexQuery(api.documents.getFileUrl, urlArgs, {
auth: 'required',
})The query is idle until a document ID exists and runs again when it changes. Use auth: 'required' for private files and keep the authorization check in the Convex query.
Display after upload
import type { UploadCompleteContext } from '@lupinum/better-convex-nuxt'
import type { Id } from '#convex/dataModel'
const props = defineProps<{ documentId: Id<'documents'> }>()
const { upload, data: uploaded } = useConvexFileUpload(api.files.generateUploadUrl, {
complete: (
op,
{ storageId, context: documentId }: UploadCompleteContext<string, Id<'documents'>>,
) => op.mutation(api.documents.attachFile, { documentId, storageId }),
})
const urlArgs = computed(() => (uploaded.value ? { documentId: props.documentId } : 'skip'))
const { data: imageUrl } = useConvexQuery(api.documents.getFileUrl, urlArgs, {
auth: 'required',
})
// Later, in the change handler of the file input:
await upload(file, { context: props.documentId })<img v-if="imageUrl" :src="imageUrl" alt="Uploaded preview" />undefined means the URL query has no value yet. A null result is a successful response. It means that the document does not exist, belongs to another user, or has no file.
URL lifetime
Treat the resolved URL as presentation data. It stays valid until the file is deleted, also for a person who has lost access. Store the branded storage ID on the document as the durable reference and resolve again when needed. See Upload files for attachFile.