Skip to main content

React Netlify Deployment

Introduction

Deploying your React application is a crucial step in the development process that makes your project accessible to users across the internet. Netlify is one of the most developer-friendly platforms for deploying web applications, particularly for React projects. It offers a streamlined deployment process with continuous integration, HTTPS by default, and many other features that make it an excellent choice for frontend applications.

In this guide, you'll learn how to deploy your React application to Netlify from start to finish. We'll cover both manual deployments and setting up continuous deployment from your Git repository.

What is Netlify?

Netlify is a web hosting and automation platform that specializes in static site hosting but works excellently for React applications built with Create React App or other modern build tools. Some key features include:

  • Continuous Deployment - Automatic builds when you push to your repository
  • Deploy Previews - Preview changes on pull requests before merging
  • Custom Domains - Connect your own domain with free SSL
  • Form Handling - Built-in form processing without server-side code
  • Serverless Functions - Run backend code without managing servers
  • Identity Service - User authentication and gated content

Prerequisites

Before we begin, ensure you have:

  1. A working React application
  2. Node.js and npm installed
  3. Git installed (for continuous deployment)
  4. A GitHub, GitLab, or Bitbucket account (for continuous deployment)
  5. A Netlify account (sign up at Netlify for free)

Preparing Your React Application for Deployment

Before deploying, we need to make sure our React application is ready for production:

1. Add a netlify.toml Configuration File

Create a netlify.toml file in the root of your project:

toml
[build]
command = "npm run build"
publish = "build"

[[redirects]]
from = "/*"
to = "/index.html"
status = 200

This configuration tells Netlify:

  • How to build your application
  • Where the build output is located
  • To redirect all requests to index.html (necessary for React Router)

2. Ensure Your package.json Has a Build Script

Make sure your package.json has a build script (this should be included if you used Create React App):

json
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
}

Deployment Methods

There are two primary ways to deploy your React app to Netlify:

  1. Manual deployment by uploading the build folder
  2. Continuous deployment from a Git repository

Let's explore both methods.

Method 1: Manual Deployment

Manual deployment is simple and quick for one-time deployments or when you're still setting up your project.

Step 1: Build Your React Application

Run the build command in your project's root directory:

bash
npm run build

This will create a build directory with your optimized production-ready application.

Step 2: Deploy Through the Netlify UI

  1. Log in to your Netlify account
  2. On the Sites page, look for the drag-and-drop area or click on "New site from upload"
  3. Drag your build folder onto the designated area or use the file picker to select it
  4. Netlify will upload and deploy your site

Once the deployment is complete, Netlify will provide you with a unique URL (something like https://random-name-123456.netlify.app) where your site is live.

Method 2: Continuous Deployment from Git

This method is recommended for ongoing projects as it automatically deploys your site whenever you push changes to your repository.

Step 1: Push Your Project to a Git Repository

If your project isn't already on GitHub, GitLab, or Bitbucket, set up a repository and push your code:

bash
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/yourusername/your-repo.git
git push -u origin main

Step 2: Connect Netlify to Your Git Repository

  1. Log in to your Netlify account
  2. Click "New site from Git" or "Import from Git" on the dashboard
  3. Choose your Git provider (GitHub, GitLab, or Bitbucket)
  4. Authenticate and select your repository
  5. Configure build settings:
    • Build command: npm run build
    • Publish directory: build
  6. Click "Deploy site"

Netlify will now automatically deploy your site and provide you with a URL.

Step 3: Set up Environment Variables (if needed)

If your React app uses environment variables:

  1. Go to Site settings > Build & deploy > Environment
  2. Add environment variables with the REACT_APP_ prefix (for Create React App)
  3. Trigger a new deploy for the changes to take effect

Custom Domains and HTTPS

One of the benefits of Netlify is how easy it is to set up a custom domain with HTTPS:

Adding a Custom Domain

  1. Go to your site's dashboard in Netlify
  2. Navigate to Site settings > Domain management
  3. Click "Add custom domain"
  4. Enter your domain name and follow the verification steps
  5. Update your domain's DNS settings to point to Netlify's servers

Netlify will automatically provision a free SSL certificate through Let's Encrypt once your DNS is configured correctly.

Handling React Router

For React applications using React Router, client-side routing needs special handling. The netlify.toml configuration we added earlier takes care of this by redirecting all requests to index.html, allowing React Router to handle routes on the client side.

Practical Example: Deploying a Todo App with React Router

Let's walk through deploying a simple Todo app that uses React Router:

  1. Our example Todo app has the following structure:
todo-app/
├── public/
├── src/
│ ├── components/
│ │ ├── TodoList.js
│ │ ├── TodoItem.js
│ │ └── AddTodo.js
│ ├── pages/
│ │ ├── Home.js
│ │ ├── About.js
│ │ └── TodoDetails.js
│ ├── App.js
│ ├── index.js
│ └── Router.js
├── package.json
├── netlify.toml
└── README.md
  1. The Router.js file sets up React Router:
jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import TodoDetails from './pages/TodoDetails';

function AppRouter() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/todo/:id" element={<TodoDetails />} />
</Routes>
</BrowserRouter>
);
}

export default AppRouter;
  1. After creating the necessary components and setting up React Router, we add the netlify.toml file:
toml
[build]
command = "npm run build"
publish = "build"

[[redirects]]
from = "/*"
to = "/index.html"
status = 200
  1. We connect the repository to Netlify as described in Method 2

  2. Once deployed, all our routes will work correctly:

    • Main route: https://my-todo-app.netlify.app/
    • About page: https://my-todo-app.netlify.app/about
    • Todo details: https://my-todo-app.netlify.app/todo/1

Advanced Netlify Features

Once your basic deployment is working, you can explore these advanced Netlify features:

1. Deploy Previews for Pull Requests

Netlify automatically builds deploy previews for pull requests, allowing you to see changes before merging them to your main branch.

2. Netlify Functions (Serverless)

For backend functionality, you can use Netlify Functions:

  1. Create a netlify/functions directory in your project
  2. Add function files like this:
js
// netlify/functions/hello-world.js
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({ message: "Hello World" })
};
}
  1. Access at /.netlify/functions/hello-world

3. Netlify Forms

For simple form handling without a backend:

html
<form name="contact" method="POST" data-netlify="true">
<input type="text" name="name" />
<input type="email" name="email" />
<textarea name="message"></textarea>
<button type="submit">Send</button>
</form>

Common Issues and Troubleshooting

Build Failures

If your build fails on Netlify:

  1. Check the build logs in the Netlify dashboard
  2. Ensure all dependencies are in your package.json
  3. Verify your build command and publish directory are correct
  4. Test the build locally with npm run build

Route Not Found (404) Errors

If you're seeing 404 errors for your routes:

  1. Verify you have the redirect rule in your netlify.toml file
  2. Check that you're using BrowserRouter (not HashRouter) in React Router

Environment Variable Issues

If your app can't access environment variables:

  1. Make sure they are prefixed with REACT_APP_ (for Create React App)
  2. Verify they're set in the Netlify dashboard
  3. Rebuild your site after adding them

Summary

Deploying a React application to Netlify is a straightforward process that offers numerous benefits:

  • Simple setup with minimal configuration
  • Automatic HTTPS and custom domain support
  • Continuous deployment from Git
  • Support for client-side routing (React Router)
  • Advanced features like serverless functions and form handling

By following this guide, you should now have your React application deployed to Netlify and accessible to users worldwide. The continuous deployment workflow ensures that any future changes you push to your repository will automatically be deployed, making the development and release process seamless.

Additional Resources and Exercises

Resources

Exercises

  1. Basic Deployment: Deploy a simple React counter application to Netlify using the drag-and-drop method.

  2. Continuous Deployment: Set up continuous deployment for your React project from GitHub, including environment variables.

  3. Advanced Features: Extend your React application to use a Netlify Function for a simple API (e.g., fetching data or processing form submissions).

  4. Custom Domain: Add a custom domain to your Netlify deployment and set up HTTPS.

  5. Form Handling: Implement a contact form that uses Netlify's built-in form handling.

By completing these exercises, you'll gain hands-on experience with the different aspects of deploying React applications to Netlify, preparing you for real-world deployment scenarios.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)