Setting Up Public S3 Bucket Policy for React and Node.js

Setting Up Public S3 Bucket Policy for React and Node.js

Setting Up Public S3 Bucket Policy for React and Node.js


1. S3 Bucket Policy

A public S3 bucket policy allows everyone to access the objects in the bucket. Here's an example of a public policy for an S3 bucket:

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "PublicReadGetObject",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::your-bucket-name/*"
      }
    ]
  }

Replace your-bucket-name with the name of your S3 bucket.

2. Applying the Policy to the S3 Bucket

  1. Go to the AWS S3 console.
  2. Select your bucket.
  3. Go to the "Permissions" tab.
  4. Click on "Bucket Policy".
  5. Paste the JSON policy above and save.

3. Using the S3 Bucket in a Node.js (React) Application

In your React application, you can set an environment variable to store your CDN URL. Create a .env file at the root of your React project if you don't already have one and add the following line:

REACT_APP_CDN_URL=https://your-bucket-name.s3.amazonaws.com

Replace https://your-bucket-name.s3.amazonaws.com with the actual URL of your S3 bucket.

4. Accessing the Environment Variable in Your React Code

In your React components, you can access the environment variable like this:

const cdnUrl = process.env.REACT_APP_CDN_URL;

const imageUrl = `${cdnUrl}/path-to-your-image.jpg`;

return (
  <img src={imageUrl} alt="Example" />
);

5. Node.js Backend (if applicable)

If you have a Node.js backend that needs to interact with your S3 bucket, you can use the AWS SDK for JavaScript. Here's an example of how to list objects in your S3 bucket:

const AWS = require('aws-sdk');

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: 'your-region'
});

const params = {
  Bucket: 'your-bucket-name'
};

s3.listObjectsV2(params, (err, data) => {
  if (err) {
    console.log(err, err.stack);
  } else {
    console.log(data);
  }
});

Ensure you have the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set in your environment variables or your AWS credentials configured properly.

By following these steps, you should be able to set up a public S3 bucket policy and access it from both your React front-end and Node.js backend.

Post a Comment

0 Comments