AWS SDK for JavaScript
Developer Guide for SDK v2

Create an Amazon S3 Bucket Configured as a Static Website

This topic is part of a larger tutorial about using the AWS SDK for JavaScript with AWS Lambda functions. To start at the beginning of the tutorial, see Tutorial: Creating and Using Lambda Functions.

In this task, you will focus on creating and preparing the Amazon S3 bucket used by the application.


      JavaScript running in a browser that creates an Amazon S3 bucket

For this application, the first thing you need to create is an Amazon S3 bucket to store all the browser assets. These include the HTML file, all graphics files, and the CSS file. The bucket is configured as a static website so that it also serves the application from the bucket's URL.

The slotassets.zip archive file contains a Node.js script named s3-bucket-setup.js that creates the Amazon S3 bucket and sets the website configuration.

To create and configure the Amazon S3 bucket that the tutorial application uses

  1. Open the slotassets.zip archive file you downloaded from the code example archive on GitHub.

  2. Copy the s3-bucket-setup.js script from the archive to the folder that contains your credentials JSON file.

  3. At the command line, type:

    node s3-bucket-setup.js BUCKET_NAME

    where BUCKET_NAME is the name for the bucket. The bucket name must be globally unique. When successful, the script displays the URL of the new bucket. Make a note of this URL because you'll use it later.

Setup Script

The setup script runs the following code. It takes the command-line argument that is passed in and uses it to specify the bucket name and the parameter that makes the bucket publicly readable. It then sets up the parameters used to enable the bucket to act as a static website host.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // Create S3 service object s3 = new AWS.S3({apiVersion: '2006-03-01'}); // Create params JSON for S3.createBucket var bucketParams = { Bucket : process.argv[2], ACL : 'public-read' }; // Create params JSON for S3.setBucketWebsite var staticHostParams = { Bucket: process.argv[2], WebsiteConfiguration: { ErrorDocument: { Key: 'error.html' }, IndexDocument: { Suffix: 'index.html' }, } }; // Call S3 to create the bucket s3.createBucket(bucketParams, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Bucket URL is ", data.Location); // Set the new policy on the newly created bucket s3.putBucketWebsite(staticHostParams, function(err, data) { if (err) { // Display error message console.log("Error", err); } else { // Update the displayed policy for the selected bucket console.log("Success", data); } }); } });

This script uses code from these AWS SDK for JavaScript code example topics:

Next Step

Return to the full Tutorial Steps.

On this page: