Skip to main content

Private downloads

Serve a private file from your own origin and check access on every request.

A storage URL works for anyone who has it, and it does not expire. Use a private download route when a file must stay private after the link is shared, or when access can end: a member leaves, a document is withdrawn, a session is revoked.

The route has two parts:

  1. A Convex HTTP action that checks the caller and the document, then sends the file.
  2. A Nuxt server route on your own origin that calls the HTTP action with the caller's Convex session token.

The browser never sees a storage URL, and <img src> and links work with the session cookie.

Check access in the HTTP action

convex/http.ts
import { httpRouter } from 'convex/server'

import { internal } from './_generated/api'
import { httpAction } from './_generated/server'
import { auth } from './auth'

const http = httpRouter()
auth.registerRoutes(http)

const noStore = { 'cache-control': 'private, no-store' }

http.route({
  pathPrefix: '/files/',
  method: 'GET',
  handler: httpAction(async (ctx, request) => {
    const user = await auth.getUser(ctx)
    if (!user) return new Response(null, { status: 401, headers: noStore })
    const id = new URL(request.url).pathname.slice('/files/'.length)
    // The same answer for a missing document and a document of another user.
    const file = await ctx.runQuery(internal.documents.forDownload, { id, userId: user.id })
    if (!file) return new Response(null, { status: 404, headers: noStore })
    const blob = await ctx.storage.get(file.storageId)
    if (!blob) return new Response(null, { status: 404, headers: noStore })
    return new Response(blob, {
      headers: {
        ...noStore,
        'content-type': file.contentType,
        'content-length': String(blob.size),
        'content-disposition': `inline; filename*=UTF-8''${encodeURIComponent(file.fileName)}`,
        'x-content-type-options': 'nosniff',
      },
    })
  }),
})

export default http

auth.getUser(ctx) reads the Authorization: Bearer header and checks the live session, as in a query. internal.documents.forDownload is your own internal query. It turns id into a document ID with ctx.db.normalizeId, checks that the user may read the document, and returns its storage ID, type and name, or null. Store the type that you found in the file's bytes at upload, not the type the uploader declared.

Do not mount this route under /api/auth/. The auth proxy refuses responses larger than 1 MiB.

Call it from a Nuxt server route

server/routes/files/[id].get.ts
import { defineEventHandler, getRouterParam } from 'nuxt/server'
import { serverConvex } from '#convex/server'

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id') ?? ''
  const noStore = { 'cache-control': 'private, no-store' }
  if (!/^[a-z0-9]{10,64}$/.test(id)) return new Response(null, { status: 404, headers: noStore })

  const upstream = await serverConvex(event).fetch(`/files/${id}`)
  if (!upstream.ok)
    return new Response(null, { status: upstream.status === 401 ? 401 : 404, headers: noStore })

  const headers = new Headers(noStore)
  for (const name of [
    'content-type',
    'content-length',
    'content-disposition',
    'x-content-type-options',
  ]) {
    const value = upstream.headers.get(name)
    if (value) headers.set(name, value)
  }
  return new Response(upstream.body, { headers })
})

fetch(path) sends a GET to the Convex HTTP actions host of the deployment, with the caller's Convex session token as Authorization: Bearer. It returns the upstream Response and streams its body. Copy only the headers that you need.

Cost and limits

  • Each download runs the HTTP action, one query and one storage read, and Convex bills the bytes the action sends.
  • Convex limits an HTTP action response to 100 MiB. fetch does not apply the 1 MiB cap of query, mutation and action, so a large file passes through your Nuxt server.
  • fetch forwards no request headers from the browser, so Range requests do not work: no seeking in a video and no resumed download. Each request sends the whole file.
  • Cache-Control: private, no-store keeps shared caches from storing one person's file for another.