JavaScript and React course ยท Module 8: Advanced React Patterns
Building a Production Application and Deployment on Vercel
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 updateRemoving 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-devAnd 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-1In 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 buildThis 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 previewThis 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 main2. Configuring the project on Vercel
Create an account on Vercel - go to vercel.com and register (preferably using the same account as your Git service)
Import the project:
- Click "Add New..." > "Project"
- Select your repository from the list
- Vercel will automatically detect that you are using Vite
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 theVITE_prefix)
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
mainormaster) 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:
- You work locally on a new feature
- You push changes to the
feature/new-featurebranch - You create a Pull Request
- Vercel automatically creates a Preview Deployment
- You test changes in a production-like environment
- After approval, you merge the PR with the main branch
- 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:
- Go to the project on Vercel
- Click the "Analytics" tab
- 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:
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
- Initialize the project with Vite:
Preparing for production
- Remove consoles and debuggers
- Configure production environment variables
- Check and update dependencies
Building
- Run the production build:
npm run build - Test the built application:
npm run preview
- Run the production build:
Preparing the repository
- Initialize the Git repository
- Commit and push to the remote repository
Deployment on Vercel
- Connect with the Git repository
- Configure the project
- Deploy
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. What is the standard naming convention for Higher-Order Components?
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:
Tasks after this lesson
- QuestionIntroduction: HOC Naming Convention
- Put in orderuseCallback Syntax
- Coding taskPractice: useReducer - Alarm System
- Put in orderBenefits of Code Splitting
- Coding taskPractice: Provider Composition
- Click in orderIntroduction: Render Props structure
- QuestionCode Splitting with React.lazy
- QuestionCustom Hook Return Value
- Put in orderuseMemo Syntax
- QuestionIntroduction: HOC and Modifying the Original Component
- Put in orderState Management Patterns
- QuestionFallback in React.lazy and Suspense
- Put in orderState Management Evolution
- Questionnpm run build
- QuestionChild-Parent Communication in React
- Click in orderIntroduction: Render Props - children as function
- QuestionReact Performance Monitoring Tools
- QuestionIntroduction: Custom Hooks - Composition Principle