How to Build React App for Production: Step-by-Step Guide
To build a React app for production, run the
npm run build command which creates an optimized build folder with minified files. This folder can then be deployed to any static hosting service for fast and efficient delivery.Syntax
The main command to build a React app for production is npm run build. This command uses the build script defined in your package.json file, which typically runs react-scripts build if you use Create React App.
npm run build: Runs the build process.build/folder: Output directory with optimized files.- Minification: Removes unnecessary code and spaces.
- Bundling: Combines files for faster loading.
bash
npm run build
Output
Creating an optimized production build...
Compiled successfully.
File sizes after gzip:
static/js/main.abc123.js 45.3 KB
static/css/main.def456.css 5.1 KB
The build folder is ready to be deployed.
Example
This example shows how to build a React app created with Create React App and then serve it locally to verify the production build.
bash
npx create-react-app my-app cd my-app npm run build npx serve -s build
Output
Creating a new React app in /path/to/my-app.
...
Compiled successfully.
You can now serve the build folder locally with:
npx serve -s build
Starting up serve, serving build
Available on:
http://localhost:5000
Press CTRL-C to stop
Common Pitfalls
Some common mistakes when building React apps for production include:
- Trying to deploy the
srcfolder instead of thebuildfolder. - Not running
npm run buildbefore deployment, which means unoptimized code is served. - Serving the build folder without a static server, causing routing issues.
- Ignoring environment variables like
REACT_APP_*which need to be set before build time.
Always build your app and deploy the build folder contents to a static host.
bash
Wrong way: # Deploying src folder scp -r src/ user@server:/var/www/html Right way: npm run build scp -r build/ user@server:/var/www/html
Quick Reference
- Build command:
npm run build - Output folder:
build/ - Deploy to: Static hosts like Netlify, Vercel, GitHub Pages, or your own server
- Serve locally: Use
npx serve -s buildto test production build - Environment variables: Set before build with
REACT_APP_*prefix
Key Takeaways
Run
npm run build to create an optimized production build of your React app.Deploy the contents of the
build folder to a static hosting service for best performance.Use a static server like
serve to test your production build locally.Never deploy the
src folder or unbuilt code to production.Set environment variables before building to customize your app for production.