Translate

Wednesday, April 14, 2021

Deploying your React App to HostGator, Quick and Painless

 


A few weeks ago, I had finished development on my personal portfolio site (at least as far as I stomach in one sitting) and decided it had been time to send it out on the internet. This was my first time deploying an application online, and while many of my friends and colleagues deployed their first sites using Heroku, I wanted the advantage of a no-downtime hosting service to properly host my portfolio.

I ended up using HostGator, one of the longest-standing hosting services out there. It’s a shared hosting service, meaning that it handles multiple websites off of one server connected to the web. One downside of this is often that if the request load spikes on a couple of of the websites on the server, you'll experience delays in responses for your domain also. The upside, however, is that it's cheap and quiet enough for smaller scale low-traffic sites.

There are a few steps to fixing a site deployment: domain setup, server hosting, connection, and deployment. I knew next to zilch about server setup going into this, so I will be able to do my best to get out the steps and supply reasoning/context where I had to try to do my research. I hope you discover this useful!

Domain Setup

First and foremost, the highlight of any website is its name. You can’t have a heavy-traffic game-changing webpage without a catchy, snazzy, on-brand name. There’s a particularly great deal of domain hosting services out there with domains available for purchase. Personally, I used Hover. it had been cheap, easy enough for my purposes, and that I was lucky to be ready to grab the griffinpoole.com domain for my personal site. it had been as simple as this: make an account, look for a website name that I wanted, and found out the subscription.
What are a website and the way does it work, you ask? I do know that you simply didn’t ask, but I’m happy to elucidate it anyway. Domain names are essentially aliases for your computer's online ID, your IP address. once you found out a DNS server, you instruct a DNS database to pair your name with an IP address. This IP is often on your pc (not recommended), from a hosting service, or from a corporation server.


Because of this, once you host an internet site, you regularly are paying for 2 separate features: the DNS servers providing you thereupon sleek, stylish name and therefore the server host providing you with the always-on computer power. thereon note, let’s mention subsequent a part of the deployment.



Server Hosting
Next, we'd like a computer to host and serve your webpage files for serving calls in response to domain requests. Technically, this will be done from your own computer, but unless you…
  1. Know alright what you're doing
  2. Are okay with leaving the pc on all the time
  3. Are okay with calls from your power service as your super awesome site scales up
…it is more advised to buy a specialized service. Hosting services make they're living off of fixing, optimizing, and maintaining the hardware required for website hosting. Also, they’re pretty fairly priced all things considered. Generally speaking, they’re the simplest thing for the work.
There are tons of hosting services out there, and in contrast to domain hosting, they really have a spread of differences which will make buying them difficult. the most important three that I can provide advice on are:
  • Shared Hosting: This I discussed earlier, but essentially one server hosts multiple websites. While having the advantage of much lower cost, it's the downside of sharing the negative effects of high server load across all sites on the server. this is often usually mitigated by fixing traffic limits for shared host sites to avoid one site outcompeting others on its server. Good for smaller-scale low-traffic sites or new sites! Sites can always be scaled up to different services as required.
  • Dedicated Hosting: For larger-scale sites, you'll get a fanatical hosting server. this is often exactly because it sounds, the server is all yours and you've got full root and administrative access to the server settings. The upsides of this are all traffic on the server is exclusive to your site(s). this suggests potentially faster responses, custom traffic tracking, and therefore the ability to customize server settings to your purposes. The downsides of this are obviously higher costs and therefore the got to found out more on your own. Although, these services do are available in managed versions (also at a better cost).
  • Cloud Hosting: a more modern hosting method, cloud hosting hosts server data on a cloud-based system, meaning that users might not necessarily have any control over where their data is stored. Cloud hosting services usually offer pay-by-use services, meaning that users only buy the resources their site uses (number of visits, processing power utilized, space for storing, etc.). This pay-by-use is one advantage of the service, the downsides being the de-centralization of knowledge could also be problematic for users with security concerns.

For my purposes, I used a shared-hosting service through HostGator. almost like the Hover purchase, it had been as easy as fixing an account, choosing an idea that most closely fits your needs, and buying the plan. HostGator provides a couple of shared hosting plans, with the main differences being traffic support, number of domain names, and program optimization (SEO).
Now that we've purchased our name and our server space, we will found out the connection between the two…


Connecting Domain to Server

Connecting a website to a server is comparatively simple to try to do, but it did take me longer than I care to admit to working out the way to roll in the hay the primary time. Most of it had been me not knowing the terminology I needed to research to work out what I used to be doing, something which I will be able to attempt to mitigate for you all here.

DNS servers concentrate on mapping domain names and addresses to IP addresses and other domain names (it gets crazy). they are doing this through something called ‘records’. Records are very simple entries that say ‘you get this address, your route to the present address. they are available during a few forms:

  • A Records (Address Record): the elemental record. These records point to a website or subdomain to an IP address. during a lot of cases (mine included), this is often the sole record you’ll get to use. you'll specify the first naked domain (@), a wildcard for all domains(*), and subdomains.
  • CNAME Records: CNAME records, as I understand them, are kind of like aliases. They intercept host requests and direct them to other hostnames. I personally haven’t made use of them, but they will be used for more complicated server management systems.
  • MX Records: These records specify server locations for receiving email. Uniquely, these are assigned priority values so that if one server can’t handle the mail request, it can attend to a special server. Some mail setups have just one server et al. have many more.
  • TXT Records: These records are often wont to store text information to be returned for the asking. they will be used for a spread of security purposes, but typically have niche uses.

So how can we do it? Again, for our purposes, we just got to point requests for our name to the IP of the server provided us by HostGator. On HostGator, you would like to form your primary domain or an addon domain for the name you’ve purchased. this will be done by getting to your HostGator portal, selecting the ‘Hosting’ tab, and setting your primary name there.



Next, we'd like the IP address of our server. this may vary from service to service, but on HostGator, you'll access this by getting to the instrument panel (cPanel) and checking the sidebar for the location IP. this is often also an honest time to form sure that your primary domain matches your purchased name.
Now that you simply have the IP address, we will attend to our Hover account and make a group of records for our domain.


Above I’ve added two simple A records, both pointing to the IP provided me by HostGator.

And that’s it! With those records, we’ve successfully directed our griffinpoole.com requests to the right IP address. The last item we'd like to try to do is put the files for our website on the server to be sent upon request.

Adding the Webpage

This is another step that will differ somewhat between services, but generally, a hosting service will route your IP and domain to given folders supported by the request type. For HostGator, this is often a folder called public_html.
In my case, I built an internet site in React, so first I ran ‘npm run build’ in my project directory to make an optimized production build for my site.
These build files, in their entirety, are to be uploaded into the public_html folder on HostGator.


Note the CGI-bin folder. This folder is within the directory by default and may be left alone. For the curious, it's meant to be a folder to store scripts that interact with the online browser for functionality on the frontend. Generally, the system is obsolete because the same features are provided by Javascript in the latest apps, but the tools are always there for any who want to use them.

At now, our website SHOULD be found out. These files are going to be properly sent to a browser in response to an HTTP request to griffinpoole.com. But there was another problem that I specifically needed to deal with. rather than serving up different documents in response to different URL requests, I used React-Router to handle all of my website's routing. This worked perfectly fine if a user visited the basis domain and clicked around across the location. The JS on the front could handle the page changes. When a user tried to directly URL request to or refresh on a page that wasn't the house page, however, I’d get a directory not found error.

The problem was that on a page refresh/request, HostGator would receive an invitation to a subdirectory (for example griffinpoole.com/project) that didn’t exist. This worked fine when the page was already loaded because the frontend JS could intercept the URL and render the page as required. However, on refresh, the present JS would get dropped and HostGator would be asked for a doc from a directory that didn’t exist.

To solve this, I had to dive deep into the Apache server documentation…
I actually found a code snippet off of a Stack Overflow response that solved the matter completely.



This code must be put during a .htaccess file that sits within the same public_html directory. Once this is often done, the webpage works completely. We’re done! But this wouldn’t be one among my blogs if I didn’t enter unnecessary detail a few problems solved… so here’s why this works.

HostGator runs their servers with Apache, and during a shared server setting, server-wide configuration settings are inaccessible by us as users. Cue the .htaccess file. An Apache server running a website will recognize a .htaccess file and overwrite the default configurations with the settings laid out in the file. this enables dedicated servers to possess domain-specific configurations, and it allows us to run Apache settings on our shared portion of the server.

So what are we doing here? Essentially what we’re doing is catching the incoming URL, checking if it fails to match an existing file address or directory address, then rerouting to index.html on failure. HostGator’s Apache environment comes with some apache modules plugged in. The one we use here is mod_rewrite. To the simplest of my understanding, here’s how it works.
Apache’s mod_rewrite sets a series of Rules and Conditions for URLs and file addresses matched against regular expressions. In other words, it intercepts the incoming requests with Apache server variables included and may control the file addresses that really get returned. Here’s how the above code works:

  1. The ‘ ‘<IfModule mod_rewrite.c>’’ tags specify that the code inside is mere to be run if the environment is running with the rewrite module installed. this may always be true on the HostGator servers but is sweet practice to avoid bizarre errors if changing hosting services.
  2. RewriteEngine on’ activates the rewrite module. This only must be run once.
  3. RewriteBase /’ defines the bottom where the directory route to-be-matched will start from. for instance, take a route request of ‘griffinpoole.com/projects/first’. If your base is ‘/’, then everything after the basis domain is going to be matched against the regex (‘/projects/first’). If your base is ‘/projects’, then your regex is going to be compared against ‘/first’.
  4. RewriteRule ^index\.html$ - [L]’ This line sets a rule to be followed if the URL matches the provided regex. The ‘^index\.html$’ regex will match only the precise file address ‘index.html’. The [L] flag is that the instruction to be followed here. The L flag just specifies that this is often the ‘Last’ rule. In other words, if the file address matches ‘index.html’, skip the remainder of the instructions.
  5. RewriteCond %{REQUEST_FILENAME} !-for This sets a condition for subsequent rule. The condition first accesses the REQUEST_FILENAME variable provided by Apache that holds the request URL. The -f flag means true if the request finds a legitimate file. The ! flips it. So, this condition says, ‘If the request doesn't find a legitimate file, follow the subsequent rule’.
  6. RewriteCond %{REQUEST_FILENAME} !-d’ This does almost the precise same thing because the previous, but rather than checking for a file, it checks for a directory.
  7. RewriteRule. /index.html [L]’ This last rule is run if a file or directory can’t be found. It matches ANY request and substitutes it for ‘index.html’.
In summary, the .htaccess file is often utilized in this manner to intercept any routes that end in file/directory not found error and may instruct the server to return the index.html response as a default. during this way, the bottom HTML and JS are often sent up, and when React JS reads the URL in-browser, it'll load the right components on the page. Easy!……..

Conclusion

So that got a touch messy at the top, but most of the small print with the .htaccess file editing doesn’t actually need to be understood. It’s just boilerplate code you'll pull from here or off of a StackOverflow posting that’s been fixing an equivalent ReactRouter problems for years now.
All in all, React deployment is often simplified into four steps: Get your domain, get your server, connect them with records, and cargo in your build files. Many of the issues that come alongside it are often troubleshot and googled for straightforward copy-paste solutions. But here, I wanted to supply a comprehensive overview of what goes into web deployment, and an example of a number of the issues which will happen.
Other options for React site deployment include Heroku (if you don’t mind startup times) and Netlify, which I haven’t used, but have heard is extremely popular. Overall, I hope this helped explain the fun and miseries of web deployment, and many thanks for reading!

No comments:

Post a Comment