An example of a Next.js application allowing you to upload photos to an S3 bucket

Next.js + AWS S3 Upload

This is an example of a Next.js application allowing you to upload photos to an S3 bucket.

Getting Started

Option 1: Use an existing S3 bucket.

Retrieve your existing access key, secret key, S3 bucket region and name. Provide those values after clicking "Deploy" to automatically set the environment variables.

Option 2: Create an S3 bucket.

  1. Create a new IAM role with permission for AWSCloudFormationFullAccess and AmazonS3FullAccess.
  2. Save the access key and secret key.
  3. Install the AWS CLI and run aws configure.
  4. This will prompt you to enter the access key and secret key.
  5. Create an .env.local file similar to .env.example.
  6. Run cdk deploy to create an S3 bucket with the correct CORS settings.
  7. Visit your newly created S3 bucket and retrieve the name and region.
  8. Add the name and region to .env.local.
  9. Run yarn dev to start the Next app at localhost:3000.
  10. Choose a .png or .jpg file.
  11. You should see your file successfully uploaded to S3.

This example uses createPresignedPost instead of getSignedUrlPromise to allow setting max/min file sizes with content-length-range.

Commands

  • yarn dev – Starts the Next.js app at localhost:3000.
  • cdk deploy – Deploy this stack to your default AWS account/region
  • cdk diff – Compare deployed stack with current state
  • cdk synth – Emits the synthesized CloudFormation template

GitHub

https://github.com/leerob/nextjs-aws-s3