- React и firebase —это всё, что вам нужно для хостинга веб-приложений
- Итак, вот описание того, что мы будем делать сегодня:
- Create the React application and enter the project folder through terminal
- Add the Homepage to your package.json File
- Actually adding Cognito Sign-in and Hosting
- Add the Build File Contents to public_html
- A note on filezilla
- A simple react example
- Adding your settings to the react project and publishing to your website
- Before we get started we need a couple of things set up on your computer
- Diving right in
- Further challenges
- Heroku
- Host a react based website free of cost with firebase hosting and connect with your own domain
- Hosting your react application with aws in 30 minutes
- Surge
- Troubleshooting react-enabled pages
- Using react
- Vercel
- You’re super done.
- Возвращаемся к react, как и обещали
- Краткая история
- Часть 1 — создание react-приложения
- Часть 2 — настройка firebase
- Часть 3 — firebase & react
- Render
- Conclusion
- Заключение
React и firebase —это всё, что вам нужно для хостинга веб-приложений
Перевод статьи Ashish Nandan Singh: React and Firebase are all you need to host your web apps
Истории многих современных веб-сайтов заканчиваются печально из-за большого числа технологий, включенных в процесс, и неудачно выбранного подхода к разработке.
Поэтому перед нами встает главный вопрос — как сделать это путешествие менее болезненным или даже, не побоюсь этого слова, более плодотворным и эффективным. В идеальной вселенной мы должны выбирать хорошо зарекомендовавшие себя технологии, которые, ко всему прочему, должны еще активно поддерживаться сообществом разработчиков.
В этой статье мы рассмотрим две технологии, которые как раз успели хорошо зарекомендовать себя на рынке веб-разработки и активно поддерживаются сообществом — эти два фактора помогут нам создавать веб-приложения более эффективно.
Итак, вот описание того, что мы будем делать сегодня:
Когда я впервые задеплоил (загрузил) React-приложение на хостинг Firebase и попытался запустить его, я столкнулся с рядом трудностей. Поэтому решил, что было бы неплохо изложить этот опыт в исчерпывающем руководстве, которым и спешу поделиться с сообществом. Итак, давайте приступим.
Эта статья состоит из трех частей:1. Создание простейшего приложения на React 2. Заведение Firebase аккаунта 3. Подключение Firebase-консоли к созданному React-приложению
Create the React application and enter the project folder through terminal
Enter the terminal and locate your folder where you store applications. I suggest a folder named “dev”.
npx create-react-app project-name && cd project-namenpm -g install create-react-app
create-react-app project-nameHere we create a React application based on the boilerplate. “npx” is a Node tool which uses the npm server for calling on remote packages. The second code snippet installs create-react-app locally withnpm -g install create-react-appand then creates the application. I suggest using npx to always be up-to-date with create-react-app.
Add the Homepage to your package.json File
Next, open up your React App. Open up your package.json file and add a «homepage» attribute like so:
Actually adding Cognito Sign-in and Hosting
For the last step, we’ll add AWS Cognito to our project through AWS MobileHub Console. You can also check out Hosting which is already enabled by default.
To test Hosting, click the feature in your console and click the URL you’ve been provided. The content here is a template by AWS, but you’ll overwrite it with the React application soon.
Add the Build File Contents to public_html
Navigate to the build file in your app’s root directory. Open it up and select all the contents inside the build file. If you upload the entire build file itself, the process will not work.
Once you’ve copied all the contents inside the build file, upload them into public_html.
A note on filezilla
I know a lot of folks like to use FileZilla to deploy and host their custom web apps. I found it to be unnecessary for my purposes, but should you choose, you can:
A simple react example
The following example creates a very simple React element and displays it on an HTML page.
First, create a file named react.html, and then copy and paste the following code into the file:
Adding your settings to the react project and publishing to your website
In your terminal, you can at any time use awsmobile pull or awsmobile push to respectively pull your changes from AWS MobileHub Console online to your application, or push your local changes done through the awsmobile CLI in the terminal.
For this use case we want to fetch the changes we made. Go back to your terminal and type
Back in VS Code, you’ll see that your project now has been modified. You can check your local configurations in ./awsmobile/backend/mobile-hub-project.yml
Also, in ./package.json you’ll find the two highlighted libraries being added by awsmobile init which we did earlier.
We’ll now use these to wrap our application in a Cognito login window. Open ./src/index.js and modify this:
to this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import awsMobile from './aws-exports';
import Amplify from 'aws-amplify';
import { withAuthenticator } from "aws-amplify-react"Amplify.configure(awsMobile);
const AppWithAuth = withAuthenticator(App)ReactDOM.render(<AppWithAuth />, document.getElementById('root'));
registerServiceWorker();
And you’re done! Try to run your application from your terminal with
npm startand see it be loaded into the browser with a sleek GUI created by AWS:
Before we get started we need a couple of things set up on your computer
Node 8.x environment installed on your computer
An AWS Free Tier account.
Install the AWS CLI (Command Line Interface) to call AWS services directly from your console
Diving right in
While working on a personal project called Punchstarter, a Kickstarter clone app, I struggled to find any good documentation on how to host a custom app on my own domain with cPanel. I hope this will serve useful to many.
Further challenges
Use the aws-amplify authentication documentation to add a signout button to your application.
Hint: You’ll need to import Auth and call its signOut function.
import { Auth } from aws-amplify-reactAdd your custom domain name to the hosted websiteThis is done through CloudFront, which you can access in MobileHub “Hosting and Streaming”. Read the docs provided if you want assitance:
Heroku
Heroku is a cloud application platform that has attracted a large number of developers since its launch in 2007. One reason for this is that it supports most programming languages, including the likes of Go, Node.js, Clojure, and more.
Host a react based website free of cost with firebase hosting and connect with your own domain
Yes you read it right “Free of Cost” , now you can host your website using Firebase Hosting service without paying anything, as long as your usage does not exceed those Free Hosting Parameters. And believe me for a beginner this is more than enough. When your website become popular and you need more resources, you can just simply switch to any paid plan. As mentioned in Firebase official site “ Start for free, then pay as you go”.
In this article we are going to demo it step by step by creating a basic react application. You can use any framework or basic HTML, JavaScript to develop you website. Lets Start …
Step 1: Create a new project in Firebase Console
Login into Firebase Console with your gmail id, and click on Add Project to create a new project.
In the popup insert your Project Name, it will auto-generate a Project ID, which you can edit also. Accept all terms & conditions and press Create Project button.
Our Firebase project is ready now, Lets create a basic React app.
Step 2: Download and install Node.js
Download Node.js from below site and install.
Step 3: Install yarn node package
Once Node.js successfully installed, Open your terminal or command prompt and run below command
npm i --global yarnStep 4: Create a new React App
From command prompt use below command to create a new react app —
npx create-react-app <your_app_name>Our basic react app is created with basic files and packages installed.
Step 5: Install firebase-tools npm package
Use below command to install firebase-tools package from command prompt
npm install -g firebase-toolsStep 6: Log into Firebase from command prompt
Once firebase-tools is installed, use below command to log into Firebase —
firebase loginStep 7: Initialize Firebase Project
Now we need to initiate Firebase project inside our project folder. From command prompt navigate inside your React application project folder and run below command —
firebase initOnce you run that command it will go through few project setup steps and questions —
? Are you ready to proceed? Yes? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choices.Navigate by up and down arrow key and select “Hosting: Configure and deploy Firebase Hosting sites” option by pressing space bar.
In next step it will ask you to select a Firebase project. If you don’t see your Firebase project ( the one your created at step 1) listed there, just select “don’t setup a default project” option. Later you can use “firebase use —add” command to link your react project with Firebase project.
Next it will ask us for the location of public folder. Firebase hosting expects all content of web application inside a “Public” folder. Inside our project folder we have a folder named Public. But we are not going to mention that as our public folder of Firebase project. Because when we build a React project it puts all it’s content inside a folder called “build”. So we are going to mention build as our firebase project public folder.
And at last it’s going to ask us if we want configure a single-page app. Just type Y and press enter.
Our firebase project is initialized now. But as I mentioned above, if you not able to setup any default project earlier, we need to setup it now. If you already selected a default project earlier then skip this below command.
firebase use --addStep 8: Build your application
Run below command to build your application
yarn buildIt will create a build folder inside our project folder with all static files of our application.
Step 9: Deploy your application
Now our firebase project is ready to deploy in Firebase Hosting. Just use below command to deploy it —
firebase deployIf you got a screenshot like below with message “Deploy complete!”, that’s it you have successfully deployed your first web application in Firebase Hosting … awesome.
Now open that Hosting URL link in any browser and hurrah… you will able to see your hosted web application.
We have already deployed our web application in Firebase hosting successfully. Now if you have a registered domain and you like to connect your app with that domain then continue with the next step.
Step 10: Connect to your own domain
Open Firebase Console and select Hosting from left hand side menu.
Now click on connect domain button at the right hand side.
In Connect Domain window enter the domain you own and click Continue.
Now in verify ownership step you can see it instructing you to add “TXT” record to your DNS provider for verification purpose.
Now just copy the Value text.
I brought my domain from GoDaddy, if you brought from any other service provider then just log into that service provider’s site and open domain maintenance page.
Click on DNS button.
You will see a set of records are already defined there. Now click on ADD button.
Now under Type select TXT, put value of Host field as “@”, under TXT Value field paste the value you copied from your Firebase console and then click Save.
Once the record successfully saved then go back to your Firebase console and click the Verify button. After successful verification you will see a screen like below —
We need to add another 2 records under our DNS settings. Value column will contain IP addresses which we need to add.
First remove any existing A or AAAA records from your DNS Management.
Now add A records same way how we added TXT record earlier.
Type: A
Host: @
Points to: copied value from Firebase console (IP address)
Once both A records successfully added then go back to Firebase Console and click on Finish button. Now your Firebase Hosting dashboard will show your custom domain there.
You may see status against your custom domain is “Pending”. It is because Firebase take few hours to complete all the processes. But it won’t stop you to open your domain in browser. So just click on the link there or type your domain name on browser and you will see your hosted website.
Initially you may see “Your Connection is not Private” error on browser. Just ignore it and continue by clicking Advanced button. It happens because it take some time for Firebase to activate the SSL certificate.
Yahoo… our website with custom domain is hosted now.
happy coding …
Hosting your react application with aws in 30 minutes
This tutorial is very image heavy and targeted towards complete beginners. It explains how you can host your React application on a website, with a complete authorization system. It invokes the power of AWS MobileHub through the Mobilehub CLI (Command Line Interface). The tutorial requires no skills with AWS services and will also show you to set up a React boilerplate application.
If you already have a React application, you can skip to section 2 where we install awsmobile-cli and add it to our application.
Surge
Surge is another fast way to deploy frontend projects. Compared to other CLIs, it requires much less configuration, is easy to deploy, and allows you to create a Surge account directly from the terminal when using it for the first time.
To deploy the latest build of the project, run the following command in the project root directory.
npm run build
To install Surge CLI globally:
npm install -g surge
Run surge inside the build folder.
cd build surge
Follow the prompts. First, you’ll be asked for an email and password.
Welcome to surge! (surge.sh)
Login (or create surge account) by entering email & password. email: [email protected] password:Before filling in any other prompts, it’s a good idea to confirm your Surge account.
In the terminal, you’ll be asked to confirm your project directory. Hit Enter.
You’ll see the domain of your project. Again, hit Enter.
project: D:codereact-example-deploybuild domain: tremendous-person.surge.sh
This will publish your application.
Success! - Published to outstanding-scent.surge.sh
You might want to rename index.html to 200.html in your build folder before surging to support the HTML5 pushState API, which is used by React libraries for routing.
If you run into an aborted error, try to run the surge command again.
Troubleshooting react-enabled pages
Because React is JavaScript-based and runs on the client, you can use a web browser to troubleshoot and diagnose problems. Many web browsers include a console that provides detailed information about the JavaScript run-time environment. This information is extremely helpful for debugging applications:
Using react
To use React in a web page, all you have to do is include two JavaScript files. There are a few ways to do this:
After you include the React library files in a web page, you have access to all of React’s features.
Vercel
Vercel is a revolutionary serverless deployment service designed for React, Angular, Vue, and other JavaScript libraries. You can easily import projects from GitLab or Bitbucket with Vercel. Automatic SSL is one of the many cool features it offers.
To deploy Vercel, create a new account. You can quickly login using OAuth.
You’re super done.
That’s it! Navigate to your domain address in the browser and you should see your fully functioning web app.
Возвращаемся к react, как и обещали
Помните, что в самом начале в части о React, я сказал, что мы еще вернемся к нему, чтобы сделать последний шаг? Так вот, этот момент настал.
Перейдите в папку, в которой создано приложение.
Один из принципов работы React — возможность кастомизировать сборку, то есть создавать очень сокращенную версию всех использованных библиотек, что оказывается крайне полезным, если в вашем приложении их много.
Чтобы получить такую миниатюрную и сжатую версию, мы можем набрать в терминале всего одну очень полезную команду:
$ npm run buildОна создаст новую папку с именем build в каталоге приложения . Эта папка содержит несколько файлов, которые являются наиболее важными частями всего вашего приложения React.
Краткая история
В 2022 году был запущен стартап под названием Envolve, который позднее прославился как Firebase. Envolve был продуктом, который предоставлял API, позволявший разработчикам интегрировать функции онлайн-чата на свой веб-сайт.
Компания заметила, что разработчики использовали Envolve не только для обмена сообщениями через чат, но и для синхронизации данных пользователей приложений в режиме реального времени, таких как состояние игры, к примеру.
Это заставило основателей Envolve, Джеймса Тамплина и Эндрю Ли отделить систему чата и режим работы в реальном времени. В апреле 2022 года Firebase была создана как отдельная компания, которая предоставляла Backend-as-a-Service функциональность в реальном времени.
После того как продукт был приобретен компанией Google в 2022 году, Firebase быстро превратился в многофункционального гиганта — платформу для разработки мобильных и веб-приложений, статус которой он сохраняет и по сей день.
Всю суть Firebase моно передать в одной простой картинке:
Часть 1 — создание react-приложения
Вероятно, вы знаете, что лучший способ создать базовый шаблон для приложения React — это команда create-react-app myapp. Она не только создает простейший шаблон, но также добавляет зависимости, необходимые для запуска React.
Если вы пока не осознаете истинную магию и настоящюю силу этой одной строки, попробуйте создать каталог для React с нуля. Вот тогда вы сможете прочувствовать всю боль построения приложения с нуля. Низкий поклон тем разработчиком, которые смогли нас избавить от всей этой мороки благодаря созданию одной простой команды.
Чтобы начать работу, нам нужно запустить утилиту create-react-app
$ npm install -g create-react-appФлаг -g в приведенной выше команде устанавливает пакетный менеджер NPM на машине глобально.
Как только это будет готово, мы воспользуемся им, чтобы получить базовый шаблон для React-приложения.
$ create-react-app myappС помощью этой команды мы создадим папку с именем myapp. Теперь нам нужно перейти в папку и выполнить приведенную ниже команду:
$ cd myapp
$ npm startПосле того как вы введете команду выше, локальный сервер разработки должен запустить и отобразить стартовый экран приложения React по адресу localhost: 3000
Надеюсь, у вас получилось это выполнить легко и быстро. Теперь у нас остался последний шаг, который нужно сделать для создания веб-приложения. Но к нему мы вернемся позже. А сейчас давайте рассмотрим Firebase. После этого мы снова поговорим о React.
Часть 2 — настройка firebase
Прежде чем мы погрузимся в настройки, необходимо понять, что же из себя представляет Firebase.
Firebase — это платформа для разработки мобильных и веб-приложений. Она предоставляет разработчикам множество инструментов и услуг, которые помогают им разрабатывать высококачественные приложения, расширять базу пользователей и получать больше прибыли.
Давайте посмотрим на историю Firebase, прежде чем переходить к настройкам.
Часть 3 — firebase & react
Нажмите на функцию «Добавить Firebase» в свое веб-приложение. Вы получите диалоговое окно с фрагментом кода.
Добавьте этот фрагмент кода в самую нижнюю часть файла index.html своего проекта. Убедитесь, что эта часть кода расположена перед всеми остальными скриптами файла index.html.
Если вы внимательно посмотрите на изображение выше, то заметите ссылки в самом низу. Нажмите на первую ссылку и посмотрите «Начало работы с Firebase для веб-приложений» (Get Started with Firebase for Web Apps). Перед вами появится экран, который представлен ниже:
Нажмите «Начать» (Get started).
Перейдите в свой корневой каталог и введите в терминал команду из картинки выше. Она загрузит инструменты Firebase на ваш компьютер.
Следующий и последний шаг — инициализировать Firebase и загрузить исходный код в каталог Firebase.
Как только вы нажмете Finish и выполните все шаги, перечисленные выше и введете всех указанные там команды в терминал, на экране вашего компьютера должен появиться список последних записей развертывания сайта:
Render
Render, the winner of Startup Battlefield at Disrupt SF 2022, is a newer cloud platform that is rising in popularity.
Conclusion
Now that we’ve discussed eight different ways to deploy React, you should try out as many as you can to determine which one best aligns with your deployment requirements. After all, they’re free to use.
For a good next step, try to add custom domains to your deployed application. It’s good to have a distinctive domain for projects, which have different ways to add a custom domain — some easy, some relatively complex.
Until next time, happy coding!
Заключение
Если вы внимательно следовали всем шагам и параллельно почитывали официальную документацию, то для вас в этом не было ничего сложного.
По моим личным ощущениям, Firebase уже произвела революцию в том, как разработчики тестируют и используют хостинг как услугу. Это гораздо более простой и более легкий способ эффективного хостинга приложений, который помогает не вдаваться в детали и тонкости настройки хостинга.

