Skip to content
react

How to deploy React Application build files to external CDN

Jul 2, 2020Abhishek EH2 Min Read
How to deploy React Application build files to external CDN

Why CDN?

In the current world, speed is the most important factor of a website. So, storing the static files just in your hosting might not help. So, CDN comes to your help. in this article, we will see how can we specify the path to an external CDN for the static build files generated by create-react-app.

Creating a React App

If you do not have an app already, create a react app using the following command:

1create-react-app react-cdn --use-npm

Adding .env file

Create a file named .env.production inside the root directory of your project with the following value

1PUBLIC_URL = https://example.com/path/from/env/file

The above settings tell the react-scripts to prefix the CDN URL to the paths generated in the index.html

Now build the application using the following command:

1npm run build

Once the build completes, check the path of the static files in index.html. You will see that the paths are prefixed with the CDN URL:

Generated HTML file

You can have multiple .env files, one for each environment. You can check more about it in the create-react-app documentation

Deploy to Vercel (Now.sh)

You can specify the CDN URL while deploying as well. You can do that so by setting the environment variable as shown below

Setting environment variable in Vercel

After deployment you can verify the correct path is taken by checking the network tab:

CDN path in network tab

Changing to a different path within the hosting website

If you wish to store the static files in a location other than the root directory, then you can provide the URL in the package.json

1"homepage": "http://example.com/local/dir/path"

Now if you build the project, you would see:

Path from package.json

Preference

You might be thinking about what will happen if I specify PUBLIC_URL in multiple places. In that case, the priority will be in the following descending order:

  • environment variable specified in the deployment configuration
  • .evn.production file
  • homepage param in package.json

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com