sajad torkamani

Setup

Install NPM package:

npm i @vercel/blob

Create blob store in the Vercel dashboard.

Vercel blobs

You should get a BLOB_READ_WRITE_TOKEN value on creating a Blob database. Make note of this in a safe place like 1Password.

Set the BLOB_READ_WRITE_TOKEN env variable in your .env file:

BLOB_READ_WRITE_TOKEN=<your-token>

Upload a file using a Server Action

import { put } from '@vercel/blob';
import { revalidatePath } from 'next/cache';
 
export async function Form() {
  async function uploadImage(formData: FormData) {
    'use server';
    const imageFile = formData.get('image') as File;
    const blob = await put(imageFile.name, imageFile, {
      access: 'public',
      addRandomSuffix: true,
    });
    revalidatePath('/');
    return blob;
  }
 
  return (
    <form action={uploadImage}>
      <label htmlFor="image">Image</label>
      <input
        type="file"
        id="image"
        name="image"
        accept="image/jpeg, image/png, image/webp"
        required
      />
      <button>Upload</button>
    </form>
  );
}

Add your blob’s host to your next.config.ts

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      new URL('https://my-store-id.public.blob.vercel-storage.com/**'),
    ],
  },
};
 
module.exports = nextConfig;

Now, you can list your blobs using the next/image component:

import { list } from '@vercel/blob';
import Image from 'next/image';
 
export async function Images() {
  const { blobs } = await list();
 
  return (
    <section>
      {blobs.map((image, i) => (
        <Image
          priority={i < 2}
          key={image.pathname}
          src={image.url}
          alt="My Image"
          width={200}
          height={200}
        />
      ))}
    </section>
  );
}

Notes