EXAMTOPICS / TECHNOLOGY INSIGHTS

React Front-End Setup: Vite, TypeScript and a Local API

React is a JavaScript library for building user interfaces from components. In a full-stack application, React can manage forms, navigation and visual state in the browser while a server implements business rules, authorization and data access. This division helps teams reason about responsibilities, but the browser must never be trusted to enforce access restrictions merely by hiding a button.

A modern setup guide must also distinguish the React library from the tools used to build and deploy an app. Create React App was deprecated in February 2025. React’s current documentation recommends an appropriate framework for many new applications and provides a from-scratch path using tools such as Vite for learning or projects whose requirements do not fit a framework. This guide builds a small React and TypeScript front end using Vite and connects it to a local Node.js API.

Choose a React setup that matches the application

If a project needs integrated routing, server rendering, data loading and deployment conventions, first evaluate a React framework recommended by the React team’s app-creation documentation. If the goal is to learn components or build a smaller client-side interface, using a build tool directly may be reasonable. Choosing Vite does not automatically give the application a router, authenticated backend, database or server-rendering strategy.

The React team’s Create React App deprecation notice explains why its old scaffolding approach is no longer recommended for new apps. An older project using Create React App may still work, but its maintenance and migration path should be evaluated separately. Do not copy commands from an outdated tutorial simply because they once worked with a previous React release.

Before generating the project, choose a package manager and a supported Node.js version. The current Vite guide states its Node.js requirements and explains available templates. Check the installed version with node --version and compare it with the versioned Vite documentation, because a template’s requirements can change independently of React’s API.

Scaffold a TypeScript front end with Vite

For this example, use npm and the React TypeScript template. In a terminal, run the commands below in a directory where you have permission to create a development project:

npm create vite@latest client-app -- --template react-ts
cd client-app
npm install
npm run dev

The development server normally prints a local URL. Open that address to see the generated starter interface. The exact port is not a contract: if the default is occupied, the tooling may choose a different one. The project includes index.html, a src directory and configuration for React and TypeScript. Read the generated package.json and scripts instead of assuming every Vite release uses exactly the same build internals.

The front end runs in the browser, even though Node.js is used for local tooling. Environment settings passed to the browser build are not secret storage. Vite variables intentionally exposed to client code can be inspected by visitors, so never put database passwords, private API keys or service-account credentials in them.

Replace the generated sample content deliberately rather than deleting configuration files at random. Keep existing TypeScript and linting settings unless there is a specific requirement to change them. Save the package lockfile so teammates and continuous integration use a reproducible dependency set.

Understand components, props and local state

React components are functions that return descriptions of UI. JSX lets developers express a visual tree using syntax resembling HTML while combining JavaScript expressions. Components can receive props from parents, and state can store values that affect what is shown. When state changes, React schedules the necessary updates to the rendered interface.

Local state belongs in a component when it represents something the component manages, such as an expanded panel or input value. Shared application state requires a separate design, but not every form needs a global store. Avoid copying derived values into state unnecessarily. For example, a total that can be calculated from an existing list may be clearer as a calculation than as another independent state variable that can become inconsistent.

Use semantic HTML when possible. A button should be a real button, not a clickable generic element without keyboard support. Inputs need labels, and status or error text should be available to assistive technologies. React does not make a design accessible automatically; component authors still choose meaningful markup, focus behavior and feedback.

Build a small backend endpoint before connecting the UI

To keep the demonstration complete, create a separate file named server.cjs outside the browser application’s source directory. The following program uses Node.js’s built-in HTTP module to return a small JSON object at /api/message. It is suitable for local learning, not an authenticated production service:

const http = require('node:http');

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'application/json');
  if (req.method === 'GET' && req.url === '/api/message') {
    res.writeHead(200, { 'Cache-Control': 'no-store' });
    res.end(JSON.stringify({ message: 'Service is available' }));
    return;
  }
  res.writeHead(404);
  res.end(JSON.stringify({ error: 'Not found' }));
});

server.listen(3000, '127.0.0.1');

Run node server.cjs in another terminal. You can check http://127.0.0.1:3000/api/message directly. This endpoint contains no database, user accounts or authentication; do not extend it to sensitive production data without designing authorization, validation, logging and rate limiting appropriately.

The demonstration uses separate ports for the React development server and the backend. A browser applies origin rules when making cross-origin requests. During local development, a Vite proxy can forward requests beginning with /api to the backend without hardcoding a public server address into the UI. A development proxy is not a substitute for production routing or an authorization policy.

Configure the local proxy and fetch data safely

In the Vite project, update vite.config.ts so the existing React plugin remains configured and API calls can be proxied to the local server:

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

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:3000',
        changeOrigin: true
      }
    }
  }
});

Restart the development server if needed for the configuration to be picked up. This uses Vite’s development-server proxy. The final production build does not automatically deploy the Node server or create a proxy; the hosting arrangement must route API traffic appropriately.

Now replace src/App.tsx with this small component. It requests the JSON response, checks the HTTP status, validates the expected field and aborts the outstanding request when the effect is cleaned up:

import { useEffect, useState } from 'react';

type ApiMessage = { message: string };

export default function App() {
  const [status, setStatus] = useState('Loading...');

  useEffect(() => {
    const controller = new AbortController();

    async function load() {
      try {
        const response = await fetch('/api/message', {
          signal: controller.signal
        });
        if (!response.ok) {
          throw new Error('HTTP ' + response.status);
        }
        const data = (await response.json()) as ApiMessage;
        if (typeof data.message !== 'string') {
          throw new Error('Invalid API response');
        }
        if (!controller.signal.aborted) setStatus(data.message);
      } catch {
        if (!controller.signal.aborted) {
          setStatus('Unable to load the service message');
        }
      }
    }

    void load();
    return () => controller.abort();
  }, []);

  return (
    <main>
      <h1>API connection</h1>
      <p role="status">{status}</p>
    </main>
  );
}

With both processes running and the proxy configured, the page should display Service is available after the request completes. Stopping the Node server should instead reveal the error state. In React development mode, Strict Mode can perform additional setup and cleanup cycles for effects; the abort signal avoids treating an obsolete request result as current. It does not eliminate every possible race in a complex data application.

Understand data fetching, errors and security boundaries

A manual useEffect request demonstrates how a component interacts with an API. Larger apps may benefit from framework-supported data loading or a client-side caching library that handles deduplication, retries and coordination across routes. React’s effects documentation explains how effects synchronize with external systems. Do not treat every calculation or state update as a reason to add an effect.

The browser can validate inputs for better feedback, but the backend must validate them independently. Hiding an administrative menu does not prevent an unauthorized API call. Sensitive operations require proper authentication, authorization against the requested resource, protection of sessions or tokens, and auditability. If the frontend and backend run on different production origins, review CORS and cookie policy carefully. Cross-origin permissions do not grant business authorization.

Present loading, empty, error and success states clearly. A failed request may be caused by network loss, invalid data, a server failure or access denial, and different cases may warrant different guidance. Avoid revealing internal stack traces or secrets in a public error message. Logging should support troubleshooting without collecting more private information than necessary.

When choosing the backend, consider the actual domain rules, data model and deployment responsibilities. The broader backend technology options include runtimes, frameworks, databases and messaging systems; a React application can work with many of them through defined APIs.

Test, build and deploy the complete application

Test the frontend as a user would: can someone identify the current status, navigate using a keyboard, recover from a request failure and understand a returned error? Component tests can verify rendering and basic behavior. Integration tests should exercise the API contract, while end-to-end tests can confirm that a real browser and local or staging server work together.

Run the project’s checks and build scripts as provided in its package.json. For the standard Vite template, npm run build generates production assets in a distribution directory. npm run preview can inspect a local build but is not a complete production-hosting design. The generated static files need an appropriate web host, and the API needs its own secure deployment and routing.

For a client-side application that uses routing, the host may need a fallback for valid application routes; a missing file or actual unknown API path should not be blindly turned into a successful HTML response. Check the intended HTTP statuses, cache policy and security headers. Deploy configuration and backend migrations through a controlled process rather than manually editing public assets in an untracked way.

Do not commit secret files, use unreviewed packages or assume that a fast local development server predicts production performance. Measure the actual page on representative devices and connections. Keep an identified release artifact and a rollback strategy for both frontend and server changes, recognizing that data migrations require separate care.

Extend the demonstration one requirement at a time

First, replace the fixed API message with a list of synthetic records and display a meaningful empty state. Next, add a form and validate both its browser input and its server-side contract. Then implement a saved operation with a clear success response and safe retry behavior. Each stage should have a repeatable test and a documented error case.

As the application grows, separate presentation components, API functions and domain-specific state where that separation clarifies ownership. Avoid building a large abstraction system for a two-component demo. The aim of full-stack configuration is to produce an understandable contract between browser and server, not to use every framework feature immediately.

A dependable React front end starts with current tooling, clear component structure, accessible feedback and honest server boundaries. Vite makes the development workflow convenient, but software quality still depends on security, validated data, testing and deployment discipline. Use the official React and Vite documentation when upgrading rather than treating a one-time configuration example as a permanent platform specification.