

 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). 

# Get started with the AWS SDK for JavaScript
<a name="getting-started"></a>

The AWS SDK for JavaScript provides access to web services in either a browser or Node.js environment. This section has getting started exercises that show you how to work with the AWS SDK for JavaScript in each of these JavaScript environments.

**Topics**
+ [SDK authentication with AWS](getting-your-credentials.md)
+ [Get started with Node.js](getting-started-nodejs.md)
+ [Get started in the browser](getting-started-browser.md)
+ [Getting started in React Native](getting-started-react-native.md)

# SDK authentication with AWS
<a name="getting-your-credentials"></a>

You must establish how your code authenticates with AWS when developing with AWS services. You can configure programmatic access to AWS resources in different ways depending on the environment and the AWS access available to you. 

To choose your method of authentication and configure it for the SDK, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*. 

We recommend that new users who are developing locally and are not given a method of authentication by their employer to set up AWS IAM Identity Center. This method includes installing the AWS CLI for ease of configuration and for regularly signing in to the AWS access portal. If you choose this method, your environment should contain the following elements after you complete the procedure for [IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) in the *AWS SDKs and Tools Reference Guide*:
+ The AWS CLI, which you use to start an AWS access portal session before you run your application.
+ A [shared AWS`config` file](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) having a `[default]` profile with a set of configuration values that can be referenced from the SDK. To find the location of this file, see [Location of the shared files](https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html) in the *AWS SDKs and Tools Reference Guide*.
+  The shared `config` file sets the [https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) setting. This sets the default AWS Region that the SDK uses for AWS requests. This Region is used for SDK service requests that aren't specified with a Region to use. 
+  The SDK uses the profile's [SSO token provider configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#feature-sso-credentials-profile) to acquire credentials before sending requests to AWS. The `sso_role_name` value, which is an IAM role connected to an IAM Identity Center permission set, allows access to the AWS services used in your application.

  The following sample `config` file shows a default profile set up with SSO token provider configuration. The profile's `sso_session` setting refers to the named [`sso-session` section](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#section-session). The `sso-session` section contains settings to initiate an AWS access portal session.

  ```
  [default]
  sso_session = my-sso
  sso_account_id = 111122223333
  sso_role_name = SampleRole
  region = us-east-1
  output = json
  
  [sso-session my-sso]
  sso_region = us-east-1
  sso_start_url = https://provided-domain.awsapps.com/start
  sso_registration_scopes = sso:account:access
  ```

The AWS SDK for JavaScript v3 does not need additional packages (such as `SSO` and `SSOOIDC`) to be added to your application to use IAM Identity Center authentication.

For details on using this credential provider explicitly, see [https://www.npmjs.com/package/@aws-sdk/credential-providers#fromsso](https://www.npmjs.com/package/@aws-sdk/credential-providers#fromsso) on the npm (Node.js package manager) website.

## Start an AWS access portal session
<a name="accessportal"></a>

Before running an application that accesses AWS services, you need an active AWS access portal session for the SDK to use IAM Identity Center authentication to resolve credentials. Depending on your configured session lengths, your access will eventually expire and the SDK will encounter an authentication error. To sign in to the AWS access portal, run the following command in the AWS CLI.

```
aws sso login
```

If you followed the guidance and have a default profile setup, you do not need to call the command with a `--profile` option. If your SSO token provider configuration is using a named profile, the command is `aws sso login --profile named-profile`.

To optionally test if you already have an active session, run the following AWS CLI command.

```
aws sts get-caller-identity
```

If your session is active, the response to this command reports the IAM Identity Center account and permission set configured in the shared `config` file.

**Note**  
If you already have an active AWS access portal session and run `aws sso login`, you will not be required to provide credentials.   
The sign-in process might prompt you to allow the AWS CLI access to your data. Because the AWS CLI is built on top of the SDK for Python, permission messages might contain variations of the `botocore` name.

## Using console login credentials
<a name="use-con-login-creds"></a>

You can use your existing AWS Management Console sign-in credentials for programmatic access to AWS services. After a browser-based authentication flow, AWS generates temporary credentials that work across local development tools like the AWS CLI and AWS SDK for JavaScript. This feature simplifies the process of configuring and managing AWS CLI credentials. To learn how to get started, follow the instructions to [Login for AWS local development using console credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html).

When you run the **aws login** command, you can select from your active console sessions, or sign in through the browser-based authentication flow and this will automatically generate temporary credentials. The AWS SDK for JavaScript automatically refreshes credentials 5 minutes before expiration, with each set of credentials valid for up to 12 hours. For more information see [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromlogincredentials](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromlogincredentials). 

## More authentication information
<a name="credother"></a>

Human users, also known as *human identities*, are the people, administrators, developers, operators, and consumers of your applications. They must have an identity to access your AWS environments and applications. Human users that are members of your organization - that means you, the developer - are known as *workforce identities*. 

Use temporary credentials when accessing AWS. You can use an identity provider for your human users to provide federated access to AWS accounts by assuming roles, which provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center (IAM Identity Center) to manage access to your accounts and permissions within those accounts. For more alternatives, see the following:
+ To learn more about best practices, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.
+ To create short-term AWS credentials, see [Temporary Security Credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the *IAM User Guide*.
+ To learn about other AWS SDK for JavaScript V3 credential providers, see [Standardized credential providers](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

# Get started with Node.js
<a name="getting-started-nodejs"></a>

This guide shows you how to initialize an NPM package, add a service client to your package, and use the JavaScript SDK to call a service action.

## The scenario
<a name="getting-started-nodejs-scenario"></a>

**Create a new NPM package with one main file that does the following:**
+ Creates an Amazon Simple Storage Service bucket
+ Puts an object in the Amazon S3 bucket
+ Reads the object in the Amazon S3 bucket
+ Confirms if the user wants to delete resources

## Prerequisites
<a name="getting-started-nodejs-prerequisites"></a>

Before you can run the example, you must do the following:
+ Configure your SDK authentication. For more information, see [SDK authentication with AWS](getting-your-credentials.md).
+ Install [Node.js](https://nodejs.org/en/download). AWS recommends using the Active LTS version of Node.js for development.

## Step 1: Set up the package structure and installing client packages
<a name="getting-started-nodejs-setup-structure"></a>

To set up the package structure and install the client packages:

1. Create a new folder `nodegetstarted` to contain the package.

1. From the command line, navigate to the new folder.

1. Run the following command to create a default `package.json` file:

   ```
   npm init -y
   ```

1. Run the following command to install the Amazon S3 client package:

   ```
   npm i @aws-sdk/client-s3
   ```

1. Add `"type": "module"` to the `package.json` file. This tells Node.js to use modern ESM syntax. The final `package.json` should look similar to the following:

   ```
   {
     "name": "example-javascriptv3-get-started-node",
     "version": "1.0.0",
     "description": "This guide shows you how to initialize an NPM package, add a service client to your package, and use the JavaScript SDK to call a service action.",
     "main": "index.js",
     "scripts": {
   "test": "vitest run **/*.unit.test.js"
     },
     "author": "Your Name",
     "license": "Apache-2.0",
     "dependencies": {
    "@aws-sdk/client-s3": "^3.420.0"
     },
     "type": "module"
   }
   ```

## Step 2: Add necessary imports and SDK code
<a name="getting-started-with-node-js-add-code"></a>

Add the following code to a file named `index.js` in the `nodegetstarted` folder.

```
// This is used for getting user input.
import { createInterface } from "node:readline/promises";

import {
  S3Client,
  PutObjectCommand,
  CreateBucketCommand,
  DeleteObjectCommand,
  DeleteBucketCommand,
  paginateListObjectsV2,
  GetObjectCommand,
} from "@aws-sdk/client-s3";

export async function main() {
  // A region and credentials can be declared explicitly. For example
  // `new S3Client({ region: 'us-east-1', credentials: {...} })` would
  //initialize the client with those settings. However, the SDK will
  // use your local configuration and credentials if those properties
  // are not defined here.
  const s3Client = new S3Client({});

  // Create an Amazon S3 bucket. The epoch timestamp is appended
  // to the name to make it unique.
  const bucketName = `test-bucket-${Date.now()}`;
  await s3Client.send(
    new CreateBucketCommand({
      Bucket: bucketName,
    }),
  );

  // Put an object into an Amazon S3 bucket.
  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
      Body: "Hello JavaScript SDK!",
    }),
  );

  // Read the object.
  const { Body } = await s3Client.send(
    new GetObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
    }),
  );

  console.log(await Body.transformToString());

  // Confirm resource deletion.
  const prompt = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  const result = await prompt.question("Empty and delete bucket? (y/n) ");
  prompt.close();

  if (result === "y") {
    // Create an async iterator over lists of objects in a bucket.
    const paginator = paginateListObjectsV2(
      { client: s3Client },
      { Bucket: bucketName },
    );
    for await (const page of paginator) {
      const objects = page.Contents;
      if (objects) {
        // For every object in each page, delete it.
        for (const object of objects) {
          await s3Client.send(
            new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }),
          );
        }
      }
    }

    // Once all the objects are gone, the bucket can be deleted.
    await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName }));
  }
}

// Call a function if this file was run directly. This allows the file
// to be runnable without running on import.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```

The example code can be found [here on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/index.js).

## Step 3: Run the example
<a name="getting-started-with-node-js-run"></a>

**Note**  
Remember to sign in\$1 If you are using IAM Identity Center to authenticate, remember to sign in using the AWS CLI `aws sso login` command.

1. Run `node index.js`.

1. Choose whether to empty and delete the bucket.

1. If you don't delete the bucket, be sure to manually empty and delete it later.

# Get started in the browser
<a name="getting-started-browser"></a>

This section walks you through an example that demonstrates how to run version 3 (V3) of the AWS SDK for JavaScript in the browser. 

**Note**  
Running V3 in the browser is slightly different from version 2 (V2). For more information, see [Using browsers in V3](welcome.md#v3_browsers).

For other examples of using (V3) of the AWS SDK for JavaScript, see [SDK for JavaScript (v3) code examples](javascript_code_examples.md).

**This web application example shows you:**
+ How to access AWS services using Amazon Cognito for authentication.
+ How to read a listing of objects in a Amazon Simple Storage Service (Amazon S3) bucket using a AWS Identity and Access Management (IAM) role.

**Note**  
This example does not use AWS IAM Identity Center for authentication.

## The Scenario
<a name="getting-started-browser-scenario"></a>

Amazon S3 is an object storage service that offers industry-leading scalability, data availability, security, and performance. You can use Amazon S3 to store data as objects within containers called buckets. For more information about Amazon S3, see the [Amazon S3 User Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/).

This example shows you how to set up and run a web app that assumes a IAM role to read from a Amazon S3 bucket. The example uses React front-end library and Vite front-end tooling to provide a JavaScript development environment. The web app uses an Amazon Cognito identity pool to provide credentials needed to access AWS services. The included code example demonstrates the basic patterns for loading and using the AWS SDK for JavaScript in web apps.

## Step 1: Create an Amazon Cognito identity pool and IAM role
<a name="getting-started-browser-create-identity-pool"></a>

In this exercise, you create and use an Amazon Cognito identity pool to provide unauthenticated access to your web app for the Amazon S3 service. Creating an identity pool also creates a AWS Identity and Access Management (IAM) role to support unauthenticated guest users. For this example, we will only work with the unauthenticated user role to keep the task focused. You can integrate support for an identity provider and authenticated users later. For more information about adding a Amazon Cognito identity pool, see [Tutorial: Creating an identity pool](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-identity-pool.html) in the *Amazon Cognito Developer Guide*.

**To create an Amazon Cognito identity pool and associated IAM role**

1. Sign in to the AWS Management Console and open the Amazon Cognito console at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/).

1. In the left navigation pane, choose **Identity pools**.

1. Choose **Create identity pool**.

1. In **Configure identity pool trust**, choose **Guest access** for user authentication.

1. In **Configure permissions**, choose **Create a new IAM role** and enter a name (for example, *getStartedRole*) in the **IAM role name**.

1. In **Configure properties**, enter a name (for example, *getStartedPool*) in **Identity pool name**.

1. In **Review and create**, confirm the selections that you made for your new identity pool. Select **Edit** to return to the wizard and change any settings. When you're done, select **Create identity pool**.

1. Note the **Identity pool ID** and the **Region** of the newly created Amazon Cognito identity pool. You need these values to replace *IDENTITY\$1POOL\$1ID* and *REGION* in [Step 4: Set up the browser code](#getting-started-browser-create-html).

After you create your Amazon Cognito identity pool, you're ready to add permissions for Amazon S3 that are needed by your web app.

## Step 2: Add a policy to the created IAM role
<a name="getting-started-browser-iam-role"></a>

To enable access to a Amazon S3 bucket in your web app, use the unauthenticated IAM role (for example, *getStartedRole*) created for your Amazon Cognito identity pool (for example, *getStartedPool*). This requires you to attach an IAM policy to the role. For more information about modifying IAM roles, see [Modifying a role permissions policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_permissions-policy) in the *IAM User Guide*.

**To add an Amazon S3 policy to the IAM role associated with unauthenticated users**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the left navigation pane, choose **Roles**.

1. Choose the name of the role that you want to modify (for example, *getStartedRole*), and then choose the **Permissions** tab.

1. Choose **Add permissions** and then choose **Attach policies**.

1. In the **Add permissions** page for this role, find and then select the check box for **AmazonS3ReadOnlyAccess**.
**Note**  
You can use this process to enable access to any AWS service.

1. Choose **Add permissions**.

After you create your Amazon Cognito identity pool and add permissions for Amazon S3 to your IAM role for unauthenticated users, you are ready to add and configure a Amazon S3 bucket.

## Step 3: Add a Amazon S3 bucket and object
<a name="getting-started-browser-create-s3-bucket"></a>

In this step, you will add a Amazon S3 bucket and object for the example. You will also enable cross-origin resource sharing (CORS) for the bucket. For more information about creating Amazon S3 buckets and objects, see [Getting started with Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html) in the *Amazon S3 User Guide*.

**To add an Amazon S3 bucket and object with CORS**

1. Sign in to the AWS Management Console and open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/).

1. In the left navigation pane, choose **Buckets** and choose **Create bucket**.

1. Enter a bucket name that conforms to [bucket naming rules](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) (for example, *getstartedbucket*) and choose **Create bucket**.

1. Choose the bucket you created, and then choose the **Objects** tab. Then choose **Upload**.

1. Under **Files and folders**, choose **Add files**.

1. Choose a file to upload, and then choose **Open**. Then choose **Upload** to complete uploading the object to your bucket.

1. Next, choose the **Permissions** tab of your bucket, and then choose **Edit** in the **Cross-origin resource sharing (CORS)** section. Enter the following JSON:

   ```
   [
     {
       "AllowedHeaders": [
         "*"
       ],
       "AllowedMethods": [
         "GET"
       ],
       "AllowedOrigins": [
         "*"
       ],
       "ExposeHeaders": []
     }
   ]
   ```

1. Choose **Save changes**.

After you have added a Amazon S3 bucket and added an object, you're ready to set up the browser code.

## Step 4: Set up the browser code
<a name="getting-started-browser-create-html"></a>

The example application consists of a single-page React application. The files for this example can be found [here on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/web/s3/list-objects).

**To set up the example application**

1. Install [Node.js](https://nodejs.org/en/download).

1. From the command line, clone the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/):

   ```
   git clone --depth 1 https://github.com/awsdocs/aws-doc-sdk-examples.git
   ```

1. Navigate to the example application:

   ```
   cd aws-doc-sdk-examples/javascriptv3/example_code/web/s3/list-objects/
   ```

1. Run the following command to install the required packages:

   ```
   npm install
   ```

1. Next, open `src/App.tsx` in a text editor and complete the following:
   + Replace *YOUR\$1IDENTITY\$1POOL\$1ID* with the Amazon Cognito identity pool ID you noted in [Step 1: Create an Amazon Cognito identity pool and IAM role](#getting-started-browser-create-identity-pool).
   + Replace the value for region to the region assigned for your Amazon S3 bucket and Amazon Cognito identity pool. Note that the regions for both service must be the same (for example, *us-east-2*).
   + Replace *bucket-name* with bucket name you created in [Step 3: Add a Amazon S3 bucket and object](#getting-started-browser-create-s3-bucket).

After you have replaced the text, save the `App.tsx` file. You're now ready to run the web app.

## Step 5: Run the Example
<a name="getting-started-browser-run-sample"></a>

**To run the example application**

1. From the command line, navigate to the example application:

   ```
   cd aws-doc-sdk-examples/javascriptv3/example_code/web/s3/list-objects/
   ```

1. From the command line, run the following command:

   ```
   npm run dev
   ```

   The Vite development environment will run with the following message:

   ```
   VITE v4.3.9  ready in 280 ms
   
   ➜  Local:   http://localhost:5173/
   ➜  Network: use --host to expose
   ➜  press h to show help
   ```

1. In your web browser, navigate to the URL shown above (for example, http://localhost:5173). The example app will show you a list of object filenames in your Amazon S3 bucket.

## Cleanup
<a name="getting-started-browser-cleanup"></a>

To clean up the resources you created during this tutorial, do the following:
+ In [the Amazon S3 console](https://console.aws.amazon.com/s3/), delete any objects and any buckets created (for example, *getstartedbucket*).
+ In [the IAM console](https://console.aws.amazon.com/iam/home#/roles), delete the role name (for example, *getStartedRole*).
+ In [the Amazon Cognito console](https://console.aws.amazon.com/cognito/home#/identity), delete the identity pool name (for example, *getStartedPool*).

# Getting started in React Native
<a name="getting-started-react-native"></a>

This tutorial shows you how you can create a React Native app using [React Native CLI](https://reactnative.dev/docs/environment-setup). 

![\[JavaScript code example that applies to React Native.\]](http://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/images/browsericon.png)

**This tutorial shows you:**
+ How to install and include the AWS SDK for JavaScript version 3 (V3) modules that your project uses.
+ How to write code that connects to Amazon Simple Storage Service (Amazon S3) to create and delete an Amazon S3 bucket.

## The Scenario
<a name="getting-started-react-scenario"></a>

Amazon S3 is a cloud service that enables you to store and retrieve any amount of data at any time, from anywhere on the web. React Native is a development framework that enables you to create mobile applications. This tutorial shows you how you can create a React Native app that connects to Amazon S3 to create and delete an Amazon S3 bucket.

The app uses the following AWS SDK for JavaScript APIs:
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity/) constructor
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/) constructor

## Prerequisite tasks
<a name="getting-started-react-setup"></a>

**Note**  
If you've already completed any of the following steps through other tutorials or existing configuration, skip those steps.

This section provides the minimal setup needed to complete this tutorial. You shouldn't consider this to be a full setup. For that, see [Set up the SDK for JavaScript](setting-up.md).
+ Install the following tools:
  + [npm](https://docs.npmjs.com/getting-started/)
  + [Node.js](https://nodejs.org/en/download/)
  + [Xcode](https://developer.apple.com/xcode/) if you're testing on iOS
  + [Android Studio](https://developer.android.com/studio/) if you're testing on Android
+ Set up your [React Native development environment](https://reactnative.dev/docs/environment-setup)
+ Set up the project environment to run these Node TypeScript examples, and install the required AWS SDK for JavaScript and third-party modules. Follow the instructions on[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/README.md).
+ You must establish how your code authenticates with AWS when developing with AWS services. For more information, see [SDK authentication with AWS](getting-your-credentials.md).
**Note**  
The IAM role for this example should be set to use **AmazonS3FullAccess** permissions.

## Step 1: Create an Amazon Cognito Identity Pool
<a name="getting-started-react-create-identity-pool"></a>

In this exercise, you create and use an Amazon Cognito Identity pool to provide unauthenticated access to your app for the Amazon S3 service. Creating an identity pool also creates two AWS Identity and Access Management (IAM) roles, one to support users authenticated by an identity provider and the other to support unauthenticated guest users.

In this exercise, we will only work with the unauthenticated user role to keep the task focused. You can integrate support for an identity provider and authenticated users later.

**To create an Amazon Cognito Identity pool**

1. Sign in to the AWS Management Console and open the Amazon Cognito console at [Amazon Web Services Console](https://console.aws.amazon.com/cognito/).

1. Choose **Identity Pools** on the console opening page.

1. On the next page, choose **Create new identity pool**.
**Note**  
If there are no other identity pools, the Amazon Cognito console will skip this page and open the next page instead.

1. In **Configure identity pool trust**, choose **Guest access** for user authentication.

1. In **Configure permissions**, choose **Create a new IAM role** and enter a name (for example, *getStartedReactRole*) in the **IAM role name**.

1. In **Configure properties**, enter a name (for example, *getStartedReactPool*) in **Identity pool name**.

1. In **Review and create**, confirm the selections that you made for your new identity pool. Select **Edit** to return to the wizard and change any settings. When you're done, select **Create identity pool**.

1. Note the identity pool ID and the Region for this newly created identity pool. You need these values to replace *region* and *identityPoolId* in your browser script.

After you create your Amazon Cognito identity pool, you're ready to add permissions for Amazon S3 that are needed by your React Native app.

## Step 2: Add a Policy to the Created IAM Role
<a name="getting-started-react-iam-role"></a>

To enable browser script access to Amazon S3 to create and delete an Amazon S3 bucket, use the unauthenticated IAM role created for your Amazon Cognito identity pool. This requires you to add an IAM policy to the role. For more information about IAM roles, see [Creating a Role to Delegate Permissions to an AWS Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*.

**To add an Amazon S3 policy to the IAM role associated with unauthenticated users**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the left navigation pane, choose **Roles**.

1. Choose the name of the role that you want to modify (for example, *getStartedRole*), and then choose the **Permissions** tab.

1. Choose **Add permissions** and then choose **Attach policies**.

1. In the **Add permissions** page for this role, find and then select the check box for **AmazonS3ReadOnlyAccess**.
**Note**  
You can use this process to enable access to any AWS service.

1. Choose **Add permissions**.

After you create your Amazon Cognito identity pool and add permissions for Amazon S3 to your IAM role for unauthenticated users, you are ready to build the app.

## Step 3: Create app using create-react-native-app
<a name="react-prerequisites"></a>

Create a React Native App by running the following command.

```
npx react-native init ReactNativeApp --npm
```

## Step 4: Install the Amazon S3 package and other dependencies
<a name="getting-started-react-install-dependencies"></a>

Inside the directory of the project, run the following commands to install the Amazon S3 package.

```
npm install @aws-sdk/client-s3
```

This command installs the Amazon S3 package in your project, and updates `package.json` to list Amazon S3 as a project dependency. You can find information about this package by searching for "@aws-sdk" on the [https://www.npmjs.com/](https://www.npmjs.com/)npm website.

These packages and their associated code are installed in the `node_modules` subdirectory of your project.

For more information about installing Node.js packages, see [Downloading and installing packages locally](https://docs.npmjs.com/downloading-and-installing-packages-locally) and [Creating Node.js modules](https://docs.npmjs.com/creating-node-js-modules) on the [npm (Node.js package manager) website](https://www.npmjs.com/). For information about downloading and installing the AWS SDK for JavaScript, see [Install the SDK for JavaScript](setting-up.md#installing-jssdk).

Install other dependencies required for authentication.

```
npm install @aws-sdk/client-cognito-identity @aws-sdk/credential-provider-cognito-identity
```

## Step 5: Write the React Native code
<a name="getting-started-react-write-native-code"></a>

Add the following code to the `App.tsx`. Replace *identityPoolId* and *region* with the identity pool ID and Region where your Amazon S3 bucket will be created.

```
import React, { useCallback, useState } from "react";
import { Button, StyleSheet, Text, TextInput, View } from "react-native";
import "react-native-get-random-values";
import "react-native-url-polyfill/auto";

import {
  S3Client,
  CreateBucketCommand,
  DeleteBucketCommand,
} from "@aws-sdk/client-s3";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const client = new S3Client({
  // The AWS Region where the Amazon Simple Storage Service (Amazon S3) bucket will be created. Replace this with your Region.
  region: "us-east-1",
  credentials: fromCognitoIdentityPool({
    // Replace the value of 'identityPoolId' with the ID of an Amazon Cognito identity pool in your Amazon Cognito Region.
    identityPoolId: "us-east-1:edbe2c04-7f5d-469b-85e5-98096bd75492",
    // Replace the value of 'region' with your Amazon Cognito Region.
    clientConfig: { region: "us-east-1" },
  }),
});

enum MessageType {
  SUCCESS = 0,
  FAILURE = 1,
  EMPTY = 2,
}

const App = () => {
  const [bucketName, setBucketName] = useState("");
  const [msg, setMsg] = useState<{ message: string; type: MessageType }>({
    message: "",
    type: MessageType.EMPTY,
  });

  const createBucket = useCallback(async () => {
    setMsg({ message: "", type: MessageType.EMPTY });

    try {
      await client.send(new CreateBucketCommand({ Bucket: bucketName }));
      setMsg({
        message: `Bucket "${bucketName}" created.`,
        type: MessageType.SUCCESS,
      });
    } catch (e) {
      console.error(e);
      setMsg({
        message: e instanceof Error ? e.message : "Unknown error",
        type: MessageType.FAILURE,
      });
    }
  }, [bucketName]);

  const deleteBucket = useCallback(async () => {
    setMsg({ message: "", type: MessageType.EMPTY });

    try {
      await client.send(new DeleteBucketCommand({ Bucket: bucketName }));
      setMsg({
        message: `Bucket "${bucketName}" deleted.`,
        type: MessageType.SUCCESS,
      });
    } catch (e) {
      setMsg({
        message: e instanceof Error ? e.message : "Unknown error",
        type: MessageType.FAILURE,
      });
    }
  }, [bucketName]);

  return (
    <View style={styles.container}>
      {msg.type !== MessageType.EMPTY && (
        <Text
          style={
            msg.type === MessageType.SUCCESS
              ? styles.successText
              : styles.failureText
          }
        >
          {msg.message}
        </Text>
      )}
      <View>
        <TextInput
          onChangeText={(text) => setBucketName(text)}
          autoCapitalize={"none"}
          value={bucketName}
          placeholder={"Enter Bucket Name"}
        />
        <Button color="#68a0cf" title="Create Bucket" onPress={createBucket} />
        <Button color="#68a0cf" title="Delete Bucket" onPress={deleteBucket} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  successText: {
    color: "green",
  },
  failureText: {
    color: "red",
  },
});

export default App;
```

The code first imports required React, React Native, and AWS SDK dependencies.

Inside the function App:
+ The S3Client object is created, specifying the credentials using Amazon Cognito Identity Pool created earlier.
+ The methods `createBucket` and `deleteBucket` create and delete the specified bucket, respectively.
+ The React Native View displays a text input field for the user to specify an Amazon S3 bucket name, and buttons to create and delete the specified Amazon S3 bucket.

The full JavaScript page is available [here on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/reactnative/ReactNativeApp/App.tsx).

## Step 6: Run the Example
<a name="getting-started-react-native-run-sample"></a>

**Note**  
Remember to sign in\$1 If you are using IAM Identity Center to authenticate, remember to sign in using the AWS CLI `aws sso login` command.

To run the example, run `web`, `ios`, or `android` command using npm.

Here is an example output of running `ios` command on macOS.

```
$ npm run ios

> ReactNativeApp@0.0.1 ios /Users/trivikr/workspace/ReactNativeApp
> react-native run-ios

info Found Xcode workspace "ReactNativeApp.xcworkspace"
info Launching iPhone 11 (iOS 14.2)
info Building (using "xcodebuild -workspace ReactNativeApp.xcworkspace -configuration Debug -scheme ReactNativeApp -destination id=706C1A97-FA38-407D-AD77-CB4FCA9134E9")
success Successfully built the app
info Installing "/Users/trivikr/Library/Developer/Xcode/DerivedData/ReactNativeApp-cfhmsyhptwflqqejyspdqgjestra/Build/Products/Debug-iphonesimulator/ReactNativeApp.app"
info Launching "org.reactjs.native.example.ReactNativeApp"

success Successfully launched the app on the simulator
```

Here is an example output of running `android` command on macOS.

```
$ npm run android

> ReactNativeApp@0.0.1 android
> react-native run-android

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 970 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug
02:18:38 V/ddms: execute: running am get-config
02:18:38 V/ddms: execute 'am get-config' on 'emulator-5554' : EOF hit. Read: -1
02:18:38 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Pixel_3a_API_30_x86(AVD) - 11' for app:debug
02:18:38 D/app-debug.apk: Uploading app-debug.apk onto device 'emulator-5554'
02:18:38 D/Device: Uploading file onto device 'emulator-5554'
02:18:38 D/ddms: Reading file permission of /Users/trivikr/workspace/ReactNativeApp/android/app/build/outputs/apk/debug/app-debug.apk as: rw-r--r--
02:18:40 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
02:18:41 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
02:18:41 V/ddms: execute: returning
02:18:41 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
02:18:41 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
02:18:41 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 6s
27 actionable tasks: 2 executed, 25 up-to-date
info Connecting to the development server...
8081
info Starting the app on "emulator-5554"...
Starting: Intent { cmp=com.reactnativeapp/.MainActivity }
```

Enter the bucket name you want to create or delete and click on either **Create Bucket** or **Delete Bucket**. The respective command will be sent to Amazon S3, and success or error message will be displayed.

![\[Bucket creation success message with options to create or delete a bucket.\]](http://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/images/react-app-running.png)


## Possible Enhancements
<a name="getting-started-react-native-variations"></a>

Here are variations on this application you can use to further explore using the AWS SDK for JavaScript in a React Native app.
+ Add a button to list Amazon S3 buckets, and provide a delete button next to each bucket listed.
+ Add a button to put text object into a bucket.
+ Integrate an external identity provider like Facebook or Amazon to use with the authenticated IAM role.