Skip to main content

Direct uploads to Vercel Blob with Next.js

When a user uploads a PNG from the Uppy Dashboard, your Next.js route checks their session and returns a signed URL for that file. In the browser, XHR Upload sends the PNG straight to Vercel Blob.

Connect a Blob store​

Use a public Vercel Blob store for images that anyone with the image URL can view. Connect the store to your Next.js project and keep its credentials on the server.

For local development, run vercel link in your project directory. Open the store’s Projects tab, enable Development for your project, then run vercel env pull .env.local.

Install Uppy and the Blob SDK (this example uses @vercel/blob 2.9.0).

npm install @uppy/core @uppy/dashboard @uppy/xhr-upload @vercel/blob

Authorize one upload​

In your Next.js App Router project, create app/api/blob/upload-url/route.ts. The route uses the Auth.js session helper from @/auth to read the user’s stable ID from the session. If you use another auth provider, read the ID from its server-side session.

import { createHash } from 'node:crypto'
import { issueSignedToken, presignUrl } from '@vercel/blob'
import { auth } from '@/auth'

export async function POST(request: Request) {
const userId = (await auth())?.user?.id
if (!userId) {
return Response.json({ error: 'Sign in to upload' }, { status: 401 })
}
if (request.headers.get('content-type') !== 'application/json') {
return new Response(null, { status: 415 })
}

const body = await request.json().catch(() => null)
const uploadId = body?.uploadId
if (typeof uploadId !== 'string' ||
!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(uploadId)) {
return Response.json({ error: 'Invalid upload ID' }, { status: 400 })
}

const owner = createHash('sha256').update(userId).digest('hex')
const pathname = `uploads/${owner}/${uploadId}.png`
const token = await issueSignedToken({
pathname,
operations: ['put'],
validUntil: Date.now() + 5 * 60_000,
maximumSizeInBytes: 10 * 1024 * 1024,
allowedContentTypes: ['image/png'],
})
const { presignedUrl } = await presignUrl(token, {
pathname,
operation: 'put',
access: 'public',
addRandomSuffix: false,
allowOverwrite: true,
})
return Response.json({ presignedUrl })
}

The signed URL lets the browser write to one pathname for five minutes. Blob enforces the 10 MiB size limit and the PNG content type. If your app needs to verify the file contents, check that the uploaded bytes form a valid PNG before using the image.

Upload from the browser​

Add the Dashboard to app/upload/page.tsx so users can see progress and cancel an upload. With formData: false, XHR Upload sends the file bytes as the body of the PUT request.

Retry gets a new signed URL for the same pathname and sends the whole file again. If Blob saved the file and the browser missed the response, the retry overwrites that copy. Removing the file and adding it again starts a new upload with its own pathname.

'use client'

import Uppy from '@uppy/core'
import Dashboard from '@uppy/dashboard'
import XHRUpload from '@uppy/xhr-upload'
import { useEffect, useRef } from 'react'
import '@uppy/core/css/style.min.css'
import '@uppy/dashboard/css/style.min.css'

export default function UploadPage() {
const target = useRef<HTMLDivElement>(null)

useEffect(() => {
const uppy = new Uppy({
restrictions: {
allowedFileTypes: ['image/png'],
maxFileSize: 10 * 1024 * 1024,
},
})
const selections = new Map<string, { uploadId: string; controller: AbortController }>()
uppy.on('file-added', (file) => {
const uploadId = crypto.randomUUID()
selections.set(file.id, { uploadId, controller: new AbortController() })
uppy.setFileMeta(file.id, { uploadId })
})
uppy.on('file-removed', (file) => {
selections.get(file.id)?.controller.abort()
selections.delete(file.id)
})
uppy.use(Dashboard, { inline: true, target: target.current! })
uppy.use(XHRUpload, {
method: 'PUT',
formData: false,
headers: { 'x-vercel-blob-access': 'public', 'x-content-type': 'image/png' },
shouldRetry: () => false,
async endpoint(file) {
if (Array.isArray(file)) throw new Error('Select individual files')
const selection = selections.get(file.id)
if (!selection || selection.uploadId !== file.meta.uploadId) {
throw new DOMException('File removed', 'AbortError')
}
const { signal } = selection.controller
try {
const response = await fetch('/api/blob/upload-url', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uploadId: selection.uploadId }),
signal,
})
if (!response.ok) {
throw new Error(response.status === 401
? 'Sign in to upload'
: 'Could not authorize the upload')
}
const { presignedUrl } = await response.json()
return presignedUrl
} catch (cause) {
signal.throwIfAborted()
const error = cause instanceof Error ? cause : new Error('Upload failed')
const current = uppy.getFile(file.id)
if (current) uppy.emit('upload-error', current, error)
throw error
}
},
})
return () => uppy.destroy()
}, [])

return <div ref={target} />
}

Try it​

Sign in, open /upload, and upload a PNG under 10 MiB. In your browser’s Network panel, you should see a POST to your app followed by a PUT to Blob. After the Dashboard reports success, look for the image in the store’s uploads/ folder.

To check cancellation, throttle the connection in developer tools. Remove the file while the authorization POST or the Blob PUT is pending. You should be able to select the same file again and upload it successfully.

To force an upload error, block the Blob request in developer tools and start an upload. Once the Dashboard shows the error, unblock the request and select Retry.