Building a Photo Gallery with Next.js, Vercel Blob Storage, and Advanced Admin Management
Tech Stack: Next.js, TypeScript, Vercel Blob, Sharp, Prisma, PostgreSQL
Building a Photo Gallery with Next.js, Vercel Blob Storage, and Advanced Admin Management
When building my portfolio website, I needed a robust photo gallery system that could handle everything from personal photography to project showcases. After evaluating various options, I decided to build a custom solution using Next.js App Router, Vercel Blob Storage, and a comprehensive admin interface. This implementation taught me valuable lessons about image optimization, storage strategies, and building user-friendly content management systems.
1. Architecture Overview
The photo gallery system consists of several interconnected components:
- Public Gallery: Responsive photo display with album organization
- Admin Interface: Comprehensive photo management with upload, editing, and organization
- Storage Layer: Vercel Blob Storage for reliable image hosting
- Database: PostgreSQL with Prisma for metadata and relationships
- Image Processing: Sharp for server-side optimization
- API Layer: RESTful endpoints for all CRUD operations
Prisma database schema for photo gallery system
// Core database models
model Album {
id Int @id @default(autoincrement())
name String
photos Photo[]
}
model Photo {
id Int @id @default(autoincrement())
filename String
title String?
description String?
albumId Int?
album Album? @relation(fields: [albumId], references: [id])
blobUrl String
width Int
height Int
fileSize Int
order Int @default(0)
pageLinks PhotoPageLink[]
}
This relational structure allows for flexible photo organization while maintaining data integrity.
2. Vercel Blob Storage Integration
Vercel Blob Storage provides an excellent solution for image hosting with global CDN distribution and automatic optimization. Here's how I integrated it:
Upload Strategy
Vercel Blob Storage upload implementation with validation
// Client-side upload for large files
export async function uploadToBlob(file: File): Promise<string> {
const response = await put(file.name, file, {
access: 'public',
handleUploadUrl: '/api/photos/upload',
});
return response.url;
}
// Server-side processing
export async function POST(request: Request) {
const formData = await request.formData();
const file = formData.get('file') as File;
// Validate file type and size
if (!file.type.startsWith('image/')) {
return NextResponse.json({ error: 'Invalid file type' }, { status: 400 });
}
if (file.size > 50 * 1024 * 1024) { // 50MB limit
return NextResponse.json({ error: 'File too large' }, { status: 400 });
}
// Process with Sharp
const buffer = await file.arrayBuffer();
const imageBuffer = Buffer.from(buffer);
const metadata = await sharp(imageBuffer).metadata();
// Upload to Blob
const blob = await put(file.name, file, { access: 'public' });
return NextResponse.json({ url: blob.url, metadata });
}
Optimization Benefits
Vercel Blob Storage provides several advantages:
- Global CDN: Images served from edge locations worldwide
- Automatic Compression: WebP conversion and size optimization
- Cache Headers: Proper HTTP caching for performance
- Security: Secure upload URLs and access control
3. Image Processing with Sharp
Sharp handles server-side image processing for metadata extraction and optimization:
Sharp image processing for metadata extraction and thumbnail generation
import sharp from 'sharp';
export async function processImage(buffer: Buffer) {
const image = sharp(buffer);
const metadata = await image.metadata();
// Extract essential information
return {
width: metadata.width!,
height: metadata.height!,
format: metadata.format!,
size: metadata.size!,
hasAlpha: metadata.hasAlpha,
orientation: metadata.orientation
};
}
// Generate thumbnails for faster loading
export async function generateThumbnail(buffer: Buffer, width: number = 400) {
return await sharp(buffer)
.resize(width, null, {
withoutEnlargement: true,
fastShrinkOnLoad: true
})
.jpeg({ quality: 85 })
.toBuffer();
}
Sharp integration provides:
- Metadata Extraction: Dimensions, format, and file size
- Format Conversion: Convert to optimal formats
- Resize Operations: Generate thumbnails and responsive images
- Quality Control: Balance between file size and image quality
4. The Photo Gallery Component
The public-facing gallery uses a responsive grid layout with album organization:
'use client';
export default function PhotoGallery() {
const [photos, setPhotos] = useState<Photo[]>([]);
const [selectedAlbum, setSelectedAlbum] = useState<string>('');
const [selectedPhoto, setSelectedPhoto] = useState<Photo | null>(null);
// Fetch photos with optional album filtering
useEffect(() => {
const fetchPhotos = async () => {
const params = selectedAlbum ? '?albumId=' + selectedAlbum : '';
const response = await fetch('/api/photos' + params);
const data = await response.json();
setPhotos(data);
};
fetchPhotos();
}, [selectedAlbum]);
// Group photos by album for organized display
const groupedPhotos = photos.reduce((acc, photo) => {
const albumName = photo.album?.name || 'Uncategorized';
if (!acc[albumName]) acc[albumName] = [];
acc[albumName].push(photo);
return acc;
}, {} as Record<string, Photo[]>);
return (
<div className="space-y-8">
{Object.entries(groupedPhotos).map(([albumName, albumPhotos]) => (
<section key={albumName}>
<h2 className="text-2xl font-bold mb-4">{albumName}</h2>
{/* Responsive grid with varied sizing */}
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{albumPhotos.map((photo, index) => (
<div
key={photo.id}
className={cn(
"relative cursor-pointer rounded-lg overflow-hidden",
// Featured photos span multiple cells
index === 0 && "md:col-span-2 md:row-span-2"
)}
onClick={() => setSelectedPhoto(photo)}
>
<Image
src={photo.blobUrl}
alt={photo.title || photo.filename}
width={photo.width}
height={photo.height}
className="object-cover w-full h-full hover:scale-105 transition-transform"
sizes="(max-width: 768px) 50vw, (max-width: 1200px) 33vw, 25vw"
/>
{/* Overlay with photo info */}
<div className="absolute inset-0 bg-black/0 hover:bg-black/30 transition-colors">
<div className="absolute bottom-2 left-2 text-white opacity-0 hover:opacity-100 transition-opacity">
<p className="font-medium">{photo.title}</p>
<p className="text-sm">{photo.description}</p>
</div>
</div>
</div>
))}
</div>
</section>
))}
{/* Modal for enlarged view */}
<PhotoModal
photo={selectedPhoto}
onClose={() => setSelectedPhoto(null)}
/>
</div>
);
}
Key Gallery Features
- Responsive Grid: Adapts to screen size with CSS Grid
- Variable Sizing: Featured photos span multiple grid cells
- Lazy Loading: Images load as they enter viewport
- Album Organization: Photos grouped by album with clear sections
- Modal View: Enlarged photo display with navigation
5. Admin Photo Management System
The admin interface provides comprehensive photo management capabilities:
export default function MediaLibrary() {
const [photos, setPhotos] = useState<Photo[]>([]);
const [albums, setAlbums] = useState<Album[]>([]);
const [selectedPhotos, setSelectedPhotos] = useState<Set<number>>(new Set());
const [isUploading, setIsUploading] = useState(false);
// Drag and drop upload
const onDrop = useCallback(async (acceptedFiles: File[]) => {
setIsUploading(true);
try {
for (const file of acceptedFiles) {
// Large files: client-side upload
if (file.size > 4.5 * 1024 * 1024) {
const blobUrl = await uploadToBlob(file);
await savePhotoMetadata({
filename: file.name,
blobUrl,
albumId: selectedAlbum
});
} else {
// Small files: server-side upload
const formData = new FormData();
formData.append('file', file);
formData.append('albumId', selectedAlbum.toString());
await fetch('/api/photos', {
method: 'POST',
body: formData
});
}
}
await refreshPhotos();
} catch (error) {
toast.error('Upload failed');
} finally {
setIsUploading(false);
}
}, [selectedAlbum]);
return (
<div className="space-y-6">
{/* Album Management */}
<AlbumManager albums={albums} onUpdate={refreshAlbums} />
{/* Upload Area */}
<DropzoneArea
onDrop={onDrop}
isUploading={isUploading}
maxSize={50 * 1024 * 1024} // 50MB
accept={{ 'image/*': ['.jpeg', '.jpg', '.png', '.webp', '.gif'] }}
/>
{/* Photo Grid with Selection */}
<PhotoGrid
photos={photos}
selectedPhotos={selectedPhotos}
onSelectionChange={setSelectedPhotos}
onEdit={handlePhotoEdit}
onDelete={handlePhotoDelete}
/>
{/* Batch Operations */}
<BatchOperations
selectedPhotos={selectedPhotos}
onBulkDelete={handleBulkDelete}
onBulkMove={handleBulkMove}
/>
</div>
);
}
Admin Features
The admin interface includes:
- Drag & Drop Upload: Intuitive file upload with progress indicators
- Album Management: Create, rename, and delete albums
- Photo Editing: Update titles, descriptions, and metadata
- Batch Operations: Select and manage multiple photos at once
- Photo Reordering: Drag and drop to change photo order within albums
- Background Settings: Set photos as site background images
- Page Associations: Link photos to specific site pages
6. Environment-Aware Image Loading
One challenge with Vercel Blob Storage is cost management during development. I implemented environment-aware loading:
// Image utilities with environment awareness
export function getOptimizedImageSrc(photo: Photo): string {
// In development, use placeholder to avoid blob storage costs
if (process.env.NODE_ENV === 'development') {
return '/placeholder.svg?w=' + photo.width + '&h=' + photo.height;
}
return photo.blobUrl;
}
// Image component with smart loading
export function OptimizedImage({ photo, ...props }: ImageProps) {
const src = getOptimizedImageSrc(photo);
return (
<Image
src={src}
alt={photo.title || photo.filename}
width={photo.width}
height={photo.height}
className="object-cover"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
loading="lazy"
{...props}
/>
);
}
This approach provides:
- Cost Control: No blob storage requests during development
- Fast Development: Instant placeholder loading
- Production Performance: Full optimization in production
- Consistent Dimensions: Placeholders maintain aspect ratios
7. Performance Optimizations
Several optimizations ensure fast loading and smooth user experience:
Image Optimization
// Next.js Image component configuration
const imageLoader = ({ src, width, quality }: ImageLoaderProps) => {
// Use Vercel's built-in image optimization
if (src.includes('blob.vercel-storage.com')) {
return src + '?w=' + width + '&q=' + (quality || 75);
}
return src;
};
// Responsive sizing
const imageSizes = "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw";
Caching Strategy
// API route with proper caching headers
export async function GET(request: Request) {
const photos = await getPhotosFromDatabase();
return NextResponse.json(photos, {
headers: {
'Cache-Control': 'public, max-age=300, s-maxage=600',
'CDN-Cache-Control': 'public, max-age=31536000',
}
});
}
Database Optimization
-- Optimized queries with proper indexing
CREATE INDEX idx_photos_album_order ON Photo(albumId, "order");
CREATE INDEX idx_photos_page_links ON PhotoPageLink(photoId, pageType);
8. Security and Validation
The system includes comprehensive security measures:
// File validation
export function validateImageFile(file: File): ValidationResult {
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
const maxSize = 50 * 1024 * 1024; // 50MB
if (!allowedTypes.includes(file.type)) {
return { valid: false, error: 'Invalid file type' };
}
if (file.size > maxSize) {
return { valid: false, error: 'File too large' };
}
return { valid: true };
}
// Admin authentication
export async function verifyAdminAccess(request: Request) {
const user = await getCurrentUser(request);
if (!user || user.role !== 'ADMIN') {
throw new Error('Unauthorized access');
}
return user;
}
9. Integration with Site Features
The photo system integrates seamlessly with other site features:
Background Images
// Site settings for background images
export async function getSiteSettings() {
const settings = await prisma.siteSettings.findFirst({
include: {
backgroundImage: true
}
});
return {
...settings,
backgroundImageUrl: settings?.backgroundImage?.blobUrl
};
}
Page Associations
// Link photos to specific pages
export async function getPhotosForPage(pageType: string) {
return await prisma.photo.findMany({
where: {
pageLinks: {
some: { pageType }
}
},
include: { album: true },
orderBy: { order: 'asc' }
});
}
10. Lessons Learned and Best Practices
Through building this photo gallery system, I learned several valuable lessons:
Storage Strategy
- Hybrid Upload: Use client-side uploads for large files to bypass serverless limits
- Cost Management: Implement environment-aware loading for development
- CDN Benefits: Leverage Vercel's global CDN for optimal performance
Image Processing
- Sharp Integration: Essential for metadata extraction and processing
- Format Optimization: Automatic WebP conversion improves performance
- Responsive Images: Proper
sizesattribute reduces bandwidth usage
User Experience
- Progressive Enhancement: Start with server components, add interactivity where needed
- Intuitive Admin: Drag-and-drop interfaces improve content management workflow
- Performance First: Lazy loading and proper caching ensure fast page loads
Database Design
- Flexible Relationships: Separate albums, photos, and page associations for maximum flexibility
- Proper Indexing: Essential for fast queries as photo collections grow
- Cascade Deletes: Maintain data integrity when removing content
Conclusion
Building a comprehensive photo gallery system with Next.js and Vercel Blob Storage has been an incredibly rewarding experience. The combination of server-side rendering, intelligent caching, robust admin tools, and global CDN distribution creates a powerful platform for managing and displaying images.
The key to success was balancing performance, usability, and maintainability while leveraging the strengths of each technology in the stack. The result is a system that's both user-friendly for content management and optimized for end-user experience.
For more information on the technologies used:
- Vercel Blob Storage Documentation
- Sharp Image Processing
- Next.js Image Optimization
- Prisma ORM Documentation
If you're building a similar system, focus on the user experience first, then optimize for performance and scalability as your content library grows.