The React frontend

The frontend is four TypeScript files, one stylesheet and one HTML file. Vite serves them in development, compiles them for production, and is configured to write the result into web/dist, the directory the Go binary embeds. React renders one component: a form, a list and an error line.

This page shows every file the build needs. The project was built in the Node image node:22-bookworm with Node v22.23.3 and npm 10.9.9, and the output below is that build: 30 modules, a 225.46 kB script and a 0.42 kB stylesheet. The Go half of the project was built, run and tested in the container that runs the rest of this course, and it is on the backend page.

The stack

React 19.3.1 and TypeScript 5.7.3 with Vite 6.4.6. Vite is the development server and the bundler: it serves the TypeScript sources as ES modules without a build step, and vite build produces a small set of static files with content hashes in their names. TypeScript is checked by tsc --noEmit in the build script, so a type error fails the build before Vite writes anything.

{ "name": "notes-frontend", "private": true, "version": "0.1.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc --noEmit && vite build", "preview": "vite preview" }, "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.4", "typescript": "~5.7.2", "vite": "^6.0.0" } }

Vite and the proxy

Three settings matter. The React plugin turns TSX into JavaScript. The proxy sends every /api request to the Go server on port 8080, so the browser sees one origin and CORS never happens in development. And outDir points at ../web/dist, which is where the embed directive of the next page looks.

import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' export default defineConfig({ plugins: [react()], server: { proxy: { '/api': 'http://127.0.0.1:8080', }, }, build: { outDir: '../web/dist', emptyOutDir: true, }, })

emptyOutDir is set because the directory is outside the Vite root: without it Vite refuses to clean a folder it does not own, and a stale bundle from an earlier build would stay in the binary.

{ "compilerOptions": { "target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true, "noEmit": true, "skipLibCheck": true, "types": ["vite/client"] }, "include": ["src", "vite.config.ts"] }

The browser loads one file, and it has nothing in it but an empty element and the module that fills it:

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Notes</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>

The API client

The Note type repeats the Go struct by hand. That duplication is deliberate and small: it is the contract, and a change on either side is a compile error in one language and a visible edit in the other. The generic request function sets the JSON header, reads the error object the backend sends, and returns void for a 204.

export type Note = { id: number title: string body: string } async function request<T>(path: string, init?: RequestInit): Promise<T> { const response = await fetch(path, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers }, }) if (!response.ok) { const problem = (await response.json().catch(() => ({ error: response.statusText }))) as { error?: string } throw new Error(problem.error ?? response.statusText) } if (response.status === 204) { return undefined as T } return (await response.json()) as T } export function listNotes(): Promise<Note[]> { return request<Note[]>('/api/notes') } export function createNote(title: string, body: string): Promise<Note> { return request<Note>('/api/notes', { method: 'POST', body: JSON.stringify({ title, body }), }) } export function deleteNote(id: number): Promise<void> { return request<void>(`/api/notes/${id}`, { method: 'DELETE' }) }

The component

One component holds the list, the two form fields and the error string. refresh reloads the list after a write, which is the simplest correct thing for a small list; a larger app would update the state from the created note and skip the round trip. Every call that can fail is inside a try, and the message the backend sent is what the reader sees.

import { useEffect, useState, type FormEvent } from 'react' import { createNote, deleteNote, listNotes, type Note } from './api' export default function App() { const [notes, setNotes] = useState<Note[]>([]) const [title, setTitle] = useState('') const [body, setBody] = useState('') const [error, setError] = useState('') async function refresh() { try { setNotes(await listNotes()) setError('') } catch (cause) { setError((cause as Error).message) } } useEffect(() => { void refresh() }, []) async function submit(event: FormEvent) { event.preventDefault() if (title.trim() === '') { return } try { await createNote(title, body) setTitle('') setBody('') await refresh() } catch (cause) { setError((cause as Error).message) } } async function remove(id: number) { try { await deleteNote(id) await refresh() } catch (cause) { setError((cause as Error).message) } } return ( <main> <h1>Notes</h1> <form onSubmit={submit}> <input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="title" aria-label="title" /> <textarea value={body} onChange={(event) => setBody(event.target.value)} placeholder="body" aria-label="body" /> <button type="submit">Add</button> </form> {error !== '' && <p className="error">{error}</p>} <ul> {notes.map((note) => ( <li key={note.id}> <strong>{note.title}</strong> <span>{note.body}</span> <button onClick={() => void remove(note.id)} aria-label={`delete ${note.title}`}> × </button> </li> ))} </ul> </main> ) }

main.tsx mounts the component into #root inside StrictMode, which runs effects twice in development on purpose, so a component that is not safe to mount twice shows its bug on the developer machine. The effect here only reads, so the double run costs one extra request and changes nothing. The stylesheet is imported here, which is the only place the CSS enters the bundle.

import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import App from './App' import './styles.css' const root = document.getElementById('root') if (root === null) { throw new Error('no #root element') } createRoot(root).render( <StrictMode> <App /> </StrictMode>, )

The stylesheet is deliberately plain: a system font, one card per note, a grid for the form. Vite writes it to one small CSS file, and the build output below shows how small.

body { font-family: system-ui, sans-serif; margin: 0; background: #f6f6f6; color: #222; } main { max-width: 640px; margin: 2rem auto; padding: 0 1rem; } form { display: grid; gap: 0.5rem; margin-bottom: 1.5rem; } input, textarea, button { font: inherit; padding: 0.5rem; } ul { list-style: none; padding: 0; display: grid; gap: 0.5rem; } li { display: flex; gap: 0.75rem; align-items: baseline; background: #fff; padding: 0.75rem; border-radius: 6px; } li span { color: #555; flex: 1; } .error { color: #a00; }

The commands

Step Command Result Where it ran
Install cd frontend && npm install Ran: node_modules and package-lock.json, 7 top-level packages node:22-bookworm
Develop npm run dev Not run: a dev server needs a browser session; the proxy it would use is in the config above No
Type-check and build npm run build Ran: tsc --noEmit silent, 30 modules, output below node:22-bookworm
Embed and serve go build -o notes ./cmd/server Ran with the placeholder web/dist; the same command embeds the built one This container

The seven top-level packages are the two runtime dependencies and the five development ones named in package.json: react, react-dom, @types/react, @types/react-dom, @vitejs/plugin-react, typescript and vite. The install also writes a lock file, so the next machine resolves the same tree.

The build output

npm run build

> notes-frontend@0.1.0 build
> tsc --noEmit && vite build

vite v6.4.6 building for production...
transforming...
✓ 30 modules transformed.
rendering chunks...
computing gzip size...
../web/dist/index.html 0.40 kB │ gzip: 0.27 kB
../web/dist/assets/index-<hash>.css 0.42 kB │ gzip: 0.27 kB
../web/dist/assets/index-<hash>.js 225.46 kB │ gzip: 70.17 kB
✓ built in 2.00s

The numbers are the build of these eight files in node:22-bookworm: the same component, client, entry point and stylesheet a reader has above. The two asset names carry a content hash and change whenever the file changes, so they are written as <hash> here and a reader will see different names. The stylesheet is fifty lines of source, 619 bytes as the build extracted it, and it compiles to 0.42 kB, 0.27 kB gzipped.

What the build proves

Three things. tsc --noEmit ran before Vite and stayed silent, so the TypeScript in api.ts and App.tsx agrees with itself and with the React types. Vite transformed 30 modules into one script and one stylesheet under web/dist/assets, which means the import graph is complete: a missing file or a bad import path fails here. And web/dist/index.html points at the hashed script, which is the file the Go binary embeds and serves on the next page.

The next page takes the built directory and puts it inside the Go binary: embed and deploy.

The Go code of this project was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container. The frontend was built in the node:22-bookworm Docker image with Node v22.23.3 and npm 10.9.9, which resolved the ranges in package.json to vite 6.4.6, react 19.3.1, react-dom 19.3.1, typescript 5.7.3, @vitejs/plugin-react 4.7.0, @types/react 19.3.0 and @types/react-dom 19.3.0. Those are the versions at the time of writing; a later npm install may resolve newer patch releases inside the same ranges.

Article author: Arthur Isaev