

 The [AWS SDK for JavaScript V3 API Reference Guide](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/) describes in detail all the API operations for the AWS SDK for JavaScript version 3 (V3). 

# Browser Script Considerations
<a name="browser-js-considerations"></a>

The following topics describe special considerations for using the AWS SDK for JavaScript in browser scripts.

**Topics**
+ [Build the SDK for Browsers](building-sdk-for-browsers.md)
+ [Cross-origin resource sharing (CORS)](cors.md)
+ [Bundle applications with webpack](webpack.md)

# Build the SDK for Browsers
<a name="building-sdk-for-browsers"></a>

Unlike SDK for JavaScript version 2 (V2), V3 is not provided as a JavaScript file with support included for a default set of services. Instead V3 enables you to bundle and include in the browser only the SDK for JavaScript files you require, reducing overhead. We recommend using Webpack to bundle the required SDK for JavaScript files, and any additional third-party packages your require, into a single `Javascript` file, and load it into browser scripts using a `<script>` tag. For more information about Webpack, see [Bundle applications with webpack](webpack.md). 

If you work with the SDK outside of an environment that enforces CORS in your browser and if you want access to all services provided by the SDK for JavaScript, you can build a custom copy of the SDK locally by cloning the repository and running the same build tools that build the default hosted version of the SDK. The following sections describe the steps to build the SDK with extra services and API versions.

## Use the SDK Builder to build the SDK for JavaScript
<a name="using-the-sdk-builder"></a>

**Note**  
Amazon Web Services version 3 (V3) no longer supports Browser Builder. To minimize bandwidth usage of browser applications, we recommend you import named modules, and bundle them to reduce size. For more information about bundling, see [Bundle applications with webpack](webpack.md).

# Cross-origin resource sharing (CORS)
<a name="cors"></a>

Cross-origin resource sharing, or CORS, is a security feature of modern web browsers. It enables web browsers to negotiate which domains can make requests of external websites or services. 

CORS is an important consideration when developing browser applications with the AWS SDK for JavaScript because most requests to resources are sent to an external domain, such as the endpoint for a web service. If your JavaScript environment enforces CORS security, you must configure CORS with the service.

CORS determines whether to allow sharing of resources in a cross-origin request based on the following:
+ The specific domain that makes the request 
+ The type of HTTP request being made (GET, PUT, POST, DELETE and so on)

## How CORS works
<a name="how-cors-works"></a>

In the simplest case, your browser script makes a GET request for a resource from a server in another domain. Depending on the CORS configuration of that server, if the request is from a domain that's authorized to submit GET requests, the cross-origin server responds by returning the requested resource.

If either the requesting domain or the type of HTTP request is not authorized, the request is denied. However, CORS makes it possible to preflight the request before actually submitting it. In this case, a preflight request is made in which the `OPTIONS` access request operation is sent. If the cross-origin server's CORS configuration grants access to the requesting domain, the server sends back a preflight response that lists all the HTTP request types that the requesting domain can make on the requested resource.

![\[Process flow for CORS requests\]](http://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/images/cors-overview.png)


## Is CORS configuration required?
<a name="the-need-for-cors-configuration"></a>

Amazon S3 buckets require CORS configuration before you can perform operations on them. In some JavaScript environments CORS might not be enforced and therefore configuring CORS is unnecessary. For example, if you host your application from an Amazon S3 bucket and access resources from `*.s3.amazonaws.com` or some other specific endpoint, your requests won't access an external domain. Therefore, this configuration doesn't require CORS. In this case, CORS is still used for services other than Amazon S3.

## Configure CORS for an Amazon S3 bucket
<a name="configuring-cors-s3-bucket"></a>

You can configure an Amazon S3 bucket to use CORS in the Amazon S3 console.

If you are configuring CORS in the AWS Web Services Management Console, you must use JSON to create a CORS configuration. The new AWS Web Services Management Console only supports JSON CORS configurations. 

**Important**  
In the new AWS Web Services Management Console, the CORS configuration must be JSON.

1. In the AWS Web Services Management Console, open the Amazon S3 console, find the bucket you want to configure and select its check box.

1. In the pane that opens, choose **Permissions**.

1. On the **Permission** tab, choose **CORS Configuration**.

1. Enter your CORS configuration in the **CORS Configuration Editor**, and then choose **Save**.

A CORS configuration is an XML file that contains a series of rules within a `<CORSRule>`. A configuration can have up to 100 rules. A rule is defined by one of the following tags:
+ `<AllowedOrigin>` – Specifies domain origins that you allow to make cross-domain requests.
+ `<AllowedMethod>` – Specifies a type of request you allow (GET, PUT, POST, DELETE, HEAD) in cross-domain requests.
+ `<AllowedHeader>` – Specifies the headers allowed in a preflight request.

For example configurations, see [How do I configure CORS on my bucket?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html#how-do-i-enable-cors) in the *Amazon Simple Storage Service User Guide*.

## CORS configuration example
<a name="cors-configuration-example"></a>

The following CORS configuration example allows a user to view, add, remove, or update objects inside of a bucket from the domain `example.org`. However, we recommend that you scope the `<AllowedOrigin>` to the domain of your website. You can specify `"*"` to allow any origin.

**Important**  
In the new S3 console, the CORS configuration must be JSON.

------
#### [ XML ]

```
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>https://example.org</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
    <ExposeHeader>x-amz-meta-custom-header</ExposeHeader>
  </CORSRule>
</CORSConfiguration>
```

------
#### [ JSON ]

```
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "https://www.example.org"
        ],
        "ExposeHeaders": [
             "ETag",
             "x-amz-meta-custom-header"]
    }
]
```

------

This configuration does not authorize the user to perform actions on the bucket. It enables the browser's security model to allow a request to Amazon S3. Permissions must be configured through bucket permissions or IAM role permissions.

You can use `ExposeHeader` to let the SDK read response headers returned from Amazon S3. For example, read the `ETag` header from a `PUT` or multipart upload, you need to include the `ExposeHeader` tag in your configuration, as shown in the previous example. The SDK can only access headers that are exposed through CORS configuration. If you set metadata on the object, values are returned as headers with the prefix `x-amz-meta-`, such as `x-amz-meta-my-custom-header`, and must also be exposed in the same way.

# Bundle applications with webpack
<a name="webpack"></a>

The use of code modules by web applications in browser scripts or Node.js creates dependencies. These code modules can have dependencies of their own, resulting in a collection of interconnected modules that your application requires to function. To manage dependencies, you can use a module bundler like `webpack`.

The `webpack` module bundler parses your application code, searching for `import` or `require` statements, to create bundles that contain all the assets your application needs. This is so that the assets can be easily served through a webpage. The SDK for JavaScript can be included in `webpack` as one of the dependencies to include in the output bundle.

For more information about `webpack`, see the [webpack module bundler](https://webpack.github.io/) on GitHub.

## Install webpack
<a name="webpack-installing"></a>

To install the `webpack` module bundler, you must first have npm, the Node.js package manager, installed. Type the following command to install the `webpack` CLI and JavaScript module.

```
npm install --save-dev webpack
```

To use the `path` module for working with file and directory paths, which is installed automatically with webpack, you might need to install the Node.js `path-browserify` package. 

```
npm install --save-dev path-browserify
```

## Configure webpack
<a name="webpack-configuring"></a>

By default, Webpack searches for a JavaScript file named `webpack.config.js` in your project's root directory. This file specifies your configuration options. The following is an example of a `webpack.config.js` configuration file for WebPack version 5.0.0 and later.

**Note**  
Webpack configuration requirements vary depending on the version of Webpack you install. For more information, see the [Webpack documentation](https://webpack.js.org/configuration/). 

```
// Import path for resolving file paths
var path = require("path");
module.exports = {
  // Specify the entry point for our app.
  entry: [path.join(__dirname, "browser.js")],
  // Specify the output file containing our bundled code.
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
   // Enable WebPack to use the 'path' package.
   resolve:{
  fallback: { path: require.resolve("path-browserify")}
  }
  /**
  * In Webpack version v2.0.0 and earlier, you must tell 
  * webpack how to use "json-loader" to load 'json' files.
  * To do this Enter 'npm --save-dev install json-loader' at the 
  * command line to install the "json-loader' package, and include the 
  * following entry in your webpack.config.js.
  * module: {
    rules: [{test: /\.json$/, use: use: "json-loader"}]
  }
  **/
};
```

In this example, `browser.js` is specified as the *entry point*. The *entry point* is the file `webpack` uses to begin searching for imported modules. The file name of the output is specified as `bundle.js`. This output file will contain all the JavaScript the application needs to run. If the code specified in the entry point imports or requires other modules, such as the SDK for JavaScript, that code is bundled without needing to specify it in the configuration.

## Run webpack
<a name="webpack-running"></a>

To build an application to use `webpack`, add the following to the `scripts` object in your `package.json` file.

```
"build": "webpack"
```

The following is an example `package.json` file that demonstrates adding `webpack`.

```
{
  "name": "aws-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@aws-sdk/client-iam": "^3.32.0",
    "@aws-sdk/client-s3": "^3.32.0"
  },
  "devDependencies": {
    "webpack": "^5.0.0"
  }
}
```

To build your application, enter the following command.

```
npm run build
```

The `webpack` module bundler then generates the JavaScript file you specified in your project's root directory.

## Use the webpack bundle
<a name="webpack-using-bundle"></a>

To use the bundle in a browser script, you can incorporate the bundle using a `<script>` tag, as shown in the following example.

```
<!DOCTYPE html>
<html>
    <head>
        <title>Amazon SDK with webpack</title>
    </head> 
    <body>
        <div id="list"></div>
        <script src="bundle.js"></script>
    </body>
</html>
```

## Bundle for Node.js
<a name="webpack-nodejs-bundles"></a>

You can use `webpack` to generate bundles that run in Node.js by specifying `node` as a target in the configuration.

```
target: "node"
```

This is useful when running a Node.js application in an environment where disk space is limited. Here is an example `webpack.config.js` configuration with Node.js specified as the output target.

```
// Import path for resolving file paths
var path = require("path");
module.exports = {
  // Specify the entry point for our app.
  entry: [path.join(__dirname, "browser.js")],
  // Specify the output file containing our bundled code.
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  // Let webpack know to generate a Node.js bundle.
  target: "node",
   // Enable WebPack to use the 'path' package.
   resolve:{
  fallback: { path: require.resolve("path-browserify")}
   /**
   * In Webpack version v2.0.0 and earlier, you must tell 
   * webpack how to use "json-loader" to load 'json' files.
   * To do this Enter 'npm --save-dev install json-loader' at the 
   * command line to install the "json-loader' package, and include the 
   * following entry in your webpack.config.js.
   module: {
    rules: [{test: /\.json$/, use: use: "json-loader"}]
  }
  **/
};
```