Frontend

ReactJS Setup & Deployment Guide

Build fast, component-based user interfaces – set up with Vite, run locally and deploy the build to any web server.

Updated Official documentation ↗

1. Introduction & use cases

React is a JavaScript library from Meta for building user interfaces out of small, reusable components. You describe what the screen should look like for the current data (state), and React updates the browser efficiently when the data changes.

A React app is usually a single-page application (SPA): the server sends one HTML file plus JavaScript bundles, and React renders every page in the browser. The modern way to start a plain React project is Vite – the old Create React App is deprecated. For server-side rendering and SEO-heavy sites, use a React framework such as Next.js.

Where it is used

  • Dashboards, admin panels and internal tools
  • Interactive front-ends for REST or GraphQL APIs
  • E-commerce and booking interfaces
  • Mobile apps with React Native (same component model)

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release (check with node -v). Download from nodejs.org or install with nvm.
npmComes with Node.js. (pnpm or Yarn also work.)
Code editorVS Code with the ES7+ React snippets and ESLint extensions
BrowserChrome, Edge or Firefox + the React Developer Tools extension
BasicsHTML, CSS and modern JavaScript (ES modules, arrow functions, async/await)

3. Local setup

  1. 1Install Node.js

    Install the LTS version from nodejs.org (Windows/macOS installer) or with nvm on macOS/Linux so you can switch versions later.

    BASH
    # macOS / Linux with nvm
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    nvm install --lts
    
    # check
    node -v
    npm -v
  2. 2Create the project with Vite

    Vite asks for a framework and variant – choose React and JavaScript (or TypeScript). The -- passes the template option through npm.

    BASH
    npm create vite@latest my-react-app -- --template react
    # TypeScript instead:
    # npm create vite@latest my-react-app -- --template react-ts
  3. 3Install dependencies and start the dev server

    The dev server has hot reload: save a file and the browser updates instantly.

    BASH
    cd my-react-app
    npm install
    npm run dev

4. Create & run a project

  1. 1Edit your first component

    Open src/App.jsx and replace it with a small counter. Components are functions that return JSX; useState keeps data that changes.

    src/App.jsx
    import { useState } from 'react';
    
    export default function App() {
      const [count, setCount] = useState(0);
      return (
        <main style={{ padding: 24 }}>
          <h1>Hello React</h1>
          <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
        </main>
      );
    }
  2. 2Fetch data from an API

    Use useEffect to load data when the component mounts. Read the API URL from an environment variable (see section 5).

    src/Users.jsx
    import { useEffect, useState } from 'react';
    
    export function Users() {
      const [users, setUsers] = useState([]);
      useEffect(() => {
        fetch(`${import.meta.env.VITE_API_URL}/users`)
          .then((r) => r.json())
          .then(setUsers)
          .catch(console.error);
      }, []);
      return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
    }
  3. 3Add pages with React Router

    For several pages install React Router and wrap your routes.

    JSX
    npm install react-router
    
    // src/main.jsx
    import { BrowserRouter, Routes, Route } from 'react-router';
    createRoot(document.getElementById('root')).render(
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<App />} />
          <Route path="/users" element={<Users />} />
        </Routes>
      </BrowserRouter>
    );
  4. 4Open it in the browser

    Visit the URL Vite prints (usually http://localhost:5173). Press o + Enter in the terminal to open it.

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Vite only exposes variables that start with VITE_ to browser code, read through import.meta.env. Everything in a React bundle is public – never put secret keys here. Use .env.production for build-time production values.

.env
# .env (development)
VITE_API_URL=http://localhost:8000/api
VITE_APP_NAME=My React App

# .env.production (used by npm run build)
VITE_API_URL=https://api.example.com/api

Key dependencies

Package / toolUsed for
react, react-domThe library and the browser renderer
vite, @vitejs/plugin-reactDev server with hot reload and production bundler
react-routerClient-side routing between pages
eslintFinds bugs and enforces code style
@tanstack/react-query (optional)Caching and syncing server data
vitest + @testing-library/reactUnit and component tests

Folder structure

project structure
my-react-app/
├── public/            # copied as-is (favicon, robots.txt)
├── src/
│   ├── assets/        # images, fonts imported in code
│   ├── components/    # reusable UI pieces
│   ├── pages/         # route-level components
│   ├── App.jsx
│   └── main.jsx       # entry: renders <App/>
├── index.html
├── .env
├── package.json
└── vite.config.js

Essential commands

CommandWhat it does
npm run devStart the dev server with hot reload
npm run buildCreate an optimised production build in dist/
npm run previewServe the production build locally to test it
npm run lintRun ESLint
npm install <pkg>Add a dependency

6. Production deployment

A React (Vite) app compiles to static files – HTML, JS and CSS in dist/. Any static host can serve it: Nginx on a VPS (below), shared hosting, AWS S3 + CloudFront, Netlify or Vercel. No Node.js is needed on the server.

Server & hosting requirements

RequirementRecommendation
ServerAny static host; for a VPS 1 vCPU / 512 MB–1 GB RAM is plenty
Web serverNginx or Apache with SPA fallback to index.html
Build machineNode.js LTS (your PC or CI) to run npm run build
Domain + SSLA/AAAA DNS records and a Let’s Encrypt certificate

Deployment steps

  1. 1Build for production

    Set production variables in .env.production, then build. Test the result locally with npm run preview.

    BASH
    npm ci
    npm run build
    npm run preview   # http://localhost:4173
  2. 2Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  3. 3Upload the build

    Copy the contents of dist/ to the web root on the server.

    BASH
    # on the server
    sudo mkdir -p /var/www/example.com
    sudo chown deploy:deploy /var/www/example.com
    
    # on your computer
    rsync -avz --delete dist/ deploy@YOUR_SERVER_IP:/var/www/example.com/
  4. 4Serve the build with Nginx

    Copy the build output to the server and let Nginx serve it. The try_files … /index.html line sends every unknown path to index.html, so client-side routes (React Router, Vue Router) work after a page refresh.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
        root /var/www/example.com;
        index index.html;
    
        location / {
            try_files $uri $uri/ /index.html;
        }
    
        location ~* \.(js|css|png|jpg|jpeg|gif|svg|webp|woff2?)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }
    }
  5. 5Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  6. 6Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  7. 7Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  8. 8Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  9. 9Deploy updates

    For each release build again and re-run rsync. Vite adds content hashes to file names, so browsers download new files while index.html points to them.

    BASH
    npm run build && rsync -avz --delete dist/ deploy@YOUR_SERVER_IP:/var/www/example.com/

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm run dev> my-react-app@0.0.0 dev> vite VITE ready in 412 ms ➜ Local: http://localhost:5173/ ➜ Network: use --host to expose ➜ press h + enter to show help
Figure 1: terminal output of the sample ReactJS project (section 4).
1Write components2npm run build3dist/ static files4Upload with rsync5Nginx serves SPA6HTTPS on yourdomain
Figure 2: production deployment flow (section 6).
my-react-app/├── public/ # copied as-is (favicon, robots.txt)├── src/│ ├── assets/ # images, fonts imported in code│ ├── components/ # reusable UI pieces│ ├── pages/ # route-level components│ ├── App.jsx│ └── main.jsx # entry: renders <App/>├── index.html├── .env├── package.json└── vite.config.js
Figure 3: project folder structure (section 5).

8. Common errors & solutions

404 Not Found when refreshing /users on the live site

The server looks for a real file called /users. Add the SPA fallback try_files $uri $uri/ /index.html; (Nginx) or a rewrite to index.html (Apache .htaccess).

import.meta.env.MY_VAR is undefined

Only variables prefixed with VITE_ are exposed. Rename to VITE_MY_VAR and restart npm run dev – env files are read at startup.

Blank page after deploy, console shows 404 for /assets/index-xxxx.js

The app is served from a sub-folder. Set base in vite.config.js, e.g. base: '/app/', and rebuild.

CORS error when calling the API

The API must send Access-Control-Allow-Origin for your site’s origin. In development you can use Vite’s proxy instead.

JS
// vite.config.js
export default defineConfig({
  plugins: [react()],
  server: { proxy: { '/api': 'http://localhost:8000' } },
});
Warning: Each child in a list should have a unique "key" prop

Give list items a stable unique key (an id from your data), not the array index when items can move.

npm ERR! ERESOLVE unable to resolve dependency tree

A package does not support your React version yet. Update the package, or as a last resort install with --legacy-peer-deps and test carefully.

Best practices

  • Keep components small and pure; lift shared state up or use a store such as Redux only when needed.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.
  • Lazy-load heavy pages with React.lazy and Suspense to keep the first load small.
  • Run npm run build in CI on every pull request so broken builds never reach the server.
  • Use Next.js when pages must be indexed by search engines or need server rendering.