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.
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 code we write during development is not optimal for running in a user's browser. A production application should be:
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:
Before building a production application, it is worth performing a few steps:
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 updateProduction 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-devAnd 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});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 productionVariables 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-1In code you use them like this:
1const apiUrl = import.meta.env.VITE_API_URL;Building a production build in Vite is simple - just run the command:
1npm run buildThis command performs several operations:
The result is a
dist directory (by default) containing the built application.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 previewThis command starts a local server serving the built application from the
dist directory, allowing you to check its operation before the actual deployment.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.
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 mainCreate an account on Vercel - go to vercel.com and register (preferably using the same account as your Git service)
Import the project:
Configure the project:
npm run build (leave unchanged)dist (leave unchanged).env.production (without the VITE_ prefix)Click "Deploy" and wait for the process to complete
After the deployment is complete, Vercel will show a summary page. You can:
your-project.vercel.app)Vercel will automatically configure Continuous Deployment for your project:
main or master) will trigger a deployment to the production environmentThis integration creates a simple and efficient workflow:
feature/new-feature branchVercel offers Analytics that help monitor application performance in the real world:
To enable Analytics:
Vite automatically optimizes assets during the build, but it is worth remembering a few additional practices:
<link rel="preload"> tags for critical resourcesFor more advanced applications, Vercel offers:
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};Integrate an error monitoring tool like Sentry or LogRocket:
1npm install @sentry/react1// 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);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}Transform your React application into a PWA by adding a Service Worker and manifest:
1npm install vite-plugin-pwa --save-dev1// 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});The entire process of creating and deploying a React application with Vite looks as follows:
Development
npm create vite@latest my-app --template reactnpm run devPreparing for production
Building
npm run buildnpm run previewPreparing the repository
Deployment on Vercel
Post-deployment
After deploying the application, your responsibilities as a developer do not end. It is important to continue:
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!