Vercel Blob tutorial: upload and serve files
By Flavio
Tagged: Services
Upload files to Vercel Blob from a server or browser, validate uploads, choose public or private storage, serve files, and delete them safely.
Vercel Blob is object storage for files. Use it for images, documents, videos, exports, and anything else that doesn’t belong in a database row or a Git repository.
In this tutorial we’ll upload an avatar, validate it, display it, and delete it. Then we’ll look at how private files change the setup.
Public and private Blob stores
You pick the access mode when you create a Blob store:
- A public store returns URLs anyone can open. Use it for public images, downloads, and media.
- A private store requires authentication for reads and writes. Use it for invoices, user documents, internal reports, and sensitive uploads.
You can’t change the access mode of an existing store later, so pick the right one before uploading any data.
Create a Blob store
Open your Vercel project and go to Storage → Create Database → Blob. Create a public store for this avatar example and connect it to your project.
Vercel adds the store credentials to the project environment automatically. Pull them down locally:
npx vercel link
npx vercel env pull
If you don’t have a Next.js app yet, create one:
npx create-next-app@latest blob-demo
cd blob-demo
Then install the Blob SDK:
npm install @vercel/blob
Upload from the server
The simplest way to handle uploads is sending the file to a Route Handler, which validates it and writes it to Blob.
Create app/api/avatar/route.ts:
import { put } from '@vercel/blob'
const allowedTypes = new Map([
['image/jpeg', 'jpg'],
['image/png', 'png'],
['image/webp', 'webp'],
])
export async function POST(request: Request) {
const form = await request.formData()
const file = form.get('file')
if (!(file instanceof File)) {
return Response.json(
{ error: 'Select a file' },
{ status: 400 },
)
}
const extension = allowedTypes.get(file.type)
if (!extension) {
return Response.json(
{ error: 'Use a JPG, PNG, or WebP image' },
{ status: 415 },
)
}
if (file.size > 4 * 1024 * 1024) {
return Response.json(
{ error: 'The image must be smaller than 4 MB' },
{ status: 413 },
)
}
const blob = await put(
`avatars/${crypto.randomUUID()}.${extension}`,
file,
{
access: 'public',
addRandomSuffix: true,
},
)
return Response.json(blob)
}
The route checks the file type and size before uploading. Because server uploads pass through the Function request body, you’re limited to about 4.5 MB including multipart overhead. Keep this pattern for small files, and use Vercel Blob client uploads for larger public files so the browser sends them directly after your server authorizes the request.
Notice that it doesn’t trust the original filename. Instead, it builds a pathname from a random ID and an extension mapped from the validated MIME type. Passing addRandomSuffix makes the final URL unique, which also helps you avoid stale browser caches when someone replaces an avatar.
Build the upload form
Replace app/page.tsx with a basic upload form:
'use client'
import { useState } from 'react'
export default function Home() {
const [url, setUrl] = useState('')
const [error, setError] = useState('')
async function uploadAvatar(formData: FormData) {
setError('')
const response = await fetch('/api/avatar', {
method: 'POST',
body: formData,
})
const result = await response.json()
if (!response.ok) {
setError(result.error)
return
}
setUrl(result.url)
}
return (
<main>
<h1>Upload an avatar</h1>
<form action={uploadAvatar}>
<input
type='file'
name='file'
accept='image/jpeg,image/png,image/webp'
required
/>
<button>Upload</button>
</form>
{error && <p>{error}</p>}
{url && <img src={url} alt='Uploaded avatar' width='240' />}
</main>
)
}
Start the app:
npm run dev
Pick an image and upload it. The server returns a public Blob URL that the browser can render directly.
Client validation is not security
The accept attribute only helps the file picker filter for the right kinds of files, and it doesn’t protect your server. Anyone can bypass the form and send whatever request they want, so always keep your type and size checks in the Route Handler.
For security-sensitive uploads, inspect the file’s actual bytes instead of trusting file.type, and consider running malware scanning before exposing uploaded files.
You should also add authentication before letting users upload anything:
const user = await auth()
if (!user) {
return new Response('Unauthorized', { status: 401 })
}
Include the signed-in user ID in the pathname, or store it alongside the returned Blob URL in your database.
Upload directly from the browser
Because server uploads pass the entire file through your Function, larger files are better handled with a client upload. Your server issues a short-lived upload token, and the browser sends the file bytes straight to Blob.
Import upload() in your client code:
import { upload } from '@vercel/blob/client'
const blob = await upload(file.name, file, {
access: 'public',
handleUploadUrl: '/api/avatar/upload',
})
Your token route controls what the browser is allowed to upload. Create app/api/avatar/upload/route.ts:
import {
handleUpload,
type HandleUploadBody,
} from '@vercel/blob/client'
export async function POST(request: Request) {
const body = (await request.json()) as HandleUploadBody
try {
const response = await handleUpload({
body,
request,
onBeforeGenerateToken: async () => {
// Authenticate the current user here.
return {
allowedContentTypes: [
'image/jpeg',
'image/png',
'image/webp',
],
maximumSizeInBytes: 5 * 1024 * 1024,
addRandomSuffix: true,
}
},
onUploadCompleted: async ({ blob }) => {
console.log('Upload completed', blob.pathname)
},
})
return Response.json(response)
} catch (error) {
return Response.json(
{ error: (error as Error).message },
{ status: 400 },
)
}
}
Never issue an upload token before authenticating and authorizing the user, or anyone will be able to upload to your store.
Use onUploadCompleted to save the final URL in your database. Since Vercel triggers that callback directly, testing it locally usually requires a public tunnel.
Store the Blob pathname
Both put() and upload() return Blob metadata. At a minimum, keep these values:
{
url: blob.url,
pathname: blob.pathname,
contentType: blob.contentType
}
Save them alongside the database record that owns the file. For example, an avatar row should store the user ID and the Blob pathname. That makes authorization and deletion much safer than trusting an arbitrary URL sent from the browser.
Delete a Blob
To remove a file, import del() on the server:
import { del } from '@vercel/blob'
await del(blobUrl)
Deletions always need to run server-side. Don’t build a route that deletes whatever URL the caller sends over. Instead, verify that the signed-in user owns the file and load its Blob URL from your database first:
const avatar = await db.avatar.findFirst({
where: {
id: avatarId,
userId: user.id,
},
})
if (!avatar) {
return new Response('Not found', { status: 404 })
}
await del(avatar.url)
Once Blob confirms the deletion, remove the database record too.
Upload a private file
For sensitive documents, create a separate private store. Upload files like this:
import { put } from '@vercel/blob'
const blob = await put('invoices/2026-0042.pdf', file, {
access: 'private',
})
Vercel Functions can authenticate with short-lived OIDC tokens, so new private stores don’t need a long-lived read-write token in your app. The returned private URL won’t work as a public link.
Serve a private file
To serve a private file, create an authenticated route and fetch the object with get():
import { get } from '@vercel/blob'
export async function GET(request: Request) {
const user = await auth()
if (!user) {
return new Response('Unauthorized', { status: 401 })
}
const fileId = new URL(request.url).searchParams.get('fileId')
if (!fileId) {
return new Response('Not found', { status: 404 })
}
const file = await findPrivateFileForUser(user.id, fileId)
if (!file) {
return new Response('Not found', { status: 404 })
}
const result = await get(file.pathname, {
access: 'private',
})
if (!result || result.statusCode !== 200) {
return new Response('Not found', { status: 404 })
}
return new Response(result.stream, {
headers: {
'content-type': result.blob.contentType,
'x-content-type-options': 'nosniff',
'cache-control': 'private, no-store',
},
})
}
Here auth() and findPrivateFileForUser() stand in for your app’s own authentication and authorization logic. The route takes an opaque file ID and looks up the exact stored pathname for that user. Don’t pass a user-supplied pathname straight to get().
For large private downloads, consider using a short-lived signed URL. It grants a single operation on one pathname without routing all the bytes through your Function.
Protect the store credential
Older public-store setups use BLOB_READ_WRITE_TOKEN. Treat it like a password:
- never prefix it with
NEXT_PUBLIC_ - never return it from an API route
- never put it in client code
- never commit
.env.local - rotate it immediately if it shows up in logs or Git history
Only ever send a Blob URL or a narrow upload token to the browser, never the store’s full credential.
Treat files as immutable
Blob files are cached, so overwriting the same pathname can leave an older version sitting in a browser or CDN cache for a while.
The easiest way around this is to create a new pathname for every version, which our avatar route already does with a random pathname. Upload the replacement, update your database to point at the new file, and then delete the old Blob. That saves you from dealing with most cache invalidation headaches.
When you’re ready to deploy, the Vercel deployment documentation walks through setting up deployments and managing environments. Once your app is live, you can monitor Blob usage and operations from your project’s Observability section.
Want me to talk about your product? You can sponsor this site.
Related posts about services: