Can a React Page Work if Uploaded to a Shared Virtual Host

Table of Contents

    • Spring to
  • Where Should I Deploy My React App?
  • Common Considerations
    • Workflow
    • Application Type
    • Security
    • Pricing and Performance
  • 7 Ways to Deploy a React App
    • Prerequisites
    • Forking the Starter Repository
    • ane. How to deploy a React App on Heroku
      • 1. Prepare-Up Node.js Server
      • 2. Deploy to Heroku
    • 2. How to deploy a React App on Apache server (Linode)
      • 1. Configure and Deploy the Server
      • 2. Prepare Upwards Apache Server
      • 4. Offset Application
    • iii. How to deploy a React App on Firebase
      • ane. Set-up Firebase Locally
      • two. Deploy to Firebase
      • iii. Add Firebase Part
      • 4. Upgrade Programme for Outbound Networking
    • 4. How to deploy a React App on Github
      • 1. Install and Configure Github Pages
      • 2. Deploy to Github Pages
      • 3. Ostend Deployment on Github
    • 5. How to deploy a React App on AWS Dilate
      • 1. Set up Upwards AWS Amplify
      • 2. Add Backend API to Projection
      • 3. Create Weather condition API Part Phone call
      • four. Modify the Client API Call
      • 5. Add API Key with AWS Secrets Manager
      • 6. Deploy to Amplify Hosting
    • vi. How to deploy a React App on Azure
      • i. Configure an Azure Function in Project
      • 2. Add API Function
      • three. Deploy Static Web App on Azure
      • 4. Add together API Central
    • 7. How to deploy a React App on Netlify
      • 1. Add together Call to Weather API
      • 2. Add netlify.toml file
      • iii. Deploy to Netlify
      • 4. Add together API Key to Environs Variables
  • Conclusion

Bound to

  • Heroku
  • Apache server (linode)
  • Firebase
  • Github
  • AWS Dilate
  • Azure
  • Netlify

Where Should I Deploy My React App?

Deploying your newly created React App typically falls at the hands of whoever is creating the tutorial or example awarding that you lot are following. Sometimes this works out fine considering they typically have experience with that deployment choice, or the deployment option is piece of cake to follow.

Notwithstanding, at some indicate, you are going to wonder what other options are out there and if your future app could do good from various deployment options.

Today, we are going to accept a elementary React application and deploy it to several services covering dissimilar options. I hope that the awarding and deployments tin can widen your understanding of how different apps fit into deployment scenarios.

Common Considerations

Workflow

The workflow consideration unremarkably is the result of the question, how much work am I willing to do? Many cloud providers have institute success past offering quick and painless ways to get an application into production that is easy to manage.

Managing a production server can be a lot of work with the amount of configuration, monitoring, and updating that takes place over the server'southward lifetime. Even so, sometimes the application requires this kind of setup. Later, we are going to cover setting up a cloud server running Ubuntu and deploy a React app to that remote server.

Furthermore, there are considerations with continuous integration (CI) and continuous deployment (CD). Does your app crave a separate Jenkins server for handling these desirable workflow features? Or, tin can you choose a deployment choice that automatically integrates with your Git repository?

Application Blazon

Another consideration is the supported application types. Some services only support certain languages. Furthermore, other services are more designed towards sure stacks (i.eastward JAMstack, MERN, LAMP). These dissimilar stacks reverberate the application's language, data storage blazon, etc. It's worthwhile to deploy in a way that fits the style of your awarding.

Security

I of the kickoff considerations that I have when choosing a deployment pick is what levels of security do I need? Many applications need to maintain secret keys to allow access to resources or muffle user information.

There are many tutorials available for deploying React applications that do non include the use of third-political party API keys. Consequently, one of the nigh important aspects of any application (security) can have an event on how the application is designed.

Pricing and Performance

The overarching consideration is how much the deployment will toll. This is usually fastened to the desired performance of the application and the desired geographic outreach. Thankfully, most cloud deployment options are transparent about their pricing and accept free options to test the service before committing.

vii Ways to Deploy a React App

In the rest of the article, we are going to take a simple React awarding and deploy it in numerous ways. The awarding is a unmarried folio and makes an API call. It volition exist transformed to fit different deployment scenarios.

The deployments practice not include static site options like Gatsby.js or server-side-rending frameworks like Next.js. However, below is a list of tutorials that can get you started using Gatsby or Side by side.js:

Gatsby.js

  • How to Create a Multi-Page React App
  • How to Display API Information Using Axios with React

Side by side.js

  • How to use the Google Maps API in React
  • How to Fetch Data From a GraphQL API in React

One static pick nosotros will talk about is deploying to Github Pages. This application will not make the third-party API call, but if you lot used a different provider, like AWS, Azure, Firebase, every bit demonstrated in the other awarding deployments, then yous could set up a function phone call to serverless deject function.

At that place are a few prerequisites to cover, just later that, we will exist set up to begin!

Prerequisites

  • Git installed and ready-upwards
  • Internet admission
  • Basic experience using Git and the control line
  • Bones experience with React.js and Node.js
  • RapidAPI Account. Visit RapidAPI to become signed upwardly for a free account if y'all oasis't already!
  • Subscription the Aeris Weather API
    • Visit the Pricing folio to subscribe.
    • The gratuitous program allows for 100 API requests a day

Forking the Starter Repository

Open upward a new browser and navigate to https://github.com/jdretz/rapidapi-deply-react-app

Towards the top right of the screen, hit theFork push button. A copy of the repository volition be added to your Github account.

Next, clone the repository from your Github account to your local system.

git clone https://github.com/yourusername/rapidapi-deply-react-app.git

Open up a new terminal in your cloned project root and runnpm install.

You are now ready to make changes and push those changes up to your new repository. If you program on doing multiple deployments with the repository yous could delete it after each deployment and re-fork the repository or work on your Git skills and revert it to a previous commit.

1. How to deploy a React App on Heroku

Sign up for an account on Heroku.

Download the Heroku-CLI for your platform or using the command line with npm install -g heroku.

heroku cli download page

Afterward downloading, open upward a new final and  configure the Heroku-CLI by enteringheroku login into the terminal.

Our Heroku deployment requires a Node backend to consummate our API call.

Therefore, we are going to rearrange our project structure and add together a Node.js backend.

After following the forking instructions higher up, open up the project with your text editor.

i. Prepare-Up Node.js Server

In the root of the project create a folder namedclient. Move all of the visible files into that folder.

Next, in the projection root, create the files;

  • server.js
  • .gitignore

And so, add the code beneath to the corresponding file.

server.js

const express = crave('express'); const path = require('path'); const axios = require('axios');  // Loads env variables require('dotenv').config()  const app = express();  const PORT = process.env.PORT || 3001;  // Adds json parsing middleware app.use(express.json());  // Setup static directory to serve app.use(express.static(path.resolve('customer', 'build')));  // Creates weather endpoint app.post('/weather', async (req, res) => {     const { location } = req.body      // Encode the variable so we tin ship the location in a URL     const encodedLocation = encodeURIComponent(location)      effort {         // Phone call the Weather condition API         const { data } = await axios({             method: "GET",             url: `https://aerisweather1.p.rapidapi.com/observations/${encodedLocation}`,             headers: {                 "content-type": "application/octet-stream",                 "x-rapidapi-host": "aerisweather1.p.rapidapi.com",                 "x-rapidapi-key": process.env.RAPIDAPI_KEY,                 "useQueryString": truthful             }         })          // Pull the information that nosotros need from the Weather API response         const weatherData = {             weather: data.response.ob.conditions,             tempC: information.response.ob.tempC,             tempF: data.response.ob.tempF         }          // Return the data object         return res.send(weatherData)     } catch (e) {         console.log(e)          render res.status(500).send('Error.')     } })  app.get('*', (req, res) => {     res.sendFile(path.resolve('client', 'build', 'index.html')); });  // panel.log that your server is up and running app.mind(PORT, () => console.log(`Listening on port ${PORT}`));

.gitignore

node_modules .env package-lock.json.*

Finally, navigate into your server folder using the final. Inside the server directory execute the commands,

$ npm init -y $ npm install limited axios dotenv --salve

Afterward the packages are installed, in that location is but one more change to be made to the project. Open upward client/src/App.js and alter the URL in line xviii of the file to/weather.

Practiced work, our API office is now on our backend server. Permit'south deploy to Heroku!

2. Deploy to Heroku

In server/package.json, under scripts add a start script and mail-build script.

"scripts": {   "showtime": "node server.js",   "heroku-postbuild"::"cd customer && npm install && npm run build"   ... },

Next, create a file named Procfile in the project root and add this line to it.

web : npm run start

Button the changes that we simply made to your Git repository.

Now, we are ready to create the Heroku app!

Brand certain that your final is in the project root and run the command heroku create.

This command returns the app proper noun (i.e "floating-declension-11273″), URL, and Git remote URL.

Now that we accept the app proper name we can add in our RapidAPI-key environment variable.

Locate your API primal on RapidAPI. Then, run the command, inserting your RapidAPI key.

heroku config:set RAPIDAPI_KEY=yourkey

Finally, nosotros can push the changes to the Heroku remote Git repository and our app will exist built.

In the project root run:

git push button heroku master

The app volition build and output the URL for the new application, again.

heroku build output

Swell piece of work! I hope that was easy!

Recollect your app is now public, you can log onto Heroku and delete or deactivate your application if you don't want people to run upward your API request usage.

2. How to deploy a React App on Apache server (Linode)

The Apache deployment requires a Node backend for our API call, but if we use Linode we tin simplify the deployment process. Then, subsequently deployment, nosotros can make the custom changes that nosotros demand past accessing the remote server.

Despite simplifying the process, running a cloud product server requires more configuration. Consequently, there is increased risk. I take made a Linode StackScript available to help mitigate some of the risks with the process.

Furthermore, when deploying to your own remote server, we are doing more than transmission tasks. Some deject providers set up nice continuous deployment workflows, but this setup is very hands-on.

Follow the forking instructions above and so complete the start pace in theHeroku deployment to complete the Node.js (Express) dorsum-stop set. When completed, push button your changes up to the Git repository.

Sign upward on Linode so visit your Cloud Dashboard.

1. Configure and Deploy the Server

Once on the dashboard selectStackScripts on the left sidebar. On the elevation right of the page click theCreate New Stackscript. Proper name it whatever y'all like, and write a cursory description.

ChooseUbuntu xviii.04 for the image and paste in the beneath code to the script.

#!/bin/bash # <UDF proper name="projection" Label="Name of Projection" instance="personal_blog" /> # <UDF proper name="username" Label="Create New User" example="username" /> # <UDF name="password" Label="New User Countersign" /> # <UDF name="hostname" Characterization="Change Hostname" example="localhost" /> # <UDF proper name="sshkey" Label="Add GPG Public Primal" example="AAAAB3NzaC1yc2EAAAADAQABAAACAQCdZBMH9fKg995K" default=""/> # <UDF proper noun="disableroot" Label="Disable Login with Password & Disable root user Login?" oneOf="Yes,No" default="Yes" /> # <UDF name="timezone" Label="Set Date Time Zone" oneOf="EST, UTC, MST" default="EST" /> # This sets the variable $IPADDR to the IP accost the new Linode receives. IPADDR=$(/sbin/ifconfig eth0 | awk '/inet / { print $two }' | sed 's/addr://') echo "    ~~~~ Running Ubuntu18LTS configuration ~~~~" #Update sudo apt-go update # Set date/Time to EST echo $TIMEZONE | sudo timedatectl ready-timezone $TIMEZONE date echo $USERNAME if [ "$USERNAME" != "" ] then   echo $USERNAME | adduser --disabled-password --vanquish /bin/bash --gecos "User" $USERNAME   echo $USERNAME:$PASSWORD | chpasswd   sudo adduser $USERNAME sudo   # SSH Harden   sudo mkdir -p /habitation/$USERNAME/.ssh   sudo chmod -R 700 /abode/$USERNAME/.ssh   sudo chown $USERNAME:$USERNAME /abode/$USERNAME/.ssh   sudo touch /dwelling/$USERNAME/.ssh/authorized_keys   # GPG Public Key   sudo echo $SSHKEY >> /home/$USERNAME/.ssh/authorized_keys   cd ~ fi echo $HOSTNAME # Check if hostname's been provided if [ "$HOSTNAME" != "" ] then   hostnamectl ready-hostname $HOSTNAME   # Add together hostname to Hosts   myip="$(roll ifconfig.me)"   sudo echo "$myip   $HOSTNAME" >> /etc/hosts   echo "Host name changed to: " $HOSTNAME fi repeat $DISABLEROOT if  [ "$DISABLEROOT" == "Yes" ] then   # Brand certain a user is provided in order to prevent beingness locked out   if [ "$USERNAME" != "" ]   then     # Disable root login     echo "Disabling root login"     sudo sed -i -e 's/PermitRootLogin yes/PermitRootLogin no/m' /etc/ssh/sshd_config     # If GPG primal is provided disable login by password     if [ "$SSHKEY" != "" ]     and then       sudo sed -i -e 's/#PasswordAuthentication yeah/PasswordAuthentication no/g' /etc/ssh/sshd_config     fi   fi fi # Install Apache sudo apt install apache2 -y sudo mkdir /var/www/$Project sudo chown -R $USERNAME:$USERNAME /var/www/$PROJECT sudo chmod -R 755 /var/world wide web/$PROJECT sudo touch /etc/apache2/sites-available/$PROJECT.conf sudo a2enmod proxy proxy_http rewrite headers expires sudo a2dissite 000-default #Install Node and NPM and other dependencies curlicue -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs sudo apt install build-essential sudo npm install pm2@latest -g # Set up Up Firewall sudo apt-get install ufw -y sudo ufw default let outgoing sudo ufw default deny incoming sudo ufw allow ssh sudo ufw permit 80 sudo ufw status sudo ufw --force enable echo "    ~~~~~~~~ Ubuntu 18 LTS configuration is consummate ~~~~~~~~" sudo reboot

There are a lot of commands that go into setting up a server. The higher up script:

  • configures the timezone, hostname, IP address
  • creates a superuser with your username and countersign
  • sets up SSH keys for remote server admission authorization
  • downloads Node, NPM,  PM2, and other dependencies
  • disables root password login
  • blocks all incoming traffic except on ports 22 (SSH port) and 80 (HTTP)
  • installs and does some configuration for Apache webserver

Save the script.

Next, select the newly created StackScript and, in the acme right, hit theDeploy New Linode button.

required arguments for linode

Fill out the information in the input fields. The project name is used equally a folder proper name on the server so it cannot take spaces.

Then, to set up up the remote SSH you must input a public SSH key that you take on your calculator.

This key must exist generated, and on a Mac can typically be found in the/.ssh/ binder. However, some systems change, and not everyone uses the same operating system. This is the point in the process where you will most likely have difficulty if yous have never accessed a remote server before.

For Mac users, this is a helpful post on Stack Overflow in terms of getting your public key.

For Windows, y'all are probably better off with this Youtube search. You lot will have to install and configure PuTTY.

Once you have your public key pasted into the form (and on your computer) terminate filling out the class with these values.

  • Disable root login
  • Select Ubuntu 18.04 LTS
  • Pick the closest region to your location.
  • Select Nanode for Linode plan. It's the cheapest option at $5 a month, and you lot tin conciliate or delete the Linode as shortly as we finish deploying.
  • Enter a root user countersign

Before creating the Linode you need a credit card on file for your business relationship.

StrikingCreate.

The Linode takes a little bit of time to boot.

2. Set Up Apache Server

The indicator circle in the top right will be light-green and display Online when the Linode is ready. Select theNetworking and copy your new IP address.

networking tab with IP address

Open up up a new terminal and SSH into the remote server. On Mac, this can exist done with:

ssh the_username_you_entered_earlier@ip_address

Requite it one or ii tries earlier starting to troubleshoot. Sometimes the server isn't ready nonetheless.

Once logged into the server open up the project configuration file for Apache. The file name will be the proper noun of the project that y'all entered earlier.

sudo nano /etc/apache2/sites-bachelor/projectname.conf

Once in the file copy and paste the code below.

<VirtualHost *:fourscore>     ServerName domain.com     ServerAlias www.domain.com      ProxyRequests Off     ProxyPreserveHost On     ProxyVia Total      <Proxy *>         Crave all granted     </Proxy>      ProxyPass / http://127.0.0.1:3001/     ProxyPassReverse / http://127.0.0.1:3001/ </VirtualHost>

The code sets up a proxy and so requests made to port 80 are redirected to port 3001. This is the port that our Node server is listening on.

To enable the site run sudo a2ensite projectname.conf .

To save the file, hit Crtl+X, and so Y, and finally, Enter.

3. Clone Repository

Next, we need to pull our project code to the server and build the project. Change directories into /var/www/projectname with the cd command.

Clone your Git repository with the command below.

git clone https://github.com/yourusername/rapidapi-deply-react-app.git

You lot may have changed the repository URL for your account.

Side by side, nosotros need to install the Node packages for the forepart-end and back-end and run a build.

Execute the commands:

$ cd rapidapi-deply-react-app/ $ npm install $ cd customer && npm install  $ npm run build

The first control may be dissimilar if your repository or folder has a dissimilar proper name.

Once it'southward washed building, change directories back the repository folder (i.east rapidapi-deply-react-app).

cd ..

4. Showtime Application

Earlier starting the app we demand to configure our environment variable that holds the RapidAPI fundamental.

Create a new file name ecosystem.config.js.

touch ecosystem.config.js

Inside that file, paste the following code.

module.exports = {   apps : [       {         proper noun: "react_deploy",         script: "./server.js",         picket: true,         env: {             "PORT": 3001,             "RAPIDAPI_KEY": "yourapikey",             "NODE_ENV":"product"         }       }   ] }

Exist sure to supersedeyourapikey with your actual API key.

Salvage the file.

This file is specific to the PM2 library.

To kickoff the application run the command below.

sudo systemctl start apache2 && pm2 offset ecosystem.config.js

Finally, you can visit the IP address that you copied earlier in the browser to notice our app.

Final app on Linode server

You have done some great work if you made it this far! However, the app can even so use a little piece of work. Unfortunately, I won't be going into setting up a custom domain or configuring an SSL certificate. Yet, yous can use the instructions on Permit's Encrypt to get a costless SSL certificate in one case you lot have a domain name.

Don't forget to deactivate or delete your Linode in the dashboard so you lot practise non any incur whatever extra charges.

3. How to deploy a React App on Firebase

Firebase has many of the same options when deploying a React app as AWS and Azure. With Firebase, we can ready a statically hosted awarding that makes API calls to a cloud function that renders dynamic content on our site.

First, follow the forking directions above to become the starter project. Then open the projection in your text editor with a new terminal in the project root.

You volition need a Google Account earlier proceeding.

one. Set-up Firebase Locally

Install the Firebase CLI.

npm install -grand firebase-tools

Log in to Firebase with your Google Account.

firebase login

Make sure your terminal is in the projection root and initialize a new Firebase projection.

firebase init

Next, y'all will be taken through a series of prompts.

For the project set-up select;

Create a new project

Next, specify the name of your new project when prompted.

When asked, What would you similar to call your new projection? hitting enter to use the default.

Then, in the hosting fix-up prompts, select the options that I made in the beneath image.

firebase prompts

Next, in the projection root, executenpm run build.

2. Deploy to Firebase

When the build completes runfirebase deploy. When the project is done deploying there should exist a URL to visit the new project. Our app should appear when you visit the folio.

application on firebase

Next, let'due south add together a office that will call our API. This will allow us to secure our API key and it will permit our app to display dynamic content.

3. Add Firebase Function

Add functions to the project.

firebase init functions

Next, follow the prompts and respond with the answers from the epitome beneath.

deploing react app prompts

Then, change directories into the functions directory with cd functions

Install Axios.

npm install axios

Afterward Axios is installed nosotros can add our RapidAPI secret key to the part configuration with the post-obit line. Enter the below control into the last replacing apikey with your RapidAPI key.

firebase functions:config:prepare rapidapi.central="apikey"

This is how nosotros tin add environs variables to functions. Finally, replace all the code in functions/index.js with the code below.

const functions = require('firebase-functions'); const axios = require('axios')  exports.weather = functions.https.onRequest(async (req, res) => {      if (req.method !== "POST") {         render res.status(405).send('Method not allowed')     }      // Assign the location value to the variable location from the trunk object     const { location } = req.torso      // Encode the variable then we can transport the location in a URL     const encodedLocation = encodeURIComponent(location)      try {         // Telephone call the Weather API         const { data } = await axios({             method: "Go",             url: `https://aerisweather1.p.rapidapi.com/observations/${encodedLocation}`,             headers: {                 "content-type": "application/octet-stream",                 "ten-rapidapi-host": "aerisweather1.p.rapidapi.com",                 "x-rapidapi-key": functions.config().rapidapi.fundamental,                 "useQueryString": truthful             }         })          // Pull the information that we need from the Weather API response         const weatherData = {             conditions: information.response.ob.weather,             tempC: data.response.ob.tempC,             tempF: data.response.ob.tempF         }         // Return the data object         render res.ship(weatherData)     } grab (e) {         panel.log(e)          return res.condition(500).send('Error.')     }    });

The fundamental is imported on thefunctions object and is accessed with functions.config().rapidapi.primal.

Nosotros need to add together a rewrite dominion and so our part has a convenient URL. In firebase.json, add the following rewrite rule above the/index.html rule.

{   "source": "/weather",   "function": "weather" },

Now, therewrites section of your firebase.json file looks like,

          "rewrites": [     {       "source": "/weather",       "function": "weather"     },     {       "source": "**",       "destination": "/alphabetize.html"     }   ] },

Then, alter the API telephone call URL on line 18 of App.js to /atmospheric condition.

Finally, redeploy your hosting and functions with,

firebase deploy.

four. Upgrade Plan for Outbound Networking

Firebase cloud functions require a pay-equally-you-go subscription for functions that use outbound networking. The free tier covers functions that y'all employ Google services. Therefore, to send the request to the Aeris Weather API you lot need to upgrade your account.

You tin see the pricing details and upgrade them by following this link.

Nevertheless, one time you upgrade, the statically hosted app can brand an API phone call to our cloud part that, subsequently, makes an API call to the weather condition API for data. The weather information is returned and displayed on the folio!

4. How to deploy a React App on Github

Github Pages is a static website hosting service. This means it takes HTML, CSS, and Javascript files and hosts them as private pages. This can be useful for documentation, or a portfolio, but requires more work if were hoping to make an API phone call from our front end-stop.

Therefore, we tin deploy a React application with ease, but cannot gear up up a simple Node backend to secure our third-political party API phone call or use a built-in serverless office (like some of the other deployment options).

We could set upwards a serverless function on a unlike service and configure the cross-origin resource sharing (CORS) to only permit access from our domain. Nonetheless, let's deploy the application.

First, follow the instructions to fork the application.

1. Install and Configure Github Pages

Install the Github Pages library.

npm install gh-pages --save-dev

Next, openbundle.json and paste in thehomepage property at the top of the object.

"homepage": "https://yourusername.github.io/yourrepositoryname",

You will need to locate your username and repository name to modify the URL accordingly.

Next, add together the post-obit properties to thescript object.

"scripts": {   // ... other commands   "predeploy": "npm run build",   "deploy": "gh-pages -d build" },

ii. Deploy to Github Pages

Push your changes to your repository.

$ git add package.json bundle-lock.json $ git commit -m "deploy setup for Github Pages" $ git push

In a last located at the root of the project (where you lot installedgh-pages in the previous step), run the controlnpm run deploy.

This creates a new branch that hosts your React app named gh-pages.

3. Confirm Deployment on Github

Open a browser and navigate to your Github repository.

Click on theSettings tab and scroll downwardly to the Github Pages section.

github pages setting

TheSource attribute needs to exist set to the gh-pages co-operative. You lot can also discover your site URL and customize the domain name.

If you visit the page the API telephone call for atmospheric condition data will not work. In that location is non a function fix to fetch the data because we cannot secure our API primal on the forepart end.

error message on website

The Axios API call URL inApp.js could be modified to phone call a serverless function gear up on a cloud provider. Bank check out i of the other deployment options for setting up serverless functions.

Regardless, it's very easy to turn a React app into a website with Github Pages.

5. How to deploy a React App on AWS Dilate

AWS is a cloud hosting service. The deployment our the React App is going to be like to our deployments for Azure and Firebase. Nosotros are going to host the static files on a storage organization and brand API calls to serverless functions. This is a smashing pick for our application, and can further be expanded to incorporate server calls for database records if the app progresses.

Sign Upward for an business relationship on Amazon Web Services.

Fork the repository following the instructions above.

1. Set Upward AWS Amplify

Open up the projection in your text editor and open a new terminal the root of the project directory.

Install AWS packages.

npm install aws-amplify aws-dilate-react --salvage

Install the Amplify CLI-tools globally

npm install -m @aws-amplify/cli

Configure the Amplify CLI

amplify configure

This will get-go a series of prompts.

Kickoff, sign in to your AWS ambassador account and specify a region that is shut to you lot.

And so, create a username for the new programmatic user that volition be connected to your local computer. To utilize the default, striking enter.

This pulls upwards the user cosmos page on AWS. Give the new user AministratorAccess.

Stop when yous come across the page with the ACCESS ID and Secret key

accessid and secret key page

In the terminal, you are prompted to enter the Access key ID and the Secret admission fundamental. The secret admission key is only available once, and then brand sure you practice not navigate abroad from this page until after yous enter thesecretAccessKey in the user prompt.

Proper noun the contour "default".

Now that nosotros accept an Dilate user we can initialize an Amplify project. In the root of the directory enter the command below.

amplify init

Again, we have a serial of prompts to fill out.

amplify initiation prompts

The two red arrows betoken to aspects of the prompts that may exist dissimilar for your situation. The cherry box outlines the name of the user profile that nosotros created when nosotros configured the Amplify CLI.

Later, we employ the aws-amplify library to telephone call a Lambda office. However, this needs to be configured in the front end-stop React awarding.

Open upsrc/index.js and add the three lines below that configure the customer.

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import Amplify from 'aws-amplify'      // ADD import config from './aws-exports'     // Add  Amplify.configure(config)            // Add  ReactDOM.render(   <React.StrictMode>     <App />   </React.StrictMode>,   document.getElementById('root') );  // If y'all want your app to piece of work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();

Now that we have initialized an Amplify project we can add the backend API.

2. Add together Backend API to Project

Information technology'southward fourth dimension for some other command and some other series of prompts!

Run amplify add api in the project root.

Then, apply the post-obit answers to the prompts.

add api prompt responses

There is at present a local Lambda function that we can edit earlier we push button it up to our Amplify projection.

3. Create Conditions API Function Telephone call

A new folder nameddilate gets created (if you ran the commands from the root of the projection) in our React projection. Open up the file atdilate/backend/office/src/app.js.

Notice that this is the Express part app that was created in the previous step. The file has function examples that use the base of operations API road we entered in the prompts (weather).

Replace all the code in amplify/backend/function/src/app.js with the code below.

/* Amplify Params - Practise NOT EDIT   ENV   FUNCTION_CALLWEATHERAPI_NAME   REGION Dilate Params - Exercise NOT EDIT *//* Copyright 2017 - 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). Yous may not utilise this file except in compliance with the License. A copy of the License is located at     http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either limited or implied. Encounter the License for the specific linguistic communication governing permissions and limitations nether the License. */  var express = require('limited') var bodyParser = require('body-parser') var awsServerlessExpressMiddleware = require('aws-serverless-express/middleware') var axios = require('axios')  // Import get secrets part var surreptitious = crave('./clandestine-manager')  // declare a new express app var app = express() app.utilize(bodyParser.json()) app.use(awsServerlessExpressMiddleware.eventContext())  // Enable CORS for all methods app.apply(part (req, res, adjacent) {   res.header("Admission-Control-Allow-Origin", "*")   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Have")   next() });  app.mail service('/weather', async function (req, res) {   // Assign the location value to the variable location from the body object   const { location } = req.torso    // Encode the variable so nosotros tin send the location in a URL   const encodedLocation = encodeURIComponent(location)    try {     // Call AWS Secrets to get RapidAPI key     const secretObj = wait secret()      // Call the Weather API     const { information } = await axios({       method: "GET",       url: `https://aerisweather1.p.rapidapi.com/observations/${encodedLocation}`,       headers: {         "content-type": "application/octet-stream",         "x-rapidapi-host": "aerisweather1.p.rapidapi.com",         "x-rapidapi-key": secretObj["RAPIDAPI-KEY"],         "useQueryString": truthful       }     })      // Pull the information that we demand from the Weather API response     const weatherData = {       conditions: information.response.ob.weather,       tempC: data.response.ob.tempC,       tempF: data.response.ob.tempF     }      // Return the information object     return res.ship(weatherData)   } grab (e) {     console.log(e)     return res.status(500).send('Error.')   }; });  app.listen(3000, function () {   panel.log("App started") });  // Consign the app object. When executing the awarding local this does nothing. However, // to port it to AWS Lambda we will create a wrapper around that will load the app from // this file module.exports = app        

This file now implements the API call the weather API for our app. However, Axios is not installed and it is used in the function. In addition, we have not implemented thesurreptitious-manager file, but that will be done in a later step.

In the terminal, modify directories into the dilate/backend/function/src folder. This folder is an initialized Node package. We know this considering there is a package.json file. Therefore, we can download Node packages here to use in our functions.

Install the Axios library and then it can be used in our function.

npm install axios --save

While we are here, we need to install the aws-sdk for accessing secrets afterwards.

npm install aws-sdk --save

4. Change the Client API Call

We demand to call our new function in src/App.js. However, in an Amplify application, this is done differently then the current API call set upwards.

Instead of using Axios, we use the aws-amplify library that we installed earlier.

Import theAPI object fromaws-amplify at the summit of the page with the other imports.

import { API } from 'aws-amplify';

Replace thefetchWeather role inApp.js with the code below.

const fetchWeather = (eastward) => {   eastward.preventDefault()   setLoading(truthful)   setError(false)    const myInit = {     body: {       location     },   };    //make edit to redeploy   API.postal service('weatherAPI', '/weather', myInit)     .and then((data) => {       setTempC(data.tempC)       setTempF(data.tempF)       setConditions(data.conditions)     })     .grab(e => {       setError(true)       console.log(e)     })     .finally(() => {       setLoading(false)     }) }

Information technology's of import to note that the start 2 arguments in the post part depend on the values we entered into the prompts when we created the function.

5. Add API Central with AWS Secrets Manager

You may detect later on in the Amplify Console that in that location is a place to add environment variables. Unfortunately, these variables are not bachelor in the Lambda function that nosotros just ready up. Therefore, we need to plant a workaround.

The workaround that we are going to implement was suggested by Troy Goode on the Amplify-CLI issues page on Github.

On your AWS business relationship, open up the Secrets Manager service

Create a new secret namedrapidapi that holds the value of your RapidAPI key.

new rapidapi secret

Back in the project, in the folderamplify/backend/role/callWeatherApi/src, create a file namehush-hush-director.js. Within of the file, add together the lawmaking:

const AWS = require('aws-sdk')  module.exports = async () => {   const secretsManager = new AWS.SecretsManager()   const secret = await secretsManager.getSecretValue({ SecretId: 'rapidapi' }).promise()   if (!hugger-mugger) {     throw new Error('Cloak-and-dagger not establish')   }   return JSON.parse(secret.SecretString) }

This gives the/weather endpoint the ability to telephone call the Secrets Manager for our underground key. However, the Lambda function does not currently have access to that secret. We tin can give the Lambda function the admission it needs in the dilate/backend/office/callWeatherApicallWeatherApi-cloudformation-template.json file.

Open up the callWeatherApicallWeatherApi-cloudformation-template.json file.

This is a JSON configuration file that controls aspects of our "cloud stack" that is implemented when the awarding is deployed. Furthermore, information technology can command IAM admission for various resource.

At that place is aResources parameter that contains an object. On that object there is a parameter named lambdaexecutionpolicy. Further down in this object exists the PolicyDocument object that holds various policy statements in aStatements array.

Add the object below to the array.

{      "Outcome": "Allow",      "Action": [          "secretsmanager:GetSecretValue"      ],      "Resource": {          "Fn::Sub": [              "arn:aws:secretsmanager:${region}:${account}:undercover:rapidapi-RLE73o",              {                  "region": {                      "Ref": "AWS::Region"                  },                  "account": {                      "Ref": "AWS::AccountId"                  }              }          ]      }  }

The post-obit line may differ depending on your secret's name:

"arn:aws:secretsmanager:${region}:${account}:secret:rapidapi-RLE73o"

Y'all can double-check the value by clicking on the secret on the Secrets Manager page.

secrets manager arn

The PolicyDocument object should look like the code below.

"PolicyDocument": {     "Version": "2012-10-17",     "Statement": [         {             "Effect": "Let",             "Action": [                 "logs:CreateLogGroup",                 "logs:CreateLogStream",                 "logs:PutLogEvents"             ],             "Resource": {                 "Fn::Sub": [                     "arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*",                     {                         "region": {                             "Ref": "AWS::Region"                         },                         "account": {                             "Ref": "AWS::AccountId"                         },                         "lambda": {                             "Ref": "LambdaFunction"                         }                     }                 ]             }         },         {             "Effect": "Allow",             "Action": [                 "secretsmanager:GetSecretValue"             ],             "Resources": {                 "Fn::Sub": [                     "arn:aws:secretsmanager:${region}:${account}:secret:rapidapi-RLE73o",                     {                         "region": {                             "Ref": "AWS::Region"                         },                         "account": {                             "Ref": "AWS::AccountId"                         }                     }                 ]             }         }     ] }

This the access rights granted, we are ready to initialize the deployment procedure.

half dozen. Deploy to Amplify Hosting

First, push the changes that you have made to your Git repository.

We are now ready to deploy our application.

In the project root, add together hosting to services with the control below.

dilate add hosting

Again, select the two options below when prompted that are displayed in teal.

prompts for adding hosting

A browser will open.Connect your Github repository by selecting theConnect App push button, choosing Github, authorizing Github, and selecting your forked repository.

selecting github repository

Select themaster co-operative.

Create a new service role if needed. Use the defaults.

Create a new environs named "master".

On the next page deploy the application and watch the build procedure.

build progress for amplify app

Back in the concluding, strikingEnter to terminate the command prompt. Y'all tin can visit the link on the build page when the app is done to view the application!

final app deployed on amplify

One of the advantages of using the Amplify-CLI and Amplify Panel is having the ability to run builds when new code is pushed to the Github repository. This deployment requires a little understanding of AWS, but in the end there are benefits to utilizing their services.

To not incur usage charges, delete resources and resources groups on AWS.

6. How to deploy a React App on Azure

Azure has static hosting capabilities and web awarding capabilities (every bit well as many other deject services). Recently, they added a Static Spider web Appresource that is geared towards frontend frameworks like React, Angular, Vue, and static publishing frameworks similar Gatsby and Next. Furthermore, the resource tin can be integrated with Github to brand the workflow easier.

It truly is easier if you are using VSCode to set upward your Azure projects. They have many plugins that tin can save y'all time. Therefore, this deployment requires that you lot have;

  • Visual Studio Code installed
  • An Azure account with an agile subscription. Create an business relationship here.
  • Azure Functions extension for Visual Studio Code

Follow the forking instructions above.

ane. Configure an Azure Function in Project

Open upwardly the forked projection in Visual Studio Code.

Create a new empty folder at the root of the project named api/.

Open up the command palette (press F1) and blazon in Azure Functions: Create New Project

Side by side, click Scan in the dropdown and select the emptyapi folder.

You lot will be asked to choose a language. Select Javascript.

Then, selectHTTPTrigger for the template and name the function "weather".

In this case, nosotros will deploy a web application.

You will need to take an business relationship with Azure. Y'all tin can sign up here.

Next, for this instance, select Anonymous admission.

Finally, add a road annunciation so we tin can easily call the function. Open up upwardsapi/conditions/function.json and add,

"route":"weather"

nether methods. The file should now read;

{   "bindings": [     {       "authLevel": "anonymous",       "type": "httpTrigger",       "direction": "in",       "proper name": "req",       "methods": [         "get",         "mail"       ],       "route": "conditions"   // new     },     {       "type": "http",       "direction": "out",       "name": "res"     }   ] }

2. Add API Function

In an open terminal, alter directories intoapi. So install Axios withnpm install axios --save.

Side by side, remove the lawmaking within ofapi/weather/index.js and replace information technology with the code below.

const axios = require('axios')  module.exports = async function (context, req) {      if (req.method !== "POST") {         context.res = {             condition: 405,             torso: 'Method non allowed'         }     }      const { location } = req.trunk      const encodedLocation = encodeURIComponent(location)      endeavor {         // Telephone call the Conditions API         const { information } = await axios({             method: "Go",             url: `https://aerisweather1.p.rapidapi.com/observations/${encodedLocation}`,             headers: {                 "content-type": "application/octet-stream",                 "x-rapidapi-host": "aerisweather1.p.rapidapi.com",                 "ten-rapidapi-key": procedure.env["RAPIDAPI_KEY"],                 "useQueryString": true             }         })          // Pull the information that we need from the Conditions API response         const weatherData = {             weather condition: information.response.ob.weather,             tempC: data.response.ob.tempC,             tempF: data.response.ob.tempF         }         // Return the data object         context.res = {             trunk: weatherData         }     } catch (e) {         console.log(e)          context.res = {             condition: 500,             body: "An fault occurred"         }     } }

Azure uses acontext object to render theres object. Virtually aspects are pretty standard in terms of making an API call to the Aeris Weather API and returning the information. Also, there are comments in the code that particular what the function is doing

3. Deploy Static Web App on Azure

Button your changes to the forked Git repository.

Navigate to your Azure portal and create a new resources.

Search forStatic Web App

search for static web app

SelectCreate.

You will demand to make a new resource group, choice a proper name, select a resource region, and qualify Azure to access your Github business relationship.

And then select your account and the repository name for the forked repository. Click on the master co-operative.

configure new resource

Before creating the resources click on Side by side: Build. Enter the values in the prototype to tell the static spider web app where to notice certain resource. Make sure your values lucifer the ones in the prototype.

build settings

Finally, click Review + Create. The resource is created and a build is initiated in your repository on Github. You tin can view the build process by going to the resource on Azure and clicking on the popup link (" T hank you for using Azure Static Web App! We have not received any content for your site nonetheless. Click hither to check the status of your GitHub Action runs." ).

If you follow the link y'all can run into when your Github activeness is completed. Next, get back to the resource folio and click on the URL link in the dashboard.

url for new app

The browser will open displaying our weather condition app, only we haven't added the API key to the environment even so.

four. Add API Key

On the static app resource page (same folio where the URL is found) click on Configuration in the sidebar. Then selectAdd to add a new value.

The value name needs to add the name that we used in the app for deployment ("RAPIDAPI_KEY").

Insert your API fundamental into the value field. Subsequently hit "OK", clickRelieve at the tiptop of theConfiguration pane.

Caput back over to the app and test out a location.

The environs variable should now be loaded and weather information can exist fetched!

final azure deployment app

To not incur usage charges, delete resources and resources groups on the Azure portal.

seven. How to deploy a React App on Netlify

Netlify makes things easier. With Netlify, we can configure serverless functions in our project that Netlify converts to AWS Lambda functions. That means that the serverless function set-up is simplified and nosotros can make an easy call to a serverless route for our weather app data.

There is a bit of configuration that nosotros need to have care of get-go, merely I remember you lot volition agree that in that location are clear benefits to this process.

Sign up for an account on Netlify.

Follow the forking instructions above.

Open up the project with your text editor.

Call back, nosotros don't currently accept an API telephone call in place because we can't secure our API key on the forepart. Therefore, we need to implement an API call.

1. Add Call to Weather API

In the project, root create the folder functions and inside of the folder add the fileweather condition.js.

Add the below code toconditions.js.

const axios = require('axios');  exports.handler = async function (event, context) {     let RAPIDAPI_KEY;      // Admission API key from environment     RAPIDAPI_KEY = procedure.env.RAPIDAPI_KEY      // Validate HTTP request type     if (event.httpMethod !== "Postal service") {         render {             statusCode: 405,             body: "Method Not Allowed"         };     }      // Get the body of the request     const trunk = JSON.parse(event.body)      // Assign the location value to the variable location from the body object     const { location } = body      // Encode the variable and then we tin can transport the location in a URL     const encodedLocation = encodeURIComponent(location)      endeavor {         // Telephone call the Weather API         const { data } = await axios({             method: "Go",             url: `https://aerisweather1.p.rapidapi.com/observations/${encodedLocation}`,             headers: {                 "content-type": "application/octet-stream",                 "x-rapidapi-host": "aerisweather1.p.rapidapi.com",                 "x-rapidapi-key": RAPIDAPI_KEY,                 "useQueryString": true             }         })          // Pull the information that we need from the Atmospheric condition API response         const weatherData = {             conditions: data.response.ob.weather,             tempC: data.response.ob.tempC,             tempF: data.response.ob.tempF         }          // Return the data object         return {             statusCode: 200,             body: JSON.stringify(weatherData)         }     } catch (e) {         console.log(eastward)         render {             statusCode: 500,             trunk: 'Server mistake.'         }     } }

I left comments in the code to explain what is happening in the function. You tin can read more than about Netlify functions on their documentation page.

Next, on line 18 ofApp.js, modify the URL to /.netlify/functions/conditions

2. Add togethernetlify.toml file

This is a configuration file that Netlify needs so information technology can plough your function files into serverless functions.

Create thenetlify.toml file at the project root and add together the code below.

[build]   functions = "functions"

3. Deploy to Netlify

Button the changes to the repository.

$ git add netlify.toml functions/conditions.js src/App.js $ git commit -m "add serverless role" $ git button

Log in to Netlify.

Click the button on the page that reads New Site from Git.

You will have to authorize Netlify to access your Github repositories.

After authorization, there will be a list of your Github repositories. Select the 1 that we just created.

On the next page, it will enquire for a build pace and publish directory. We practise not accept a build step and so leave that blank.

Addpublic to the publish directory input. Deploy the site.

It will build quickly and there will exist a link for your new site!

If you click on the link yous should see our app, but it won't work however because nosotros didn't add together our API key to the environment variables.

4. Add API Primal to Environment Variables

InSite Settings, select the Build & Deploy tab. Whorl towards the bottom and add together our key to the environment variables section.

add RAPIDAPI_KEY to environment variables on netlify

Remember, information technology needs to equal the value that we placed in the serverless function.

Subsequently adding the environment variable y'all can trigger a new deploy from theDeploys tab.

The application should be functioning at the URL yous are provided!

To not incur usage charges, deactivate or delete the site.

Conclusion

The application morphed into almost seven unlike applications throughout the process. Some aspects change when we factor in how we desire to deploy and how to handle things like security. Understanding the end environment can salve you fourth dimension later if you lot can develop the needed structure ahead of fourth dimension.

Furthermore, choosing sure deployment services can afford improve workflows. Or, you can choose an choice that gives you control of the end surround and create your own custom workflow.

The probability that your React app will need to muffle secrets, API-keys, etc. is fairly loftier. Therefore, y'all should know some of the options that tin can offer this protection.

Deploying an app brings forth new challenges, but the first time or two tends to be the most hard. Soon, you develop a meliorate understanding and can quickly set upward application deployments that fit your needs. If you accept whatever questions please leave a comment below!

chaneyflovedint.blogspot.com

Source: https://rapidapi.com/blog/how-to-deploy-a-react-app/

0 Response to "Can a React Page Work if Uploaded to a Shared Virtual Host"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel