1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactとバックエンドで作る!実践Web開発入門 | 第8章: アプリをデプロイする

Posted at

はじめに

第7章で認証機能を追加しました。今回は、完成したアプリを本番環境にデプロイします。ReactフロントエンドとNode.jsバックエンドをそれぞれVercelとHerokuにデプロイする方法を学びます。

目標

  • Reactアプリをビルドしてデプロイする
  • バックエンドをクラウドにデプロイする
  • フロントエンドとバックエンドを連携させる

フロントエンドのデプロイ(Vercel)

1. Reactアプリのビルド

frontendフォルダで以下を実行:

npm run build

buildフォルダが生成されます。

2. Vercelのセットアップ

  1. Vercel CLIをインストール:
    npm install -g vercel
    
  2. frontendフォルダでログイン:
    vercel login
    
  3. デプロイ実行:
    vercel
    
    • 指示に従い、設定を進めます(デフォルトでOK)。
    • 完了後、URL(例: https://your-app.vercel.app)が提供されます。

3. 環境変数の設定

バックエンドのURLをReactで使うため、frontend/.envを作成:

REACT_APP_API_URL=https://your-backend.herokuapp.com

App.tsxfetchを修正:

const response = await fetch(`${process.env.REACT_APP_API_URL}/products`);

ビルドし直し、再デプロイ:

npm run build
vercel --prod

バックエンドのデプロイ(Heroku)

1. Herokuの準備

  1. Heroku CLIをインストール(公式サイトから)。
  2. backendフォルダでログイン:
    heroku login
    

2. アプリの設定

  1. Herokuアプリを作成:
    heroku create your-backend
    
  2. MongoDBをクラウドで使用する場合(例: MongoDB Atlas):
    • Atlasで無料クラスタを作成し、接続文字列を取得。
    • index.jsmongoose.connectを更新:
      mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/productdb', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
      
  3. Heroku環境変数を設定:
    heroku config:set JWT_SECRET=secret_key
    

3. デプロイ

  1. backendProcfileを作成:
    web: node index.js
    
  2. Gitで管理:
    git init
    git add .
    git commit -m "Initial commit"
    
  3. Herokuにプッシュ:
    heroku git:remote -a your-backend
    git push heroku main
    

4. 動作確認

https://your-backend.herokuapp.com/productsにアクセスし、データが返るか確認。

フロントエンドとバックエンドの連携

  • ReactのREACT_APP_API_URLをHerokuのURLに設定。
  • CORSを調整(backend/index.js):
    app.use(cors({ origin: 'https://your-app.vercel.app' }));
    
  • 再デプロイ(HerokuとVercel両方)。

動作確認

  1. https://your-app.vercel.appにアクセス。
  2. ログインし、商品リストの表示と追加をテスト。

次回予告

第9章では、パフォーマンスの最適化と追加機能を学びます。お楽しみに!


この記事が役に立ったら、ぜひ「いいね」や「ストック」をお願いします!質問や感想はコメント欄で気軽にどうぞ。次回も一緒に学びましょう!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?