Now that we have an app that sort-of functions on our local environment, we should start looking into deployment options. You may have noticed that our app doesn't have much in the way of server configuration in our /server.js file. That's no coincidence; our app doesn't run on a server.
In fact, if you compile your app using webpack with the webpack command and then open the index.html file within /dist, you'll see that you have a fully functional app just from static assets. That index.html file has all the assets it needs to run an app without a server because everything is static and all of your data comes from an API call to our backend.
Given that everything is static, it's super easy to host our site. We don't even have to spin up a server to do it; we can simply drop in the files and serve them when someone hits your url. We're going to host these files on Amazon Web Service's (AWS) Simple Storage Service (S3). We will go into detail on these later.
Now we have a functional app. The last thing we need to do in preparation for deployment is change out our hardcoded localhost:4000 values.
To do this, we need to change our webpack.config.js to include a webpack.DefinePlugin.
... module: { ... }, plugins: [ new webpack.DefinePlugin({ "process.env": { API_HOST: JSON.stringify('http://localhost:4000'), SOCKET_HOST: JSON.stringify('ws://localhost:4000/socket') } }) ], ...Now all we have to do is change out every instance of http://localhost:4000 for process.env.API_HOST. We can use ES6 string interpolation (which uses a ${}) to insert a string into an existing string, so your new paths would look something like this: ${API_HOST}/api/users. Also change out the ws://localhost:4000/socket for process.env.SOCKET_HOST.
You'll probably have to run this manually with a find and replace. Keep in mind that string interpolation only works with back ticks (``), not quotes (""). As always, when you change your webpack configuration, you need to restart your server.
One of the reasons we're using S3 rather than a Node server is that S3 is insanely cheap. It's something like 5 cents per gigabyte per month for storage and another 5 cents per gigabyte for data transfer. In other words, you would have to have an insane amount of traffic for the cost to even become noticeable.
Not only that, but this type of architecture can instantly scale to a seemingly-infinite amount of traffic (if you're at a point at which AWS cannot handle your level of traffic, then you shouldn't be reading this tutorial series).
Go to aws.amazon.com and create an account. You'll need to add your credit card as well, but this is going to cost little-to-nothing, so relax.
Then go to your console where you can see all of the tools that AWS has to offer. There are lots and lots of them, and they all have vague and confusing names. All we're going to use for the time being is S3, so go ahead and click on S3.
On the left you'll see a list of your buckets. Think of a bucket as a figurative bucket that holds your files. You can dump all kinds of data in a bucket. We're going to create a new bucket that will hold all of our static files for our frontend app.
Click on the "Create Bucket" button and create a bucket with a name that is unique across all AWS. A good strategy for naming your domain is to give it the name of your domain, since by definition your domain will be unique. Since we're going to host this app at www.phoenixchat.io we can give it that bucket name. Since yours will have to be unique, you'll have to come up with something different, but you get the idea. Go ahead and click Create.
Now you'll see your bucket on the left. On the right you'll see an option for Static Website Hosting. Go ahead and click on that dropdown and select Enable website hosting. Where it says Index Document go ahead and type in index.html and click Save.
The next part is a little bit less obvious. We need to set up Permissions that determine who can access the bucket and what can be done with it. Under Permissions, click on Add bucket policy, after which point you'll see a blank textarea. This text area expects your configuration options in JSON and Amazon gives us a tool to automatically generate this code. On the bottom left of this modal, you should see AWS Policy Generator. Click on that.
Change Select Type of Policy to S3 Bucket Policy.
Change Principal to *, which means "everyone".
For Actions go ahead and check the box for GetObject.
The Amazon Resource Name (ARN) follows a pattern that is shown below the text input. It's something like arn:aws:s3:::<bucket_name>/<key_name>. If your bucket is named www.phoenixchat.io and you want it to apply to everyone your configuration will look like: arn:aws:s3:::www.phoenixchat.io/*
Then click Add Statement, which will show your configuration options in a table. Check them over and make sure they're right and then click Generate Policy.
Copy the JSON that was generated and paste that into the other tab with the empty text area and click Save.
Now we want to send our files to S3. But before we can do that, we need to give ourselves access to S3 through the command line tool (you could upload your files through the website, but it's clunky and can't be done programmatically).
Go back to the AWS console and click on Identity and Access Management.
From here, click on Groups on the left and create a new group. Administrators is a perfectly valid group name, but you can enter any name you like and click Next Step.
Then add the policy AmazonS3FullAccess which you can find by filtering down the options. Then click Next Step to review, and if everything looks right click Create Group.
Now that we have a group, we need to create a user to add to that group. On the left side, click Users, then Create New User. Enter a username for that user. In our case, we're going to enter the username phoenixchat, but it's common to use your first and last name as the username.
Make sure the Generate an access key for each user is checked, then create the user. You'll see an option to Download credentials. Go ahead and do that now because we will need those credentials later.
Now click on the username from the list (not the checkbox), go to the Groups tab and Add User to Groups. Select the Administrators group and click Add to groups.
Finally, under the Security Credentials tab under Sign-In Credentials, choose Manage Password. Go ahead and fill out the Assign a custom password option and click Apply.
We're now ready to send our app to S3... but not quite. We need to change around our webpack configuration a little bit to prepare our app for production.
We need webpack to build our app in production mode. This means a few things need to change.
The first takes our code and removes whitespace and any extraneous data to make our bundle as small as possible. This simple step often cuts your bundle size by more than 1/3.
The second is deduplication (dedupe), which looks for files that are duplicates and removes the copy. This doesn't often noticeably affect the bundle size, but it doesn't cost anything to add.
The third is adding our environment variables. In this case, we only have one, which as you will see later tells webpack to use our Heroku app rather than localhost:4000. In the future, this is where you would inject things like Stripe tokens. But keep in mind, your environment variables are not hidden from the user. You shouldn't have anything secret living in your frontend.
The last piece of optimization is to load some of our libraries as externals. It's possible that our user will already have common libraries, such as React, cached in their browser. If that's the case, then we don't need to fetch that data again. This is not strictly necessary, and we aren't going to bother with it at this point.
In the future, we will look into more advanced optimizations, such as code splitting and the use of an entry-chunk to reduce our initial bundle size as much as possible. For more on webpack optimization, check out this page.
Before we can proceed, with our build, we're going to need to set up some environment variables. You can use the code below (with the proper information instead of the placeholders within < >) to export your variables to the environment. You can also keep them in a .sh file such as .env.sh and run run it with source .env.sh to export all of the variables at the same time.
If you choose to keep these keys in a file, be sure to add that file to your .gitignore so you don't accidentally expose your keys to the world.
export PROFILE=<profile name>export AWS_ACCESS_KEY_ID=<access key>export AWS_SECRET_ACCESS_KEY=<secret key>export BUCKET=<bucket name>Go ahead and run this now so we have access to these variables.
Now let's create a special webpack configuration just for production. We'll call it webpack.prod.config.js.
There are many ways to go about setting up your webpack configuration for production. Since the configuration is just an object, you can run it through a series of functions or conditionals to determine what you're exporting (often based on the currently chosen environment).
It's also common to make a "shared" configuration that all apps will use and then build on that as you add more environments and platforms. Keep in mind that this configuration is just JavaScript, so you can manipulate the configuration object just like you could any other JavaScript object.
That said, we're just going to keep it simple and put this in a new file for now and optimize later if it becomes necessary.
$ touch webpack.prod.config.jsWe're going to need the extract-text-webpack-plugin, which combines all of our CSS into a separate CSS file, which prevents React from inlining your styles into the JavaScript and bundles them all into a single file that gets loaded in parallel with your JavaScript bundle. This is something you want to do with react-css-modules in production.
$ npm install --save-dev extract-text-webpack-pluginWithin your webpack.prod.config.js file, add the following configuration. It will be almost the same as our existing code with a few differences, explained below the codeblock.
var path = require("path")var webpack = require("webpack")var ExtractTextPlugin = require("extract-text-webpack-plugin")var cssnext = require("postcss-cssnext")var HtmlWebpackPlugin = require("html-webpack-plugin")module.exports = { devtool: "cheap-module-source-map", entry: ["whatwg-fetch", "./app/index"], output: { path: path.join(__dirname, "dist"), filename: "bundle.js", }, plugins: [ new ExtractTextPlugin("style.css", { allChunks: true, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false, }, }), new webpack.DefinePlugin({ API_HOST: JSON.stringify("https://phoenix-chat-api.herokuapp.com"), SOCKET_HOST: JSON.stringify("wss://phoenix-chat-api.herokuapp.com"), "process.env": { NODE_ENV: JSON.stringify("production"), }, }), new HtmlWebpackPlugin({ template: "index.html", hash: true, filename: "index.html", }), ], module: { loaders: [ { test: /\.js$/, loaders: ["babel"], exclude: /node_modules/, include: path.join(__dirname, "app"), }, { test: /\.css$/, loader: ExtractTextPlugin.extract( "style", "css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]!postcss" ), include: path.join(__dirname, "app"), }, ], }, postcss: function () { return [cssnext] }, resolve: { extensions: ["", ".js"], },}The first thing we changed is our devtool, which we changed from eval to cheap-module-source-map. This change along will save you about 80% on your bundle size. If you aren't familiar with what source maps are, you can think of it as how your computer lets you know how errors that occur in compiled code correspond to your un-compiled, human-readable code. So with a good source map, rather than getting an error like "error bundle.js line 1", you would get, "error app/components/Chat/index.js line 42".
You'll notice that our entry point no longer includes webpack dev server, because we don't need it. If you're worried about cross-browser compatibility, you can also npm install babel-polyfill and add that as entry point as well. That will add some weight to your code, but it'll make sure your app works with older browsers.
We've also added 5 plugins. The first is the extract text plugin, which pulls out your inline styles and adds them to a single CSS file at the top of app. The next two are simply optimizations. They are not necessary for a successful build, but they make your bundle smaller and more efficient.
The last plugin is the HtmlWebpackPlugin, which is not an optimization, but it will inject our index.html file into our production distribution. You could simply copy this over or use the file-loader if you wanted, but we want to use this plugin to hash our bundle names to solve any cache invalidation issues with S3. When you compile a production build, check your index.html file and you'll see that your bundle and style files have a ? and a random series of numbers and letters after it. We will explain why this is important in a later lesson when we go over CloudFront.
And now that we're injecting our HTML file into our app, we should remove the tags we have hardcoded in our index.html file:
<!-- Delete this --><link rel="stylesheet" href="style.css" /><!-- Delete this too --><script src="bundle.js"></script>But in doing this, we've broken our dev build, so you need to add the HtmlWebpackPlugin to your webpack.config.js file as well.
...var HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = { ... new HtmlWebpackPlugin({ template: "index.html", hash: true, filename: "index.html" }) ...}We will also need to install that plugin.
$ npm install html-webpack-plugin --save-devNow go ahead and run webpack with the webpack.prod.config.js to build our app using the production configuration.
$ webpack --config webpack.prod.config.jsCheck the /dist directory to make sure everything is in order. If you open the dist/index.html file in a browser, you should have a fully functional app. If this works as you would expect, then we're ready to deploy.
For now, we'll hack this together. In the next lesson, we'll go over continuous integration and automated deployments.
Go back to AWS and click on that bucket we made earlier (in our case, www.phoenixchat.io). Click Upload in the top left and add the index.html, bundle.js, and style.css files currently in /dist.
Once those are uploaded, click Properties on the top right and select Static Website Hosting.
Change the setting to Enable website hosting and set the Index document to index.html. When you save, you should see an endpoint just above the tabs with a long domain name ending in ...amazonaws.com.
Click on the link. Your site is now live.
Previous: Deploying the API to HerokuNext: Continuous Integration and Deployment