Code and resources for optimizing image uploading speed to AWS S3 buckets in a Next.js app directory using @apollo/server , including directory API routes for AWS S3 bucket integration. Utilizes @aws-sdk, @aws-sdk/client-s3, @as-integrations/next, dropzone, graphql, and graphql-tag.
First, run the development server:
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
Follow these steps to enable image uploading to an AWS S3 bucket in your Next.js application:
Add the following environment variables to your .env
file:
NEXT_PUBLIC_REGION=your-region
NEXT_PUBLIC_AWS_BUCKET=your-bucket-name
NEXT_PUBLIC_AWS_ACCESS_KEY_ID=your-access-key-id
NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY=your-secret-access-key
Add the following policy to your S3 bucket's CORS configuration to allow cross-origin requests:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
}
]
}
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST",
"DELETE",
"HEAD"
],
"AllowedOrigins": [
"http://localhost:3000",
"https://example.app",
"http://example.com",
"http://example.app"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
With these steps completed, your Next.js application should be configured to upload images to your AWS S3 bucket.
Customize the CORS policy according to your application's needs, specifying the allowed headers, methods, and origins.
For security reasons, restrict permissions in the S3 bucket policy based on your application's requirements.
Additionally, in the policy section, you can create policies for specific actions such as requests, updates, or deletes. It is not recommended to provide full access for the live environment.
It is essential to carefully review and configure the bucket policy to ensure the security and integrity of your AWS S3 bucket.