Getting Started with Next.js S3 Uploader
In this section, you will learn how to get started with Next.js S3 Uploader. We'll cover the prerequisites, setting up your Amazon S3 bucket, and integrating the package into both your Next.js frontend and API route.
Prerequisites
Before you begin, make sure you have the following prerequisites:
Amazon S3 Bucket
You'll need an Amazon S3 bucket to store your uploaded files. Depending on your requirements, you can create a public or private bucket:
Public Bucket
If you want to allow public access to your uploaded files, create your S3 bucket with a public access policy. Here's an example of a public access policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicRead",
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::your-bucket-name/*"]
}
]
}
Private Bucket
For a private bucket, you can configure Next.js S3 Uploader to generate pre-signed URLs for secure access to files. We'll cover this in more detail in the API Refrence section.
Next.js Application Directory
Make sure you have a Next.js application directory set up. You'll be integrating Next.js S3 Uploader into both your frontend and API route.
Frontend Implementation
To integrate Next.js S3 Uploader into your frontend, follow these steps:
Import the Hook
In your Next.js component, import the useS3FileUpload
hook from "next-s3-uploader":
import { useS3FileUpload } from "next-s3-uploader";
Use the Hook
Inside your component, use the useS3FileUpload
hook to manage file uploads and track progress:
function UploadPage() {
const { uploadedFiles, uploadFiles } = useS3FileUpload({
multiple: true, // Allow multiple file uploads (optional)
maxFiles: 10, // 10 files limit (optional)
maxFileSize: 10 * 1024 * 1024, // 10MB limit (optional)
});
// Your file upload logic here
return (
// Your component JSX
);
}
Handle File Upload
Implement the logic to handle file uploads, such as selecting files and calling uploadFiles
:
const handleFileChange = async (e) => {
const files = e.target.files;
if (files && files.length > 0) {
await uploadFiles(files);
}
};
Render Uploaded Files
Render the uploaded files using the uploadedFiles
array:
return (
<div>
<h1>File Upload to Amazon S3</h1>
<input
title="Upload File"
type="file"
accept="image/*"
multiple
onChange={handleFileChange}
/>
{/* Display uploaded files and progress */}
<div>
{uploadedFiles.map((file, index) => (
<div key={index}>
<p>File Key: {file.key}</p>
<p>Status: {file.status}</p>
<p>Progress: {file.progress}%</p>
<p>Time Left: {file.timeLeft || "Calculating..."}</p>
{file.status === "success" && (
{/* Display the uploaded image */}
<img src={file.url} alt={`Uploaded File ${index}`} />
{/* Or display a download link */}
<a href={file.url} download>
Download File
</a>
)}
</div>
))}
</div>
</div>
);
API Route Implementation
To create an API route for handling pre-signed URLs, follow these steps:
Import Dependencies
In your API route, import the necessary dependencies from "next-s3-uploader":
import { createS3Client, generatePresignedUrls } from "next-s3-uploader";
Create the API Route
Inside your API route function, configure the S3 client and generate pre-signed URLs:
export async function POST(req) {
try {
const { keys } = await req.json();
// Configure AWS S3 client
const s3Client = createS3Client({
provider: "aws", // Amazon S3 provider
region: "us-east-1", // Specify the appropriate AWS region
credentials: {
accessKeyId: "YOUR_ACCESS_KEY_ID", // Your AWS access key ID
secretAccessKey: "YOUR_SECRET_ACCESS_KEY", // Your AWS secret access key
},
});
// Generate pre-signed URLs
const bucket = "your-bucket-name";
const prefix = `userId/images/`;
const urls = await generatePresignedUrls(s3Client, keys, bucket, prefix);
return new Response(JSON.stringify(urls), { status: 200 });
} catch (error) {
console.error("Error processing the request:", error);
return new Response("Internal Server Error", { status: 500 });
}
}
With these steps, you'll be ready to start using Next.js S3 Uploader in your Next.js application.
Continue to the Usage section to explore more usage scenarios and options.