Table of Contents
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:
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
After deployment you can verify the correct path is taken by checking the 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:
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