Image Upload

Upload files / images to S3 using pre-signed URLs for secure uploads.

This template uses AWS S3 for image uploading. For more information, go to AWS S3 docs

Setup

Prerequisites

☁️

AWS Account

Account with S3 access permissions

🪣

S3 Bucket

Configured S3 bucket for storage

🔑

AWS Credentials

Access and secret keys configured

Environment Variables

Terminal

Components

Image Upload Component

A reusable component for handling image uploads with preview:

components/image-upload.tsx
TYPESCRIPT

Features

🖱️

Drag & Drop

Support for drag and drop file uploads using react-dropzone

🖼️

Image Preview

Real-time preview of uploaded images with Next.js Image component

File Validation

Validates file types and shows appropriate error messages

Loading States

Visual feedback during upload process with loading indicators

Upload Process

1. Get Pre-signed URL

Request a pre-signed URL from the server:

lib/image-upload.ts
TYPESCRIPT

2. Upload to S3

Upload the file directly to S3 using the pre-signed URL:

lib/image-upload.ts
TYPESCRIPT

API Route

The /api/image-upload route handles the server-side logic for generating pre-signed URLs and managing S3 uploads.

API Route Handler

Server-side implementation for secure image uploads:

app/api/image-upload/route.ts
TYPESCRIPT

Key Features

🔒

Secure File Names

Generates unique file names using MD5 hashing and timestamps

⏱️

Rate Limiting

Prevents abuse with Upstash Redis-based rate limiting

👤

User Isolation

Stores files in user-specific S3 directories

📦

Caching Strategy

Implements proper cache control headers

Filename Generation

Secure filename generation to prevent conflicts:

lib/image-upload.ts
TYPESCRIPT

Rate Limiting Setup

Configure rate limiting with Upstash Redis:

TYPESCRIPT

AWS Configuration

AWS Client Setup

Configure the AWS S3 client:

TYPESCRIPT

Best Practices

Security

  • 1
    Use pre-signed URLs for secure uploads
  • 2
    Implement proper file validation
  • 3
    Set appropriate CORS policies
  • 4
    Use environment variables for credentials

User Experience

  • 1
    Show upload progress indicators
  • 2
    Provide clear error messages
  • 3
    Support drag and drop
  • 4
    Preview uploaded images