How to setup Nuxt.js and AWS Amplify on AWS Cloud9.

How to setup Nuxt.js and AWS Amplify on AWS Cloud9.
AWS Cloud9でNuxt.js とAWS Amplifyをセットアップする方法についての記事です。

# 前提条件

* AWSアカウント有り

# セットアップ内容

* node(npm)
* yarn
* Nuxt.js(create-nuxt-appを利用）
* Amplify CLI

# 流れ

1. AWS Cloud9起動
2. nodeインストール
3. yarnインストール
4. create-nuxt-app実行
5. 起動確認
6. AWS Amplify CLIインストール
7. 認証追加
8. 起動確認
9. デプロイ
10. 環境の削除

---
# 1. AWS Cloud9起動

起動画面
![スクリーンショット 2021-08-18 6.08.37.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/ed0fb9ab-7ee3-77b3-a26a-a37ff8996717.png)

環境名を入力して次へ
![スクリーンショット 2021-08-18 6.12.47.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/3f239a7f-e53b-3942-de22-99fdb98ae093.png)


Create environment 選択
![スクリーンショット 2021-08-18 6.10.01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/3c1a2a6c-01ed-ea11-bdb7-2464a543c6f6.png)

Configure settings
インスタンスタイプにt2.smallを選択。
![スクリーンショット 2021-08-18 22.08.46.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/431b9d42-7c6a-0b8f-e289-c6db0f5b30a6.png)


確認画面で Create environment選択
![スクリーンショット 2021-08-18 22.09.09.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/dac0126e-da31-ff01-5478-f9a678cae105.png)
![スクリーンショット 2021-08-18 6.29.19.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/9efda05e-7ea7-6cc0-9dc6-b73f7c79cdc6.png)

Cloud9の環境が起動します。
![スクリーンショット 2021-08-18 6.32.16.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/022f5b18-c528-dbd5-8787-5e71af400a08.png)

![スクリーンショット 2021-08-18 6.38.43.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/0b1f65d4-fc0a-2865-b1d2-bf99e2a1a016.png)


# 2. nodeインストール

下記手順参照

Node.js サンプルAWS Cloud9
https://docs.aws.amazon.com/ja_jp/cloud9/latest/user-guide/sample-nodejs.html

nvm
https://github.com/nvm-sh/nvm


## コマンド

ターミナル画面にて下記のコマンドを入力

`$ nvm install --lts`

`$ sudo yum -y update`

`$ nvm alias default node`


```
admin-user:~/environment $ node -v
v10.24.1
admin-user:~/environment $ npm -v
6.14.12
$ nvm install --lts
Installing latest LTS version.
Downloading https://nodejs.org/dist/v14.17.5/node-v14.17.5-linux-x64.tar.xz...
######################################################################################################################################### 100.0%
Now using node v14.17.5 (npm v6.14.14)
nvm_ensure_default_set: a version is required
admin-user:~/environment $ node -v
v14.17.5
admin-user:~/environment $ sudo yum -y update
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                                               | 3.7 kB  00:00:00     
242 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package ec2-utils.noarch 0:1.2-44.amzn2 will be updated
---> Package ec2-utils.noarch 0:1.2-45.amzn2 will be an update
---> Package emacs-filesystem.noarch 1:27.1-1.amzn2.0.1 will be updated
---> Package emacs-filesystem.noarch 1:27.2-4.amzn2.0.1 will be an update
（省略）
Replaced:
  grub2.x86_64 1:2.06-2.amzn2.0.1                                     grub2-tools.x86_64 1:2.06-2.amzn2.0.1                                    

Complete!
admin-user:~/environment $ nvm alias default node
admin-user:~/environment $ node -v
v14.17.5
```

# 3. yarnインストール

下記参照。
https://yarnpkg.com/getting-started/install

# コマンド

ターミナル画面で下記のコマンドを入力

`$ npm install -g yarn`


```
$ npm install -g yarn

> yarn@1.22.11 preinstall /home/ec2-user/.nvm/versions/node/v14.17.5/lib/node_modules/yarn
> :; (node ./preinstall.js > /dev/null 2>&1 || true)

/home/ec2-user/.nvm/versions/node/v14.17.5/bin/yarn -> /home/ec2-user/.nvm/versions/node/v14.17.5/lib/node_modules/yarn/bin/yarn.js
/home/ec2-user/.nvm/versions/node/v14.17.5/bin/yarnpkg -> /home/ec2-user/.nvm/versions/node/v14.17.5/lib/node_modules/yarn/bin/yarn.js
+ yarn@1.22.11
added 1 package in 0.721s
admin-user:~/environment $ yarn --version
1.22.11
```

# 4. create-nuxt-app実行

Nuxt.js日本語マニュアルを参照
https://ja.nuxtjs.org/docs/2.x/get-started/installation

## コマンド

ターミナル画面で下記コマンドを入力

`yarn create nuxt-app note`
`note`の部分はお好きなプロジェクト名を入力。

`cd note`


質問には下記の通り回答

```
✨  Generating Nuxt.js project in note
? Project name: note
? Programming language: JavaScript
? Package manager: Yarn
? UI framework: Vuetify.js
? Nuxt.js modules: Axios - Promise based HTTP client, Progressive Web App (PWA)
? Linting tools: ESLint
? Testing framework: None
? Rendering mode: Single Page App
? Deployment target: Server (Node.js hosting)
? Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
? Continuous integration: None
? Version control system: Git
```


```
yarn create v1.22.11
[1/4] Resolving packages...
warning create-nuxt-app > sao > micromatch > snapdragon > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
warning create-nuxt-app > sao > micromatch > snapdragon > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "create-nuxt-app@3.7.1" with binaries:
      - create-nuxt-app

create-nuxt-app v3.7.1
✨  Generating Nuxt.js project in note
? Project name: note
? Programming language: JavaScript
? Package manager: Yarn
? UI framework: Vuetify.js
? Nuxt.js modules: Axios - Promise based HTTP client, Progressive Web App (PWA)
? Linting tools: ESLint
? Testing framework: None
? Rendering mode: Single Page App
? Deployment target: Server (Node.js hosting)
? Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
? Continuous integration: None
? Version control system: Git
warning nuxt > @nuxt/babel-preset-app > core-js@2.6.12: core-js@<3.3 is no longer maintained and not recommended for usage due to the number of 
issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfille
d. Please, upgrade your dependencies to the actual version of core-js.
warning nuxt > @nuxt/webpack > webpack-hot-middleware > querystring@0.2.1: The querystring API is considered Legacy. new code should use the URL
SearchParams API instead.
warning nuxt > @nuxt/webpack > webpack > node-libs-browser > url > querystring@0.2.0: The querystring API is considered Legacy. new code should 
use the URLSearchParams API instead.
warning nuxt > @nuxt/webpack > webpack > watchpa
（省略）
yarn run v1.22.11
$ eslint --ext ".js,.vue" --ignore-path .gitignore . --fix
Done in 3.42s.

🎉  Successfully created project note

  To get started:

        cd note
        yarn dev

  To build & start for production:

        cd note
        yarn build
        yarn start

Done in 160.84s.
```


# 5. 起動確認

※以降の作業は`create-nuxt-app`で作成したプロジェクトフォルダにcdして行います。

## コマンド

`$ yarn dev`

```
admin-user:~/environment/note (master) $ yarn dev
yarn run v1.22.11
$ nuxt

ℹ NuxtJS collects completely anonymous data about usage.                                                                              22:47:44
  This will help us improve Nuxt developer experience over time.
  Read more on https://git.io/nuxt-telemetry

? Are you interested in participating? No


   ╭───────────────────────────────────────╮
   │                                       │
   │   Nuxt @ v2.15.8                      │
   │                                       │
   │   ▸ Environment: development          │
   │   ▸ Rendering:   client-side          │
   │   ▸ Target:      server               │
   │                                       │
   │   Listening: http://localhost:8080/   │
   │                                       │
   ╰───────────────────────────────────────╯

ℹ Preparing project for development                                                                                                   22:48:36
ℹ Initial build may take a while                                                                                                      22:48:37
ℹ Discovered Components: .nuxt/components/readme.md                                                                                   22:48:37
✔ Builder initialized                                                                                                                 22:48:37
✔ Nuxt files generated                                                                                                                22:48:37

✔ Client
  Compiled successfully in 13.29s

ℹ Waiting for file changes                                                                                                            22:48:53
ℹ Memory usage: 193 MB (RSS: 316 MB)                                                                                                  22:48:53
ℹ Listening on: http://localhost:8080/  
```

メニューからPreview→Preview Running Applicationを選択します。

![スクリーンショット 2021-08-18 7.50.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/5770ecc6-0f39-b2e0-7661-558e608fe3fe.png)


# 6. AWS Amplify CLIインストール

下記を参照。
https://docs.amplify.aws/cli/start/install/

## コマンド
 
`npm install -g @aws-amplify/cli`

`$ amplify --version`

```
admin-user:~/environment $ node -v
v14.17.5
admin-user:~/environment $ npm install -g @aws-amplify/cli
npm WARN deprecated graphql-import@0.7.1: GraphQL Import has been deprecated and merged into GraphQL Tools, so it will no longer get updates. Use GraphQL Tools instead to stay up-to-date! Check out https://www.graphql-tools.com/docs/migration-from-import for migration and 
（省略）
> node -e "try{require('./postinstall')}catch(e){}"

admin-user:~/environment $ amplify --help

amplify <command> <subcommand>

  init                Initializes a new project, sets up deployment resources in the cloud, and makes your project ready for Amplify.                              
  configure           Configures the attributes of your project for amplify-cli, such as switching front-end framework and adding/removing cloud-provider plugins. 
  push                Provisions cloud resources with the latest local developments.                                                                               
  pull                Fetch upstream backend environment definition changes from the cloud and updates the local environment to match that definition.             
  publish             Executes amplify push, and then builds and publishes client-side application for hosting.                                                    
  serve               Executes amplify push, and then executes the project's start command to test run the client-side application locally.                        
  status              Shows the state of local resources not yet pushed to the cloud (Create/Update/Delete).                                                       
  delete              Deletes all of the resources tied to the project from the cloud.                                                                             
  <category> add      Adds a resource for an Amplify category in your local backend                                                                                
  <category> update   Update resource for an Amplify category in your local backend.                                                                               
  <category> push     Provisions all cloud resources in a category with the latest local developments.                                                             
  <category> remove   Removes a resource for an Amplify category in your local backend.                                                                            
  <category>          Displays subcommands of the specified Amplify category.                                                                                      
  mock                Run mock server for testing categories locally.                                                                                              
  codegen             Generates GraphQL statements(queries, mutations and eventHandlers) and type annotations.                                                     
  env                 Displays and manages environment related information for your Amplify project.                                                               
  console             Opens the web console for the selected cloud resource.                                                                                       
  logout              If using temporary cloud provider credentials, this logs out of the account.                                                                 

where <category> is one of: notifications, analytics, api, auth, function, hosting, interactions, predictions, storage, xr

admin-user:~/environment $ amplify --version
5.3.0
```

## Amplify 用のIAMユーザー作成

1. `amplify configure`
2. `? region:  ap-northeast-1`
3. `? user name:` デフォルトのままEnter
4. 表示されるURLをブラウザで開く
5. accessKeyIdとsecretAccessKeyをコピー
6. Press Enter to continue　して
7. ? accessKeyId:  ******************** ←貼り付け
8. ? secretAccessKey:  **************************************** ←貼り付け
9. ? Profile Name:  デフォルトEnter


```
admin-user:~/environment $ amplify configure
Follow these steps to set up access to your AWS account:

Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Specify the AWS Region
? region:  ap-northeast-1
Specify the username of the new IAM user:
? user name:  amplify-JGFWB
Complete the user creation using the AWS console

<URL>

Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
This would update/create the AWS Profile in your local machine
? Profile Name:  default

Successfully set up the new user.
admin-user:~/environment $ 
```

## スクリーンショット

![スクリーンショット 2021-08-18 8.27.35.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/4ce110c1-534b-03da-6baa-583f79906739.png)

![スクリーンショット 2021-08-18 8.32.03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/c619703b-4009-7be2-9da9-bab2eefd6332.png)

![スクリーンショット 2021-08-18 8.32.13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/a6b9bc9d-fcc9-4df9-66a4-5b61c5a0556f.png)

![スクリーンショット 2021-08-18 8.33.15.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/59d236eb-d4b3-16fb-e5e0-f103817558db.png)



# 7. 認証追加

## バックエンドの設定

### Amplify 初期化

#### コマンド

`amplify init`


```
admin-user:~/environment/note (master) $ pwd
/home/ec2-user/environment/note
admin-user:~/environment/note (master) $ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project note
The following configuration will be applied:

Project information
| Name: note
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: none
| Source Directory Path: src
| Distribution Directory Path: dist
| Build Command: npm run-script build
| Start Command: npm run-script start

? Initialize the project with the above configuration? Yes
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Please choose the profile you want to use default
Adding backend environment dev to AWS Amplify Console app: d2xswp19w9h576
⠧ Initializing project in the cloud...

CREATE_IN_PROGRESS amplify-note-dev-234626 AWS::CloudFormation::Stack Tue Aug 17 2021 23:46:35 GMT+0000 (Coordinated Universal Time) User Initiated
CREATE_IN_PROGRESS UnauthRole              AWS::IAM::Role             Tue Aug 17 2021 23:46:40 GMT+0000 (Coordinated Universal Time)               
CREATE_IN_PROGRESS AuthRole                AWS::IAM::Role             Tue Aug 17 2021 23:46:40 GMT+0000 (Coordinated Universal Time)               
CREATE_IN_PROGRESS DeploymentBucket        AWS::S3::Bucket            Tue Aug 17 2021 23:46:40 GMT+0000 (Coordinated Universal Time)               
⠏ Initializing project in the cloud...

CREATE_IN_PROGRESS UnauthRole       AWS::IAM::Role  Tue Aug 17 2021 23:46:41 GMT+0000 (Coordinated Universal Time) Resource creation Initiated
CREATE_IN_PROGRESS AuthRole         AWS::IAM::Role  Tue Aug 17 2021 23:46:42 GMT+0000 (Coordinated Universal Time) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Tue Aug 17 2021 23:46:43 GMT+0000 (Coordinated Universal Time) Resource creation Initiated
⠇ Initializing project in the cloud...

CREATE_COMPLETE UnauthRole       AWS::IAM::Role  Tue Aug 17 2021 23:47:03 GMT+0000 (Coordinated Universal Time) 
CREATE_COMPLETE AuthRole         AWS::IAM::Role  Tue Aug 17 2021 23:47:04 GMT+0000 (Coordinated Universal Time) 
CREATE_COMPLETE DeploymentBucket AWS::S3::Bucket Tue Aug 17 2021 23:47:04 GMT+0000 (Coordinated Universal Time) 
⠋ Initializing project in the cloud...

CREATE_COMPLETE amplify-note-dev-234626 AWS::CloudFormation::Stack Tue Aug 17 2021 23:47:07 GMT+0000 (Coordinated Universal Time) 
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add <category>" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

admin-user:~/environment/note (master) $ 
```

![スクリーンショット 2021-08-18 8.49.20.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/25ccede7-cb6e-7191-716f-15c08d5664c7.png)


### 認証機能の追加（amplify add auth）

#### コマンド

ローカルに環境作成
`$ amplify add auth`

デプロイ
`$ amplify push --y`

```
admin-user:~/environment/note (master) $ amplify add auth
Using service: Cognito, provided by: awscloudformation
 
 The current configured provider is Amazon Cognito. 
 
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Email
 Do you want to configure advanced settings? No, I am done.
Successfully added auth resource note7539b6b2 locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

admin-user:~/environment/note (master) $ amplify status

Current Environment: dev

| Category | Resource name | Operation | Provider plugin   |
| -------- | ------------- | --------- | ----------------- |
| Auth     | note7539b6b2  | Create    | awscloudformation |


admin-user:~/environment/note (master) $ amplify push --y
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name | Operation | Provider plugin   |
| -------- | ------------- | --------- | ----------------- |
| Auth     | note7539b6b2  | Create    | awscloudformation |
⠴ Updating resources in the cloud. This may take a few minutes...

UPDATE_IN_PROGRESS amplify-note-dev-234626 AWS::CloudFormation::Stack Tue Aug 17 2021 23:53:54 GMT+0000 (Coordinated Universal Time) User Initiated
⠧ Updating resources in the cloud. This may take a few minutes...
（省略）
UPDATE_COMPLETE                     amplify-note-dev-234626 AWS::CloudFormation::Stack Tue Aug 17 2021 23:56:57 GMT+0000 (Coordinated Universal Time) 
✔ All resources are updated in the cloud
```

## フロントエンド側の設定

### Amplifyモジュールのインストール

 ~~$ npm install aws-amplify~~

:::note info
 Amplifyモジュールもyarnでインストールしてください。
 yarn add aws-amplify
:::



※ディスク容量不足でインストールができない場合は下記を参考にディスク容量を増やしてください。

#### ディスク容量を増やす

下記参照。
https://docs.aws.amazon.com/ja_jp/cloud9/latest/user-guide/move-environment.html

容量不足でインストールができない場合は、下記ファイルをルートディレクトリに作成してコマンドを実行します。

1. `$ touch resize.sh`
2. ファイルを作成
3. `$ bash resize.sh 20`

```bash
#!/bin/bash

# Specify the desired volume size in GiB as a command line argument. If not specified, default to 20 GiB.
SIZE=${1:-20}

# Get the ID of the environment host Amazon EC2 instance.
INSTANCEID=$(curl http://169.254.169.254/latest/meta-data/instance-id)

# Get the ID of the Amazon EBS volume associated with the instance.
VOLUMEID=$(aws ec2 describe-instances \
  --instance-id $INSTANCEID \
  --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" \
  --output text)

# Resize the EBS volume.
aws ec2 modify-volume --volume-id $VOLUMEID --size $SIZE

# Wait for the resize to finish.
while [ \
  "$(aws ec2 describe-volumes-modifications \
    --volume-id $VOLUMEID \
    --filters Name=modification-state,Values="optimizing","completed" \
    --query "length(VolumesModifications)"\
    --output text)" != "1" ]; do
sleep 1
done

#Check if we're on an NVMe filesystem
if [ $(readlink -f /dev/xvda) = "/dev/xvda" ]
then
  # Rewrite the partition table so that the partition takes up all the space that it can.
  sudo growpart /dev/xvda 1

  # Expand the size of the file system.
  # Check if we are on AL2
  STR=$(cat /etc/os-release)
  SUB="VERSION_ID=\"2\""
  if [[ "$STR" == *"$SUB"* ]]
  then
    sudo xfs_growfs -d /
  else
    sudo resize2fs /dev/xvda1
  fi

else
  # Rewrite the partition table so that the partition takes up all the space that it can.
  sudo growpart /dev/nvme0n1 1

  # Expand the size of the file system.
  # Check if we're on AL2
  STR=$(cat /etc/os-release)
  SUB="VERSION_ID=\"2\""
  if [[ "$STR" == *"$SUB"* ]]
  then
    sudo xfs_growfs -d /
  else
    sudo resize2fs /dev/nvme0n1p1
  fi
fi
```


```
admin-user:~/environment/ (master) $ df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        474M     0  474M   0% /dev
tmpfs           492M     0  492M   0% /dev/shm
tmpfs           492M  492K  492M   1% /run
tmpfs           492M     0  492M   0% /sys/fs/cgroup
/dev/xvda1       10G  9.9G  151M  99% /
tmpfs            99M     0   99M   0% /run/user/1000
admin-user:~/environment $ touch resize.sh
admin-user:~/environment $ pwd
/home/ec2-user/environment
admin-user:~/environment $ ls -la
total 12
drwxr-xr-x  4 ec2-user ec2-user   63 Aug 18 00:21 .
drwx------ 15 ec2-user ec2-user 4096 Aug 18 00:20 ..
drwxr-xr-x  4 ec2-user ec2-user  148 Aug 17 23:00 .c9
drwxrwxr-x 13 ec2-user ec2-user  320 Aug 17 23:47 note
-rw-r--r--  1 ec2-user ec2-user  569 Aug  3 03:48 README.md
-rw-rw-r--  1 ec2-user ec2-user 1654 Aug 18 00:21 resize.sh
admin-user:~/environment $ bash resize.sh 20
admin-user:~/environment $ df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        474M     0  474M   0% /dev
tmpfs           492M     0  492M   0% /dev/shm
tmpfs           492M  496K  492M   1% /run
tmpfs           492M     0  492M   0% /sys/fs/cgroup
/dev/xvda1       20G  9.9G   11G  50% /
tmpfs            99M     0   99M   0% /run/user/1000
```

### Amplify UI Components のインストール 

下記を参照。
https://docs.amplify.aws/ui/q/framework/vue/

#### コマンド

`$ yarn add aws-amplify @aws-amplify/ui-vue`

`$ mkdir plugins`

`$ cd plugins`

`$ touch amplify.js`

amplify.jsは下記を入力します。

```amplify.js
import Vue from 'vue';
import Amplify from 'aws-amplify';
import awsconfig from '../src/aws-exports';
import '@aws-amplify/ui-vue';
Amplify.configure(awsconfig);
Vue.use(Amplify);
```

nuxt.config.jsに下記の内容を追加します。

```nuxt.config.js
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    { src: '~/plugins/amplify', mode: 'client' }
  ],
```


default.vueを下記の内容で書き換えます。

```default.vue
<template>
 <amplify-authenticator>
   <v-app>
     <v-app-bar app></v-app-bar>
     <v-main>
       <v-container>
         <Nuxt />
         <amplify-sign-out></amplify-sign-out>
       </v-container>
     </v-main>
   </v-app>
 </amplify-authenticator>
</template>
```

# 8. 起動確認

下記コマンドでテストサーバーを起動して確認する。

`yarn dev`

下記が表示されてメモリ不足でビルドできない場合は、一時的にビルドオプションを設定して実行する。

```
FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory
```

package.json に `"NODE_OPTIONS=\"--max-old-space-size=8192\" nuxt"`を設定する。

```package.json
  "private": true,
  "scripts": {
    "dev": "NODE_OPTIONS=\"--max-old-space-size=8192\" nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
```


サインイン画面が表示されます。
Create account を選択します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/ab75c3b5-cc89-e70e-241c-99a94c0a8232.png)


ユーザー名、パスワード他を入力して CREATE ACCOUNT を押下します。メールアドレスに確認コードが届きます。
![スクリーンショット 2021-08-18 14.40.38.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/50446706-d5ae-195e-a751-79fcb541e49b.png)

メールに記載の確認コードを入力してCONFIRMを押下します。
![スクリーンショット 2021-08-18 14.41.26.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/17f3cd71-a8a8-67cc-c631-4fb7558f16b4.png)


ログインが成功すると下記の画面が表示されます。
![スクリーンショット 2021-08-18 14.42.19.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/ea39a1bd-8b25-f201-ee09-27163ac7648d.png)


# 9. デプロイ

GitHubにコードをpushします。

## コードをcommit

`$ git status`
`$ git add .`
`$ git commit -m "initial commit"


## GitHubにログイン

GitHubのコンソールにログインします。

右端のNewを選択します。
![スクリーンショット 2021-08-18 23.20.58.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/3fd8c454-f335-a2cf-ff66-ac42131a95f2.png)

新規リポジトリ作成画面でリポジトリ名を入力します。Create repositoryを押下。
![スクリーンショット 2021-08-18 23.22.22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/a467caaa-4092-d861-aa9e-83eb4ccd1d3d.png)

「…or push an existing repository from the command line」の箇所のコマンドをCloud9のコンソールで入力します。

![スクリーンショット 2021-08-18 23.26.55.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/4f30249d-f243-5f62-aeef-34c181a631a2.png)

`$ git push -u origin main` の後に、ユーザーIDとパスワードを聞かれますが、パスワードのところはアクセストークンを入力してください。

https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/

https://docs.github.com/ja/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token

GitHubのリポジトリをリロードするとコードがpushされていることを確認できます。
![スクリーンショット 2021-08-18 23.36.39.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/45fb3aa4-34f8-3879-6920-20b0be4470ba.png)


## Amplifyコンソールからコードをデプロイ
AmplifyコンソールからGitHubにpushしたコードを利用してデプロイします。

バックエンドの作成でAmplify CLIから作成したnoteアプリを選択します。
![スクリーンショット 2021-08-18 23.39.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/2a0dbfc3-da3e-b985-96d1-34fb271f9590.png)

Frontend environmentsを選択して、GitHubにチェック。Connect branchを押下します。
![スクリーンショット 2021-08-18 23.39.43.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/1bd53fab-a73c-6202-3a52-a930d70a1f05.png)

GitHubの認証の後のページにて、リポジトリとブランチを選択します。次へを押下。
![スクリーンショット 2021-08-18 23.43.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/f95b65c5-9d17-1250-938d-9da07e2f8f1f.png)

バックエンドの環境はdevを選択。
![スクリーンショット 2021-08-18 23.45.05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/3a868ab4-0a06-964b-b5e8-ecdb922d2f67.png)

ロールは作成済みのものを選択するか、新規にここで作成することができます。
![スクリーンショット 2021-08-18 23.48.15.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/2f326d83-d70d-e36d-0a26-9d7458fd82d6.png)

ビルド設定画面でEditを選択します。
![スクリーンショット 2021-08-18 23.49.28.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/e4a96c4a-ceb1-05e1-5290-5b28e8c0428f.png)

ビルド設定を下記の通り変更します。
下記を参照。
https://docs.amplify.aws/guides/hosting/nuxt/q/platform/js/

変更前
![スクリーンショット 2021-08-18 23.53.08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/7af5f669-c34b-312e-c25d-e85c68083266.png)

変更後
![スクリーンショット 2021-08-19 0.07.44.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/cf3b8744-52c4-bf8a-292e-7cdaeea02c20.png)

保存してデプロイを押下します。

デプロイ成功画面です。
![スクリーンショット 2021-08-19 0.10.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/3c2c73e5-a569-3a90-5977-c81d5f58a1b5.png)

## 実行して確認
Amplifyでホスティングが実行されているので、URLのリンクからブラウザでアクセスします。
![スクリーンショット 2021-08-19 0.12.21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/68a8af25-6857-330c-33ea-a53d8aa9592b.png)

アクセスができない場合は、デプロイの設定を見直して再度デプロイします。
![スクリーンショット 2021-08-19 0.12.48.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/cc9efde7-a5c5-35fb-4c29-7b9190009171.png)

ビルド・デプロイが成功すると、Amplifyでホスティングされた環境でアプリを実行することができます。
![スクリーンショット 2021-08-19 0.20.09.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/b818c6fb-2ae5-eba8-c6fd-ed7e5c3fcc29.png)



# 10. 環境の削除

## バックエンドリソースの削除
Amplify CLIを使ってバックエンドの環境を削除します。

### コマンド

`$ amplify status`

`$ amplify delete`


```
admin-user:~/environment $ cd note
admin-user:~/environment/note (main) $ amplify status

Current Environment: dev

| Category | Resource name | Operation | Provider plugin   |
| -------- | ------------- | --------- | ----------------- |
| Auth     | note7539b6b2  | No Change | awscloudformation |


admin-user:~/environment/note (main) $ amplify delete
? Are you sure you want to continue? This CANNOT be undone. (This will delete all the environments of the project from the cloud and wipe o
ut all the local files created by Amplify CLI) (y/N) y
⠋ Deleting resources from the cloud. This may take a few minutes...
Deleting env: dev.
✔ Project deleted in the cloud.
Project deleted locally.
```

## フロントエンド環境の削除

AmplifyコンソールからAmplifyプロジェクトを削除します。

右上のアクションを押下。アプリの削除を選択します。

![スクリーンショット 2021-08-18 21.22.08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/2b4a2aed-71bf-cef4-3f6e-f36e3bb6990a.png)

「アプリを削除します」ダイアログにdeleteを入力して、Deleteボタンを押下します。
![スクリーンショット 2021-08-18 21.24.50.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/ff77a33f-af3d-dc42-291a-d2c7f4173913.png)

最後にCloud9環境も削除します。

Cloud9ダッシュボード画面にて、Deleteを押下。
![スクリーンショット 2021-08-19 0.29.44.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/301b23bb-b0bd-27b7-7dae-83081cea0814.png)

削除ダイアログにて、Deleteを入力して、Deleteを押下。
![スクリーンショット 2021-08-19 0.30.06.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/214523/5d78305e-c49f-05d3-64bb-d895548a0d77.png)

これで全ての環境が削除されました。

お疲れ様でした。