How to Deploy React App to Netlify: Step-by-Step Guide
To deploy a React app to Netlify, first build your app using
npm run build, then push your code to a Git repository. Next, connect your repository to Netlify and configure the build settings with npm run build as the build command and build as the publish directory.Syntax
Deploying a React app to Netlify involves these main steps:
- Build command:
npm run build- creates optimized static files. - Publish directory:
build- folder with files to serve. - Git repository: Your app's source code hosted on GitHub, GitLab, or Bitbucket.
- Netlify site setup: Connect your Git repo to Netlify and configure build settings.
bash
npm run build
# Builds the React app into the 'build' folder
# Netlify build settings example:
Build command: npm run build
Publish directory: buildExample
This example shows how to deploy a React app from GitHub to Netlify:
- Run
npm run buildlocally to create thebuildfolder. - Push your React app code to a GitHub repository.
- Go to Netlify, click New site from Git, and connect your GitHub repo.
- Set
npm run buildas the build command andbuildas the publish directory. - Click deploy and wait for Netlify to build and publish your site.
bash
/* Terminal commands */ npm run build git add . git commit -m "Prepare for Netlify deployment" git push origin main /* Netlify build settings */ Build command: npm run build Publish directory: build
Output
Creating an optimized production build...
Compiled successfully.
File sizes after gzip:
36.2 KB build/static/js/main.js
Deploy site on Netlify: Success
Common Pitfalls
Common mistakes when deploying React apps to Netlify include:
- Not running
npm run buildbefore deployment, so no static files exist. - Setting the wrong publish directory (should be
build, notpublicor others). - Not pushing the latest code to the Git repository before connecting to Netlify.
- Forgetting to set the build command in Netlify settings, causing build failures.
- Using environment variables locally but not configuring them in Netlify.
react
/* Wrong build command example */ Build command: npm start /* Correct build command example */ Build command: npm run build
Quick Reference
Summary tips for deploying React apps to Netlify:
- Always run
npm run buildto generate production files. - Push your code to a Git repo before connecting to Netlify.
- Set
npm run buildas the build command in Netlify. - Set
buildas the publish directory. - Configure environment variables in Netlify if your app uses them.
Key Takeaways
Run 'npm run build' to create optimized static files before deployment.
Push your React app code to a Git repository before connecting to Netlify.
Set 'npm run build' as the build command and 'build' as the publish directory in Netlify.
Check environment variables are configured in Netlify if used in your app.
Avoid using 'npm start' as build command; it serves locally but does not build.