JavaScript and React course ยท Module 8: Advanced React Patterns

Building a Production Application and Deployment on Vercel

9 min read ยท
In this lesson8

Our cosmic journey through React is coming to an end. We have built our spaceship, tested it, optimized it - now it is time to launch it into interstellar space. In this module, you will learn how to prepare your React application for production and deploy it on the Vercel platform so that it is available to users from around the world.

From code to production - preparing the application

The process of moving a React application from a development environment to production requires several important steps. Before we send our application into space (the internet), we need to prepare it properly.

The importance of a production build

The code we write during development is not optimal for running in a user's browser. A production application should be:

  • Minified - removed whitespace, comments, and shortened variable names
  • Optimized - combining multiple files, removing unused code (tree shaking)
  • Compressed - smaller size for network transfer
  • Stable - free of debug messages and developer tools

Vite as a modern build tool

Vite (French for "fast") is a modern tool for building frontend applications that significantly speeds up the development and production process. Unlike older tools (like Create React App), Vite uses native ES modules in the browser during development and Rollup for production builds.

Main advantages of Vite:

  • Lightning-fast dev server startup
  • Fast refresh (Hot Module Replacement)
  • Efficient production builds
  • Support for TypeScript, JSX, CSS, SCSS, Less, and more
  • Minimal configuration with flexibility

Production build process with Vite

1. Preparing the application for building

Before building a production application, it is worth performing a few steps:

Checking dependencies

Make sure all dependencies are up to date and secure:

# Check for outdated packages
npm outdated

# Check for security vulnerabilities
npm audit

# Update packages (if safe)
npm update

Removing consoles and debuggers

Production code should not contain console.log or debugger statements. You can use a Babel or ESLint plugin to automatically remove them.

For Vite, you can add the vite-plugin-remove-console plugin:

npm install vite-plugin-remove-console --save-dev

And configure it in vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import removeConsole from 'vite-plugin-remove-console';

export default defineConfig({
  plugins: [
    react(),
    removeConsole()
  ],
});

Setting environment variables

Vite supports environment variables through .env files. You can create different files for different environments:

  • .env - variables for all environments
  • .env.development - only for development
  • .env.production - only for production

Variables must start with the VITE_ prefix to be available in code:

# .env.production
VITE_API_URL=https://api.yourdomain.com/v1
VITE_ANALYTICS_ID=UA-123456789-1

In code you use them like this:

const apiUrl = import.meta.env.VITE_API_URL;

2. Building the production application

Building a production build in Vite is simple - just run the command:

npm run build

This command performs several operations:

  • Transpiles ES6+/TypeScript/JSX code to a format supported by browsers
  • Minifies JavaScript and CSS code
  • Optimizes assets (images, fonts)
  • Generates hashed file names for cache busting
  • Creates a bundle optimized for production

The result is a dist directory (by default) containing the built application.

3. Testing the production build locally

Before deployment, it is worth checking if the built application works correctly. Vite provides a simple tool for locally serving the production build:

npm run preview

This command starts a local server serving the built application from the dist directory, allowing you to check its operation before the actual deployment.

Deployment on Vercel

Vercel is a platform for deploying frontend applications that works great with React, Next.js, and other frameworks. It offers a global CDN, automatic deployments from Git repositories, HTTPS, and many other features.

Why Vercel?

  • Zero-config - automatic framework detection and configuration
  • Global CDN - fast content delivery to users worldwide
  • Free tier - for personal and open-source projects
  • Preview deployments - each pull request generates a separate deployment
  • Git integration - automatic deployment on every push
  • Serverless functions - ability to add a backend without a separate server

Step by step: Deploying a Vite+React app on Vercel

1. Preparing the Git repository

Vercel integrates with GitHub, GitLab, and Bitbucket. Make sure your project is stored in one of these services:

# If you haven't initialized a repository yet
git init

# Add files to the repository
git add .

# Create a commit
git commit -m "Prepare for deployment"

# Add remote repository (replace URL with yours)
git remote add origin https://github.com/your-username/your-project.git

# Push changes
git push -u origin main

2. Configuring the project on Vercel

  1. Create an account on Vercel - go to vercel.com and register (preferably using the same account as your Git service)

  2. Import the project:

    • Click "Add New..." > "Project"
    • Select your repository from the list
    • Vercel will automatically detect that you are using Vite
  3. Configure the project:

    • Framework Preset: Vercel should automatically detect Vite
    • Build Command: By default npm run build (leave unchanged)
    • Output Directory: By default dist (leave unchanged)
    • Environment Variables: Add the same variables as in .env.production (without the VITE_ prefix)
  4. Click "Deploy" and wait for the process to complete

3. Verifying deployment

After the deployment is complete, Vercel will show a summary page. You can:

  • Visit your site at the automatically assigned address (e.g., your-project.vercel.app)
  • Check build and deployment logs
  • Configure a custom domain

Continuous deployment configuration (CI/CD)

Vercel will automatically configure Continuous Deployment for your project:

  • Every push to the main branch (usually main or master) will trigger a deployment to the production environment
  • Every pull request will generate a unique "Preview Deployment", allowing you to test changes before merging them to the main branch

This integration creates a simple and efficient workflow:

  1. You work locally on a new feature
  2. You push changes to the feature/new-feature branch
  3. You create a Pull Request
  4. Vercel automatically creates a Preview Deployment
  5. You test changes in a production-like environment
  6. After approval, you merge the PR with the main branch
  7. Vercel automatically updates the production environment

Deployment optimization

1. Performance analysis

Vercel offers Analytics that help monitor application performance in the real world:

  • Real Experience Score - user experience rating
  • Core Web Vitals - metrics like LCP, FID, and CLS
  • Per-page metrics - which parts of the application are slowest

To enable Analytics:

  1. Go to the project on Vercel
  2. Click the "Analytics" tab
  3. Click "Enable Analytics"

2. Static asset optimization

Vite automatically optimizes assets during the build, but it is worth remembering a few additional practices:

  • Use modern image formats - WebP instead of JPEG/PNG
  • Lazy loading - load images/components only when needed
  • Preload critical assets - add <link rel="preload"> tags for critical resources

3. Edge Functions and Edge Middleware on Vercel

For more advanced applications, Vercel offers:

  • Edge Functions - lightweight functions running on the global edge network
  • Edge Middleware - code executed before every request

Example Edge Middleware for redirecting users based on their location:

// middleware.js
export default function middleware(request) {
  const country = request.geo.country || 'US';

  // Redirect Polish users to the Polish version of the site
  if (country === 'PL' && !request.nextUrl.pathname.startsWith('/pl')) {
    return Response.redirect(new URL('/pl' + request.nextUrl.pathname, request.url));
  }
}

export const config = {
  matcher: ['/((?!api|_next/static|favicon.ico).*)'],
};

Production best practices

1. Error monitoring

Integrate an error monitoring tool like Sentry or LogRocket:

npm install @sentry/react
// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import * as Sentry from '@sentry/react';
import App from './App';
import './index.css';

if (import.meta.env.PROD) {
  Sentry.init({
    dsn: import.meta.env.VITE_SENTRY_DSN,
    integrations: [new Sentry.BrowserTracing()],
    tracesSampleRate: 0.5,
  });
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

2. Code splitting

Split the application into smaller chunks loaded on demand:

import { lazy, Suspense } from 'react';

// Instead of: import Dashboard from './Dashboard';
const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <Dashboard />
      </Suspense>
    </div>
  );
}

3. Progressive Web Apps (PWA)

Transform your React application into a PWA by adding a Service Worker and manifest:

npm install vite-plugin-pwa --save-dev
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
  plugins: [
    react(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico', 'robots.txt', 'apple-touch-icon.png'],
      manifest: {
        name: 'Space Mission Control',
        short_name: 'SpaceMission',
        description: 'Application for managing space missions',
        theme_color: '#ffffff',
        icons: [
          {
            src: 'pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          },
          {
            src: 'pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png'
          }
        ]
      }
    })
  ]
});

Summary of the development to deployment process

The entire process of creating and deploying a React application with Vite looks as follows:

  1. Development

    • Initialize the project with Vite: npm create vite@latest my-app --template react
    • Develop features in the local environment: npm run dev
    • Test components and functionality
  2. Preparing for production

    • Remove consoles and debuggers
    • Configure production environment variables
    • Check and update dependencies
  3. Building

    • Run the production build: npm run build
    • Test the built application: npm run preview
  4. Preparing the repository

    • Initialize the Git repository
    • Commit and push to the remote repository
  5. Deployment on Vercel

    • Connect with the Git repository
    • Configure the project
    • Deploy
  6. Post-deployment

    • Configure the domain
    • Enable Analytics
    • Monitor errors
    • Optimize performance

Managing the application in production

After deploying the application, your responsibilities as a developer do not end. It is important to continue:

  • Monitoring performance and errors - regularly checking Vercel Analytics and error tracking tools
  • Updating dependencies - regularly updating packages, especially for security fixes
  • Introducing new features - leveraging the CI/CD workflow for safely introducing changes
  • A/B testing - testing new features on a subset of users before full deployment

End of the cosmic journey

We have completed our cosmic journey through React! Starting from the basics, we gradually built increasingly advanced components, all the way to a full application ready for deployment on the Vercel platform.

Remember that, like space exploration, learning React is a never-ending journey. The React ecosystem is constantly evolving, new libraries, tools, and patterns are emerging. Stay up to date with documentation, blogs, and the community to keep your skills current.

Now that your spaceship is built, tested, and ready to fly - it is time to conquer the cosmos of frontend applications!

Code for this lesson: App.jsx
import React from 'react';

// Deployment and building the production application
export default function App() {
  return (
    <div style={{
      background: '#0d1b2a', minHeight: '100vh',
      padding: '20px', fontFamily: 'Arial', color: '#e0e1dd'
    }}>
      <h1 style={{ color: '#ffd700', textAlign: 'center' }}>
        Deployment to Vercel
      </h1>
      <div style={{
        background: '#1b2838', borderRadius: '12px',
        padding: '20px', maxWidth: '600px', margin: '20px auto',
        border: '1px solid #2a3f5f'
      }}>
        <h2 style={{ color: '#00d4ff' }}>Deployment steps:</h2>
        <ol style={{ color: '#e0e1dd', lineHeight: 1.8 }}>
          <li>npm run build - production build</li>
          <li>Verify the build/ directory</li>
          <li>Deploy to Vercel/Netlify</li>
          <li>Configure environment variables</li>
        </ol>
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the standard naming convention for Higher-Order Components?

  2. 2. What does React.lazy() do and when do we use it?

These are 2 of 9 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the useCallback hook syntax with a dependency:

  • Code editor

    useReducer for an alarm system

  • Vertical ordering

    Arrange the steps for implementing code splitting in a React application:

  • Code editor

    Provider Composition with Hooks

  • Click in order

    Arrange the Render Props pattern:

  • Horizontal ordering

    Arrange the useMemo hook syntax with a dependency array:

  • Vertical ordering

    Arrange React state management patterns from simplest to most complex:

  • Vertical ordering

    Arrange the evolution of state management in React:

  • Click in order

    Arrange the Render Props pattern with children as a function:

  1. QuestionIntroduction: HOC Naming Convention
  2. Put in orderuseCallback Syntax
  3. Coding taskPractice: useReducer - Alarm System
  4. Put in orderBenefits of Code Splitting
  5. Coding taskPractice: Provider Composition
  6. Click in orderIntroduction: Render Props structure
  7. QuestionCode Splitting with React.lazy
  8. QuestionCustom Hook Return Value
  9. Put in orderuseMemo Syntax
  10. QuestionIntroduction: HOC and Modifying the Original Component
  11. Put in orderState Management Patterns
  12. QuestionFallback in React.lazy and Suspense
  13. Put in orderState Management Evolution
  14. Questionnpm run build
  15. QuestionChild-Parent Communication in React
  16. Click in orderIntroduction: Render Props - children as function
  17. QuestionReact Performance Monitoring Tools
  18. QuestionIntroduction: Custom Hooks - Composition Principle

Useful articles