

# Amazon S3

Amazon Simple Storage Service (Amazon S3) is an object storage service that stores files, images, and other assets at any scale. Use an Amazon S3 integration to let your app read and write objects in a bucket without managing credentials.

## Environment variables for Amazon S3
<a name="integrations-s3-env-vars"></a>

When you connect an Amazon S3 integration, Amplify sets the following environment variables.


| Variable | Value | 
| --- | --- | 
|  `BUCKET_NAME`  | The name of the bucket | 
|  `BUCKET_REGION`  | The AWS Region that the bucket is in | 

## Permissions for Amazon S3
<a name="integrations-s3-permissions"></a>

The integration grants your app `s3:GetObject`, `s3:PutObject`, `s3:DeleteObject`, and `s3:ListBucket` on the bucket and the objects in it.

## Create an Amazon S3 integration
<a name="integrations-s3-create"></a>

Use an existing bucket in the same AWS account as your app. You can’t change the bucket after you create the integration.

### Create an Amazon S3 integration in the console
<a name="_create_an_amazon_s3_integration_in_the_console"></a>

To create an Amazon S3 integration in the console:

1. Sign in to the Amplify console at https://us-east-2.console.aws.amazon.com/amplifygen3/home.

1. For **Integrations**, choose **Add**.

1. For **Select integration**, select **Amazon S3**, and then choose **Add**.

1. For **Integration name**, enter a unique integration name.

1. For **Bucket**, enter the name or the Amazon Resource Name (ARN) of your bucket.

1. (Optional) Choose **Connect to app**, select your app, and then choose the environments to connect the integration to.

1. Choose **Add**.

### Create an Amazon S3 integration using the CLI
<a name="_create_an_amazon_s3_integration_using_the_cli"></a>

The following AWS CLI command creates an Amazon S3 integration for an existing bucket and connects it to the `preview` environment. Replace `my-storage` with a name for the integration and `amzn-s3-demo-bucket` with the name of your bucket.

```bash
aws amplifygen3 integration connect s3 --name my-storage --id amzn-s3-demo-bucket --env preview
```

To identify the bucket by its ARN instead of its name, use `--arn arn:aws:s3:::amzn-s3-demo-bucket`.

## Use Amazon S3 in your code
<a name="integrations-s3-code"></a>

The following TypeScript example uses the AWS SDK for JavaScript to upload an object to the bucket.

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

```typescript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({ region: process.env.BUCKET_REGION });

await s3.send(
  new PutObjectCommand({
    Bucket: process.env.BUCKET_NAME,
    Key: "uploads/hello.txt",
    Body: "Hello from Amplify",
  }),
);
```

Integration variables are available to the build and to server-side code, such as API routes and server components. A variable reaches browser code only if its name has your framework’s public prefix, such as `NEXT_PUBLIC_`. To run your app locally against the same bucket, download the environment’s variables with `aws amplifygen3 var download .env.local --env preview`. Your local AWS credentials must be allowed to access the bucket.

## How to perform user access control with the backend
<a name="integrations-s3-access-control"></a>

The integration gives your app’s server code access to every object in the bucket. To let each signed-in user access only their own files, record each file in a `files` table in the Amplify backend database, and write row-level security (RLS) policies that check the file’s `owner_id`. Your server code queries the file’s row as the user who sent the request, and presigns the S3 request only if the query succeeds.

In the following migration, each row records one file. The database generates `id` with `gen_random_uuid()`, and `owner_id` defaults to `auth.uid()`. Use `<owner_id>/<id>` as the object key.

The migration turns on RLS and adds owner policies for select, insert and delete. It grants those operations to `authenticated`, so each user can read, add and delete only their own rows. For more information about grants and policies, see [Secure your data](backend-rls.md).

Add the following migration, and deploy to apply it:

```sql
create table public.files (
  id           uuid primary key default gen_random_uuid(),
  owner_id     text not null default auth.uid(),
  name         text not null,
  content_type text not null,
  created_at   timestamptz not null default now()
);
create index files_owner_id_idx on public.files (owner_id);
alter table public.files enable row level security;

create policy "owner_select" on public.files for select to authenticated
  using ((select auth.uid()) = owner_id);
create policy "owner_insert" on public.files for insert to authenticated
  with check ((select auth.uid()) = owner_id);
create policy "owner_delete" on public.files for delete to authenticated
  using ((select auth.uid()) = owner_id);

grant select, insert, delete on public.files to authenticated;
```

The following Next.js route handler checks the user’s permission before it allows an upload. The request sends the signed-in user’s token as `Authorization: Bearer <token>`. The route creates a backend client that acts as that user, and inserts the file’s row. PostgreSQL applies the `owner_insert` policy to the insert.

If the insert succeeds, the route returns a presigned URL that the browser uses to upload the file to S3. If the insert fails, the route returns an error and doesn’t presign the request.

Install the backend client SDK and the AWS SDK for JavaScript packages:

```bash
npm install @aws-amplifygen3/backend-client-js @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
```

Add the route handler:

```typescript
// app/api/files/route.ts
import { createClient } from '@aws-amplifygen3/backend-client-js'
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'

const s3 = new S3Client({ region: process.env.BUCKET_REGION })
const bucket = process.env.BUCKET_NAME!

export async function POST(request: Request) {
  // Check the user's access permission with the backend.
  const header = request.headers.get('authorization') ?? ''
  const token = header.startsWith('Bearer ') ? header.slice(7) : ''
  if (!token) return Response.json({ error: 'Sign in first' }, { status: 401 })

  const backend = createClient(process.env.AMPLIFY_BACKEND_URL!, process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY!, {
    webTokenProvider: () => token,
  })

  const { name, contentType } = await request.json()
  const { data: file, error } = await backend
    .from('files').insert({ name, content_type: contentType }).select().single()
  if (error) return Response.json({ error: error.message }, { status: error.code === 'invalid_credential' ? 401 : 403 })

  // The user has access, so return a presigned URL for the upload to S3.
  const uploadUrl = await getSignedUrl(s3,
    new PutObjectCommand({ Bucket: bucket, Key: `${file.owner_id}/${file.id}`, ContentType: contentType }),
    { expiresIn: 300 })
  return Response.json({ id: file.id, uploadUrl })
}
```

## Delete an Amazon S3 integration
<a name="integrations-s3-delete"></a>

Before you delete an integration, disconnect it from every environment, and then redeploy those environments so that they stop using it. Deleting an integration doesn’t delete the bucket or its objects, which continue to incur storage charges. To avoid ongoing charges, empty and delete the bucket separately if you no longer need it. For more information, see [Deleting a general purpose bucket](AmazonS3/latest/userguide/delete-bucket.html).

### Delete an Amazon S3 integration in the console
<a name="_delete_an_amazon_s3_integration_in_the_console"></a>

To delete an Amazon S3 integration in the console:

1. Sign in to the Amplify console at https://us-east-2.console.aws.amazon.com/amplifygen3/home.

1. For **Integrations**, choose your Amazon S3 integration.

1. Choose **Delete**.

1. Confirm your choice and choose **Delete**.

### Delete an Amazon S3 integration using the CLI
<a name="_delete_an_amazon_s3_integration_using_the_cli"></a>

The following AWS CLI commands disconnect the integration from the `preview` environment and then delete it.

```bash
aws amplifygen3 integration disconnect --name my-storage --env preview
aws amplifygen3 integration delete --name my-storage
```

The `delete` command asks for confirmation. In a non-interactive session such as CI, add `--yes`.