A coding agent can change a React component in seconds, but checking that the change works takes longer. A response with an unexpected shape can crash the page, and a bad import can break the production build.
With React, TypeScript, and Vite 8, each of these fails at a known point. The dev server reports module errors when the page loads, tsc -b stops a build that has type errors, and a Vercel Preview Deployment tests real network requests. This guide starts from the official react-ts template, adds types for API data, and deploys to Vercel.
Copy link to headingPrerequisites
Before you begin, make sure you have:
Node.js 24+ and a package manager (e.g., pnpm)
Vercel CLI installed (
npm i -g vercel)
Copy link to headingScaffold a Vite 8 application
Use the Vite CLI to create the project:
npm create vite@9.3.4 my-app -- --template react-ts --no-immediateGo to the new project directory:
cd my-appCopy link to headingUnderstand the project structure
In the official template, index.html loads src/main.tsx, which renders App from src/App.tsx. Vite loads vite.config.ts separately to register the React plugin.
Open
index.html, the app's entry point during development. The<div id="root"></div>is the Document Object Model (DOM) node where React mounts the app. The module script loads/src/main.tsx.Open
src/main.tsx. It imports the global stylesheet andApp, finds therootelement, and renders<App />inside ReactStrictMode.Open
src/App.tsx. It defines the root app component. You'll replace its contents when you add the repository card.Open
vite.config.ts. Theplugins: [react()]entry registers@vitejs/plugin-reactfor development and production builds.
The basic Vite and React setup includes hot module replacement (HMR) and Oxlint rules.
These excerpts show the HTML entry point and how React mounts the app.
<!-- index.html --><div id="root"></div><script type="module" src="/src/main.tsx"></script>import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import './index.css'import App from './App.tsx'
createRoot(document.getElementById('root')!).render( <StrictMode> <App /> </StrictMode>,)Copy link to headingSeparate browser and Node TypeScript boundaries
The root tsconfig.json references two TypeScript projects. One covers the browser code, and the other covers the Node.js configuration.
The root config lists no source files of its own. The references array lets TypeScript check the app and Node.js projects in the same build.
{ "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ]}In tsconfig.app.json, include points to src. This config adds DOM and Vite client types, enables the automatic React JSX transform, and uses bundler-style module resolution.
tsconfig.node.json includes only vite.config.ts. It loads Node.js types and uses the nodenext module setting. The browser project has its own type configuration.
Both projects set noEmit so TypeScript can check the code without writing JavaScript. Vite transforms and bundles it.
Copy link to headingStart the on-demand development server
After npm install, run npm run dev to serve modules on demand and pre-bundle dependencies with Rolldown.
The rest of the tutorial uses npm. Install the dependencies in package.json and commit package-lock.json so local builds, continuous integration (CI), and Vercel can use the same locked versions. If you use another package manager, run its equivalent commands and commit its lockfile.
npm installnpm run devOpen the URL from the terminal, usually http://localhost:5173. You should see the starter screen. Vite serves modules as the browser requests them, so the dev server doesn't have to build the whole app first.
When the dependency cache is empty, Vite scans your source for bare imports that resolve to node_modules. Rolldown uses those imports for dependency pre-bundling during development. The production command runs a separate optimized build.
Copy link to headingVerify updates with Fast Refresh
Change the starter heading to see React Fast Refresh update the page without reloading it.
Keep npm run dev running and increment the counter in the starter app. In src/App.tsx, change the <h1> from Get started to Vite + React + TypeScript, then save.
<h1>Vite + React + TypeScript</h1>The heading should change without a page reload, and the count should stay the same. Vite sends the updated module over its HMR channel. @vitejs/plugin-react then applies Fast Refresh to eligible React components. The plugins: [react()] setting enables the plugin. This template uses @vitejs/plugin-react v6, which uses Oxc to transform components for React Refresh.
Copy link to headingBuild a typed data component
Replace the starter screen with a component that fetches live data from the GitHub repository endpoint. The component has typed props and checks the response at runtime. It uses AbortController to cancel requests and shows a loading message, repository data, or an error.
Replace the contents of src/App.tsx with:
import { useEffect, useState } from 'react'import './App.css'
interface RepositoryCardProps { owner: string name: string}
interface GitHubRepository { full_name: string description: string | null html_url: string language: string | null stargazers_count: number}
function isGitHubRepository(value: unknown): value is GitHubRepository { if (typeof value !== 'object' || value === null) return false
const repository = value as Record<string, unknown>
return ( typeof repository.full_name === 'string' && (typeof repository.description === 'string' || repository.description === null) && typeof repository.html_url === 'string' && (typeof repository.language === 'string' || repository.language === null) && typeof repository.stargazers_count === 'number' )}
type RepositoryState = | { status: 'loading' } | { status: 'success'; repository: GitHubRepository } | { status: 'error'; message: string }
function RepositoryCard({ owner, name }: RepositoryCardProps) { const [state, setState] = useState<RepositoryState>({ status: 'loading' })
useEffect(() => { const controller = new AbortController()
async function loadRepository(): Promise<void> { setState({ status: 'loading' })
try { const response = await fetch( `https://api.github.com/repos/${owner}/${name}`, { signal: controller.signal }, )
if (!response.ok) { throw new Error(`Request failed with status ${response.status}`) }
const data: unknown = await response.json()
if (!isGitHubRepository(data)) { throw new Error("The response didn't match the repository shape") }
if (controller.signal.aborted) return
setState({ status: 'success', repository: data }) } catch (error: unknown) { if (controller.signal.aborted) return
const message = error instanceof Error ? error.message : 'An unexpected error occurred' setState({ status: 'error', message }) } }
void loadRepository() return () => controller.abort() }, [owner, name])
if (state.status === 'loading') { return <p role="status">Loading repository...</p> }
if (state.status === 'error') { return <p role="alert">Couldn't load the repository: {state.message}</p> }
const { repository } = state
return ( <article className="repository-card"> <p className="eyebrow">GitHub repository</p> <h2>{repository.full_name}</h2> <p>{repository.description ?? 'No description provided.'}</p> <dl> <div> <dt>Language</dt> <dd>{repository.language ?? 'Unknown'}</dd> </div> <div> <dt>Stars</dt> <dd>{repository.stargazers_count.toLocaleString()}</dd> </div> </dl> <a href={repository.html_url}>View repository</a> </article> )}
function App() { return ( <main> <header> <p className="eyebrow">React + TypeScript + Vite</p> <h1>A typed repository card</h1> <p> This component fetches live repository data and renders explicit loading, error, and success states. </p> </header> <RepositoryCard owner="vercel" name="vercel" /> </main> )}
export default AppKeep src/index.css for the custom properties. Replace src/App.css with the following styles:
main { width: min(720px, calc(100% - 40px)); margin: 0 auto; padding: 72px 0; text-align: left;}
header { margin-bottom: 32px;}
header > p:last-child { max-width: 60ch;}
.eyebrow { margin-bottom: 8px; color: var(--accent); font-family: var(--mono); font-size: 14px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase;}
.repository-card { padding: 24px; border: 1px solid var(--border); border-radius: 12px; background: var(--social-bg); box-shadow: var(--shadow);}
.repository-card h2 { margin-bottom: 12px;}
.repository-card dl { display: flex; gap: 32px; margin: 24px 0;}
.repository-card dt { color: var(--text); font-size: 14px;}
.repository-card dd { margin: 4px 0 0; color: var(--text-h); font-weight: 700;}
.repository-card a { color: var(--accent); font-weight: 700;}RepositoryCardProps defines the component's inputs. RepositoryState defines the fields each status can have. Check response.ok because fetch resolves even on HTTP errors such as 404 and 500. The Effect cleanup aborts the request if the component unmounts or its inputs change. Both abort checks keep canceled requests from updating state.
The starter wraps App in StrictMode. In development, React runs an extra setup and cleanup cycle when the component first mounts. The cleanup aborts the first pending GitHub request before the next setup. In production, React runs setup once on mount.
Save both files. You'll see a loading message, then repository data or an error.
Copy link to headingValidate network payloads at runtime
A TypeScript response type helps catch type errors in your app. It can't check what an HTTP response contains at runtime.
A type assertion on response.json() tells TypeScript to treat the result as GitHubRepository:
const data = (await response.json()) as GitHubRepositoryTypeScript removes type assertions during compilation, so this line checks nothing at runtime. It won't reject a response with a missing full_name or a string stargazers_count.
The app passes data as unknown to isGitHubRepository. The guard checks the required strings, nullable fields, and numeric star count before the app sets the state to success. Once the guard passes, TypeScript narrows data to GitHubRepository and checks property access.
Copy link to headingEnforce type checks before production builds
The template's npm run build script runs tsc -b before vite build. A type error prevents the build from starting bundling.
Vite converts each requested TypeScript file to JavaScript without checking types. Your editor or a separate TypeScript process can report errors while the dev server continues to serve the module.
To see the difference, introduce a type error in src/App.tsx:
<RepositoryCard owner="vercel" name={42} />The app can still run in the browser because Vite can convert the file to JavaScript. In another terminal, run the production build:
npm run buildtsc -b checks both TypeScript projects and reports TS2322: Type 'number' is not assignable to type 'string'. The generated script is tsc -b && vite build, so vite build starts only after the type check succeeds.
Restore name="vercel" before continuing. The dev server transforms the file you changed. The build checks types in both TypeScript projects.
Copy link to headingInspect the dist bundle
npm run build checks types, bundles the app, and writes the optimized output to dist.
Run the command again after fixing the deliberate prop error.
npm run buildAfter tsc -b succeeds, Vite writes the static assets and reports their file names and sizes.
List the build output without changing any files:
find dist -maxdepth 2 -type f -printLook for dist/index.html and JavaScript and CSS bundles with content hashes in their names. The HTML loads those bundles in place of /src/main.tsx.
The build generates dist. Make edits under src and rebuild, since the next build replaces direct edits in dist.
Copy link to headingPreview the built files
Once the build succeeds, serve dist locally for a final browser check:
npm run previewThe script runs vite preview, usually on port 4173. Check that the app loads from dist. The browser fetches GitHub data separately. If GitHub is down or rate-limits the request, the card shows an error even when the bundle works.
Use the preview command to inspect the build locally. It isn't a production server. Press Ctrl+C when you're done.
Vercel builds the app from source in its own environment. Commit the lockfile and set "engines": { "node": "24.x" } in package.json so Vercel matches your local Node.js major version. Test the app in a Preview Deployment to catch differences that a local dist preview can't show.
Copy link to headingDeploy the application to Vercel
The Git integration creates Preview Deployments by default when you push to a non-production branch or open a pull request. Updates to the configured production branch create Production Deployments. A pull request from a fork may need authorization.
Commit your changes, push them to a supported Git provider, and import the repository into Vercel. Before deploying, confirm the Vite preset, the npm run build command, and the dist output directory.
After the first deployment, make a change on a new branch. Run npm run build and test the app locally in your browser. Push the branch, open its Preview URL, and check that the repository card loads. Teammates can review the same change at that URL.
Choose a method based on how you want to deploy or manage the app:
Git ties deployments to commits and adds Preview URLs to pull requests. To deploy the current directory, use the Vercel CLI:
vercelThe CLI prints the deployment URL to standard output. After the first deployment, vercel creates a Preview Deployment by default. Use --prod for Production:
vercel --prodUse the Vercel REST API to create deployments, read deployment data, manage domains, and update project resources over HTTP.
Vercel MCP is Vercel's official remote Model Context Protocol (MCP) server. It's available on all plans at https://mcp.vercel.com.
Connect a supported MCP client through OAuth to inspect deployments and build logs. Some connections can also create deployments from Git or files. Use Git to deploy from a branch, the CLI to deploy a local directory, or the REST API to deploy from your own tools.
If you add a client-side router to this single-page application (SPA), direct requests to paths such as /settings/profile need to load index.html. Add this SPA rewrite in vercel.json at the project root. If you enable cleanUrls, use / as the destination.
{ "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]}This app has no client-side routes, so it doesn't need the rewrite. If you add nested routes, apply the rewrite and open one of those URLs directly in a Preview Deployment.
Copy link to headingFrequently asked questions
Copy link to headingWhich Node.js version does Vite 8 require?
Vite 8 accepts Node.js ^20.19.0 || >=22.12.0. Use Node.js 24 for this tutorial. Vercel has deprecated Node.js 20 for builds and functions.
Copy link to headingDoes Vite type-check TypeScript during development?
No. Vite converts requested modules to JavaScript. Your editor or a separate TypeScript process can report type errors. The template's production script runs tsc -b before vite build.
Copy link to headingIs vite preview a production server?
No. vite preview serves the built dist files for local inspection. Vercel serves the deployed production build.
Copy link to headingDoes a Vite app need Vercel configuration?
Usually not. Vercel detects a standard Vite app like this one and applies the default build settings. If you add a client-side router, use a vercel.json rewrite so direct visits to those routes work.
Keep the dev server running to check Fast Refresh. Run npm run build to check types and produce the bundle, then open the Preview URL to test the deployed app. If the app behaves differently on Vercel, check how it runs in the browser and compare environment variables, build settings, and dependency versions.