Storage with Amplify

After you have successfully created an account with Cognito User Pool, we will use that account to upload files to the S3 bucket with Amplify in this section.

  1. Keep both terminals running npx ampx sandbox and npm run dev.

  2. Create a storage folder in the amplify folder, then create the amplify/storage/resource.ts file with the content below to add storage to the application:

import { defineStorage } from '@aws-amplify/backend';

export const storage = defineStorage({
  name: 'fcajdmsstore',
  access: (allow) => ({
    'protected/{entity_id}/*': [
      allow.authenticated.to(['read']),
      allow.entity('identity').to(['read', 'write', 'delete']),
    ],
  }),
});

CreateStorage

  • name: the friendly name of the storage, used to name the S3 bucket.

  • protected/{entity_id}/*: the folder that stores the user’s files. When a file is uploaded, {entity_id} is replaced with the user’s Identity ID in the Cognito Identity Pool.

  • allow.authenticated.to(['read']): every signed-in user can read the files.

  • allow.entity('identity').to(['read', 'write', 'delete']): only the owner of the folder can write and delete files.

  • Open the amplify/backend.ts file and add storage to the backend:

import { defineBackend } from '@aws-amplify/backend';
import { auth } from './auth/resource';
import { storage } from './storage/resource';

defineBackend({
  auth,
  storage,
});

CreateStorage

  1. Save the files. The sandbox automatically redeploys the backend to create the S3 bucket.
  • Wait until the sandbox terminal shows Deployment completed and File written: amplify_outputs.json.
  • The amplify_outputs.json file is updated with a storage section that contains the bucket name and the access permissions.

CreateStorage

  1. Go back to the CloudFormation console to check if the storage nested stack has been created.
  • Open the storage nested stack, select the Resources tab, then click the Physical ID of AWS::S3::Bucket to open the console of that bucket. The bucket name looks like amplify-fcajdms-…-fcajdmsstore…

CreateStorage

  1. Go back to the application at http://localhost:3000. The web page automatically reloads when the amplify_outputs.json file changes.
  • Click Upload

UploadFile

  1. Click Add files and select the files you want to upload. Add tags to the files or skip this step. Then click Upload

UploadFile

  1. Go back to the S3 bucket console and check if the files have been uploaded.

UploadFile

You have completed user authentication and file upload to S3 with Amplify. The files are stored in the protected/{Identity ID}/ folder because the storage is declared with the protected/{entity_id}/* path. To learn more about access control, move on to the next section.