We use cookies to enhance your experience on the site
CodeWorlds

Building a Production Application and Deployment on Vercel

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:

1# Check for outdated packages
2npm outdated
3
4# Check for security vulnerabilities
5npm audit
6
7# Update packages (if safe)
8npm 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:

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

And configure it in

vite.config.js
:

1import { defineConfig } from 'vite';
2import react from '@vitejs/plugin-react';
3import removeConsole from 'vite-plugin-remove-console';
4
5export default defineConfig({
6  plugins: [
7    react(),
8    removeConsole()
9  ],
10});

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:

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

In code you use them like this:

1const apiUrl = import.meta.env.VITE_API_URL;

2. Building the production application

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

1npm 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:

1npm 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:

1# If you haven't initialized a repository yet
2git init
3
4# Add files to the repository
5git add .
6
7# Create a commit
8git commit -m "Prepare for deployment"
9
10# Add remote repository (replace URL with yours)
11git remote add origin https://github.com/your-username/your-project.git
12
13# Push changes
14git 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:

1// middleware.js
2export default function middleware(request) {
3  const country = request.geo.country || 'US';
4  
5  // Redirect Polish users to the Polish version of the site
6  if (country === 'PL' && !request.nextUrl.pathname.startsWith('/pl')) {
7    return Response.redirect(new URL('/pl' + request.nextUrl.pathname, request.url));
8  }
9}
10
11export const config = {
12  matcher: ['/((?!api|_next/static|favicon.ico).*)'],
13};

Production best practices

1. Error monitoring

Integrate an error monitoring tool like Sentry or LogRocket:

1npm install @sentry/react
1// src/main.jsx
2import React from 'react';
3import ReactDOM from 'react-dom/client';
4import * as Sentry from '@sentry/react';
5import App from './App';
6import './index.css';
7
8if (import.meta.env.PROD) {
9  Sentry.init({
10    dsn: import.meta.env.VITE_SENTRY_DSN,
11    integrations: [new Sentry.BrowserTracing()],
12    tracesSampleRate: 0.5,
13  });
14}
15
16ReactDOM.createRoot(document.getElementById('root')).render(
17  <React.StrictMode>
18    <App />
19  </React.StrictMode>
20);

2. Code splitting

Split the application into smaller chunks loaded on demand:

1import { lazy, Suspense } from 'react';
2
3// Instead of: import Dashboard from './Dashboard';
4const Dashboard = lazy(() => import('./Dashboard'));
5
6function App() {
7  return (
8    <div>
9      <Suspense fallback={<div>Loading...</div>}>
10        <Dashboard />
11      </Suspense>
12    </div>
13  );
14}

3. Progressive Web Apps (PWA)

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

1npm install vite-plugin-pwa --save-dev
1// vite.config.js
2import { defineConfig } from 'vite';
3import react from '@vitejs/plugin-react';
4import { VitePWA } from 'vite-plugin-pwa';
5
6export default defineConfig({
7  plugins: [
8    react(),
9    VitePWA({
10      registerType: 'autoUpdate',
11      includeAssets: ['favicon.ico', 'robots.txt', 'apple-touch-icon.png'],
12      manifest: {
13        name: 'Space Mission Control',
14        short_name: 'SpaceMission',
15        description: 'Application for managing space missions',
16        theme_color: '#ffffff',
17        icons: [
18          {
19            src: 'pwa-192x192.png',
20            sizes: '192x192',
21            type: 'image/png'
22          },
23          {
24            src: 'pwa-512x512.png',
25            sizes: '512x512',
26            type: 'image/png'
27          }
28        ]
29      }
30    })
31  ]
32});

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!

Go to CodeWorlds