Image Upload
Upload files and images to AWS S3 using pre-signed URLs for secure uploads in your application.
This template uses AWS S3 for image uploading. For more information, visit the AWS S3 documentation.
Setup
Prerequisites
AWS Account
S3 Bucket
AWS Credentials
Environment Variables
Add the following variables to your .env.local
file:
Never commit your AWS credentials to version control. Always use environment variables.
Components
Image Upload Component
A reusable component for handling image uploads with preview:
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
The image upload process uses pre-signed URLs to securely upload files directly to S3 without exposing your AWS credentials.
1. Get Pre-signed URL
Request a pre-signed URL from the server:
2. Upload to S3
Upload the file directly to S3 using the pre-signed URL:
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:
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:
Rate Limiting Setup
Configure rate limiting with Upstash Redis:
AWS Configuration
AWS Client Setup
Configure the AWS S3 client:
The S3Client is configured using environment variables to keep credentials secure.
Usage Example
Here's how to implement the image upload component in a form:
CORS Configuration
Important
You must configure CORS settings on your S3 bucket to allow uploads from your domain.
Add the following CORS configuration to your S3 bucket:
Best Practices
Security
- Use pre-signed URLs for secure uploads
- Implement proper file validation
- Set appropriate CORS policies
- Use environment variables for credentials
User Experience
- Show upload progress indicators
- Provide clear error messages
- Support drag and drop
- Preview uploaded images