Deploying to Netlify (Part 1) #156
📖 Introduction
After mastering production builds and Environment Variables in React (Part 2), it's time to share your React application with the world! Netlify is a popular platform that makes deploying modern frontend applications incredibly simple and efficient, offering a fantastic developer experience with features like continuous deployment from Git, CDN distribution, HTTPS, and more. This article, Part 1, will guide you through the initial steps of deploying a React app to Netlify.
📚 Prerequisites
Before we begin, you will need:
- A React application that you've built for production (i.e., you can run
npm run buildoryarn buildto generate static assets in abuildordistfolder). - Your React project hosted on a Git provider like GitHub, GitLab, or Bitbucket. (Netlify integrates best with Git).
- A free Netlify account (signup at netlify.com).
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ What is Netlify? Key features and benefits for frontend developers.
- ✅ Preparing Your React App for Netlify: Build command and publish directory.
- ✅ Deployment Method 1: Connecting Your Git Repository (Continuous Deployment).
- Signing up/Logging into Netlify.
- Creating a new site from Git.
- Configuring build settings.
- First deployment and accessing your live site.
- ✅ Understanding Netlify's Build Process.
🧠 Section 1: What is Netlify?
Netlify is a powerful platform designed to build, deploy, and manage modern web projects (often called "Jamstack" sites, but it's great for any static-first or client-side rendered app like React SPAs).
Key Features and Benefits:
- Global CDN (Content Delivery Network): Your site's assets are distributed across multiple servers worldwide, ensuring fast load times for users no matter their location.
- Continuous Deployment from Git: Automatically builds and deploys your site whenever you push changes to your connected Git repository (GitHub, GitLab, Bitbucket).
- Free HTTPS/SSL: Automatic SSL certificates for custom domains and Netlify subdomains, ensuring your site is served securely.
- Custom Domains: Easily connect your own domain names.
- Atomic Deploys & Instant Rollbacks: Each deploy is "atomic," meaning it's an all-or-nothing update. If a build fails or you need to revert, you can instantly roll back to a previous version.
- Serverless Functions: Built-in support for deploying backend functions (Node.js, Go, etc.) without managing servers.
- Forms, Identity, Analytics: Offers add-on services like form handling, user authentication, and basic analytics.
- Generous Free Tier: The free tier is often sufficient for personal projects, portfolios, and even small production sites.
- Developer-Friendly Workflow: Intuitive UI and powerful CLI tools.
- Build Plugins: Extend build capabilities with a rich ecosystem of plugins.
For React SPAs, Netlify takes your build (or dist) output (the static HTML, JS, CSS files) and deploys it to its global CDN.
💻 Section 2: Preparing Your React App for Netlify
Before deploying, ensure your React application has the correct build settings configured, which Netlify will use.
-
Build Command:
- This is the command Netlify will run to build your application. For most React projects, it's:
- Create React App:
npm run buildoryarn build - Vite:
npm run buildoryarn build(which usually runsvite build)
- Create React App:
- This command should generate the static production assets.
- This is the command Netlify will run to build your application. For most React projects, it's:
-
Publish Directory (or Build Output Directory):
- This is the directory where your build command outputs the static files that Netlify should deploy.
- Create React App:
build - Vite:
dist
- Create React App:
- If you have a custom setup, ensure you know which directory contains your
index.htmland other static assets after the build.
- This is the directory where your build command outputs the static files that Netlify should deploy.
-
Handling Client-Side Routing (for SPAs):
- React applications that use client-side routing (like React Router) need special handling on the server so that direct navigation to a route (e.g.,
your-site.com/about) or page refreshes on a route correctly load yourindex.htmlfile, allowing React Router to take over. - Netlify handles this automatically for most SPAs! It has built-in redirect rules that serve your
index.htmlfor any path that doesn't match a static file in your publish directory. You usually don't need to configure this manually unless you have very specific needs. A common way to ensure this is to have a_redirectsfile in your public folder or build output (though Netlify often infers this for SPAs). - A simple
_redirectsfile in yourpublicfolder (which then gets copied tobuild/dist) might look like:This tells Netlify to redirect all paths to# public/_redirects
/* /index.html 200index.htmlwith a 200 status code, which is standard for SPAs. However, as mentioned, Netlify's default SPA detection usually makes this unnecessary.
- React applications that use client-side routing (like React Router) need special handling on the server so that direct navigation to a route (e.g.,
🛠️ Section 3: Deployment Method 1 - Connecting Your Git Repository
This is the most common and recommended way to deploy to Netlify, as it enables Continuous Deployment.
Step 1: Sign Up/Log In to Netlify Go to app.netlify.com and sign up using your GitHub, GitLab, Bitbucket account, or email.
Step 2: Create a New Site from Git
-
Once logged in, you'll be on your Netlify dashboard. Click the "Add new site" (or "New site from Git") button.
-
Connect to your Git provider: Choose GitHub, GitLab, or Bitbucket. You'll be asked to authorize Netlify to access your repositories.
-
Pick your repository: Select the repository containing your React application. If you have many repositories, you might need to search or configure Netlify's access to specific repos.
Step 3: Configure Build Settings
After selecting your repository, Netlify will ask for build settings:
- Branch to deploy: Choose the branch you want to deploy (e.g.,
main,master, or a specific production branch). Netlify will automatically build and deploy when you push to this branch. - Base directory (Optional): If your React app is in a subdirectory of your repository (e.g.,
packages/my-react-appin a monorepo), specify that path here. Otherwise, leave it blank or as/. - Build command: Enter the command to build your app.
- For CRA/Vite:
npm run buildoryarn build. - Netlify often auto-detects this for common frameworks.
- For CRA/Vite:
- Publish directory: Enter the directory where your build output is located.
- For CRA:
build - For Vite:
dist - Netlify often auto-detects this too.
- For CRA:
- Environment Variables (Advanced): You can click "Show advanced" or "Advanced build settings" to add environment variables (like
REACT_APP_API_URLorVITE_API_KEY) that your build process needs. These are securely stored by Netlify. We covered these in detail in Articles 154-155.
Step 4: Deploy Site Click the "Deploy site" (or similar) button.
Step 5: First Deployment and Accessing Your Site
- Netlify will now pull your code, run the build command in its build environment, and deploy the contents of your publish directory to its CDN.
- You'll see the deploy logs in real-time on your Netlify site dashboard.
- Once the deployment is complete (it usually takes a minute or two for simple apps), Netlify will provide you with a unique subdomain (e.g.,
random-name-12345.netlify.app). - Click this link to see your live React application!
Continuous Deployment in Action:
Now, whenever you push changes to the configured branch (e.g., main) in your Git repository:
- Netlify automatically detects the push via webhooks.
- It triggers a new build using your specified build command and publish directory.
- If the build is successful, it deploys the new version atomically. Your site is updated automatically!
🔬 Section 4: Understanding Netlify's Build Process
When Netlify builds your site from Git:
- Clones Repository: It clones your specified branch.
- Sets up Build Environment: It uses a build image (typically Linux-based) with Node.js, npm, yarn, and other common tools pre-installed. You can often specify Node.js versions via a
.nvmrcfile or Netlify settings. - Installs Dependencies: It usually runs
npm installoryarn installbased on yourpackage-lock.jsonoryarn.lockfile. - Injects Environment Variables: Any environment variables you've configured in Netlify's UI are made available to the build process.
- Runs Build Command: Executes the build command you specified (e.g.,
npm run build). - Collects Build Output: Takes the files from the specified "Publish directory."
- Deploys to CDN: Distributes these static files across its global CDN.
- Atomic Swap: Atomically switches the live version of your site to the new deploy.
You can view detailed build logs for every deploy in your Netlify site dashboard, which is very helpful for troubleshooting build issues.
💡 Conclusion & Key Takeaways (Part 1)
Deploying a React application to Netlify via Git integration is remarkably straightforward and sets up a powerful continuous deployment workflow. By connecting your repository and configuring a few basic build settings, you can have your site live on a global CDN with HTTPS in minutes.
Key Takeaways:
- Netlify is a platform optimized for deploying modern web projects, offering CDN, continuous deployment, HTTPS, and more.
- Ensure your React app has a build command that outputs static assets to a known publish directory (
buildfor CRA,distfor Vite). - Connecting your Git repository to Netlify is the primary method for deployment and enables CI/CD.
- Netlify automatically builds your project using your specified command and deploys the publish directory.
- Future pushes to your deployment branch will trigger automatic rebuilds and deploys.
➡️ Next Steps
We've successfully deployed our React app to a live URL! In "Deploying to Netlify (Part 2)", we will explore:
- Adding custom domains.
- Managing environment variables through the Netlify UI for different deploy contexts (production, branches, deploy previews).
- Understanding deploy previews and branch deploys.
- Using the Netlify CLI for manual deploys and other tasks.
Get ready to customize your Netlify deployment further!
glossary
- Netlify: A platform for building, deploying, and managing modern web projects, known for its ease of use and CI/CD capabilities.
- CDN (Content Delivery Network): A geographically distributed network of servers that cache content closer to users, improving load times.
- Continuous Deployment (CD): An automation practice where code changes pushed to a repository are automatically built, tested, and deployed to production.
- Atomic Deploy: A deployment method where a new version of a site is made live all at once. If the deploy fails, the site remains on the previous stable version. This prevents broken states.
- Publish Directory (Build Output Directory): The folder where your build command places the static HTML, JS, and CSS files ready for deployment (e.g.,
buildordist). - SPA Redirects/Rewrites: Server-side rules needed for Single Page Applications to ensure direct navigation or refreshes on client-side routes correctly load the main
index.htmlfile. Netlify handles this well.
Further Reading
- Netlify Official Documentation
- [Netlify: Get started with Git-linked sites](https://docs.netlify.com/get-started/ اولین-سایت-شما-با-git/)
- Netlify Build Configuration
- Jamstack.org (For more on the architecture Netlify excels at)