Chapter-7: Build the Storefront with React
Sample code
The complete, tested code for this chapter is in samples/microservices/storefront. Use it to compare against your own work.
Introduction
In this lab, we will build the Storefront, the website our customers use to browse the products and fill their shopping cart. Where the Admin site builds every page on the server, the Storefront is a single-page application (SPA) written with React: the browser downloads the app once, and JavaScript then draws and updates the page without reloading it.
We will create the project with Vite, write a small store page, and package it with a multi-stage Dockerfile into an nginx image that serves the finished site.
Technical Scenario
As a Frontend (FE) developer, you have been assigned the task of building the Storefront of our online store. Customers use it to:
- see the list of products with their prices,
- add products to a cart and change the quantities,
- place the order.
The Storefront owns no data. In the finished store, it reads the products from the Product API and sends orders to the Order API, both through the gateway. Because the gateway serves the Storefront and the APIs on one address, the app calls relative /api/... URLs and needs no runtime configuration, such as an API address per environment (Chapter-15). In this chapter it runs on its own: the product list comes from a static JSON file served with the site, the cart lives in the page, and the Place order button stays disabled. Chapter-14 replaces the static file with the live products from the Product API and connects the button to the Order API.
Objective
In this exercise, our objective is to accomplish and learn the following tasks:
- Step-1: Install Node.js and NPM
- Step-2: Create a new React application
- Step-3: Build the store page
- Step-4: Add the nginx configuration and Dockerfile
- Step-5: Docker build and run locally
- Step-6: Push docker container to ACR (optional)
Prerequisites
- The
microservicesrepository from Chapter-4, cloned locally - Node.js 24 (LTS) and npm
- Docker Desktop
- Visual Studio Code or another code editor
- For the optional step only: an Azure Container Registry (ACR)
Architecture Diagram
The following diagram shows how the Storefront is built and served. Node.js and Vite are only needed to build the site; the container that runs it holds nothing but nginx and the finished files.
flowchart LR
subgraph build ["Build stage: node:24-alpine"]
src["React source<br/>src/, public/"] -->|npm run build| dist["dist/<br/>HTML, JS, CSS,<br/>products.json"]
end
subgraph container ["Container: sample/storefront"]
nginx["nginx-unprivileged<br/>port 8080"]
end
dist -->|COPY --from=build| nginx
customer([Customer: browser]) -->|"GET /"| nginx
Step-1: Install Node.js and NPM
To build a React app, you need Node.js and npm (Node Package Manager), which comes with it. If you followed Chapter-5, you already have them.
Otherwise, download the LTS installer from https://nodejs.org/en/download, or install it from the command line:
-
Windows with Chocolatey (run as administrator):
-
macOS with Homebrew:
Follow the instructions Homebrew prints to add it to your
PATH.
Verify the installation:
Step-2: Create a new React application
We create the project with Vite, a fast build tool for modern web apps. (The older create-react-app tool is deprecated.) From the root of your microservices repository, run:
# output (trimmed)
create-vite v9.3.4
│
◇ Scaffolding project in ...\storefront...
│
└ Done. Now run:
cd storefront
npm install
npm run dev
--template react picks the React template with JavaScript, and --no-interactive accepts the defaults without asking questions. Install the packages:
cd storefront
npm install
# output
added 74 packages, and audited 75 packages in 11s
20 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
The template comes with a demo page. Delete the files we won't use:
src/assets/(the whole folder)src/App.csspublic/icons.svgREADME.md
In index.html, change the page title to <title>Store</title>.
Step-3: Build the store page
The product list
Create public/products.json. Vite copies everything in public unchanged into the finished site, so the browser can fetch this file from /products.json:
[
{ "id": 1, "sku": "MUG-001", "name": "Coffee mug", "description": "Ceramic mug, 350 ml.", "price": 9.99 },
{ "id": 2, "sku": "TEE-001", "name": "T-shirt", "description": "Cotton T-shirt with the store logo.", "price": 19.99 },
{ "id": 3, "sku": "CAP-001", "name": "Baseball cap", "description": "Adjustable cotton cap, one size.", "price": 14.50 },
{ "id": 4, "sku": "BAG-001", "name": "Tote bag", "description": "Reusable canvas tote bag.", "price": 12.00 },
{ "id": 5, "sku": "BTL-001", "name": "Water bottle", "description": "Stainless steel bottle, 500 ml.", "price": 24.95 }
]
It has exactly the shape the Product API returns from GET /products, so switching to the real API later only changes the address we fetch from.
The app
Replace src/App.jsx with:
import { useEffect, useState } from 'react'
const formatPrice = (price) => price.toFixed(2)
function ProductList({ products, onAdd }) {
return (
<ul className="products">
{products.map((product) => (
<li key={product.id} className="product">
<h3>{product.name}</h3>
<p>{product.description}</p>
<div className="product-footer">
<span className="price">{formatPrice(product.price)}</span>
<button type="button" onClick={() => onAdd(product.id)}>
Add to cart
</button>
</div>
</li>
))}
</ul>
)
}
function Cart({ lines, onAdd, onRemove }) {
const total = lines.reduce((sum, line) => sum + line.price * line.quantity, 0)
return (
<aside className="cart">
<h2>Your cart</h2>
{lines.length === 0 ? (
<p>Your cart is empty.</p>
) : (
<ul>
{lines.map((line) => (
<li key={line.id}>
<span>{line.name}</span>
<span className="quantity">
<button type="button" onClick={() => onRemove(line.id)} aria-label={`Remove one ${line.name}`}>
-
</button>
{line.quantity}
<button type="button" onClick={() => onAdd(line.id)} aria-label={`Add one ${line.name}`}>
+
</button>
</span>
<span>{formatPrice(line.price * line.quantity)}</span>
</li>
))}
</ul>
)}
<p className="total">Total: {formatPrice(total)}</p>
{/* A span carries the tooltip, because disabled buttons don't show one in every browser */}
<span title="Ordering is not available yet">
<button type="button" disabled>
Place order
</button>
</span>
</aside>
)
}
function App() {
const [products, setProducts] = useState([])
const [error, setError] = useState(null)
// The cart maps a product id to a quantity, for example { 1: 2 }
const [cart, setCart] = useState({})
useEffect(() => {
let ignore = false
// Temporary: a static file served with the site.
// A later chapter loads the products from the Product API instead.
fetch('/products.json')
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return response.json()
})
.then((data) => {
if (!ignore) setProducts(data)
})
.catch((err) => {
if (!ignore) setError(err.message)
})
return () => {
ignore = true
}
}, [])
function addToCart(id) {
setCart((current) => ({ ...current, [id]: (current[id] ?? 0) + 1 }))
}
function removeFromCart(id) {
setCart((current) => {
const { [id]: quantity, ...rest } = current
return quantity > 1 ? { ...current, [id]: quantity - 1 } : rest
})
}
const cartLines = products
.filter((product) => cart[product.id])
.map((product) => ({ ...product, quantity: cart[product.id] }))
return (
<>
<header>
<h1>Store</h1>
</header>
<main>
<section>
<h2>Products</h2>
{error && <p role="alert">Could not load the products: {error}</p>}
<ProductList products={products} onAdd={addToCart} />
</section>
<Cart lines={cartLines} onAdd={addToCart} onRemove={removeFromCart} />
</main>
</>
)
}
export default App
The page is made of three React components:
ProductListshows a card for each product with an Add to cart button.Cartshows the cart lines, buttons to change the quantities, the total, and the Place order button, which is disabled for now.Appholds the state: the products, a possible error, and the cart. When the state changes, React redraws the parts of the page that depend on it.
useEffect with an empty list [] runs once, after the page first appears, and fetches the products. The ignore flag is the React way to ignore a response that arrives after the component is gone. The cart is stored as product ids and quantities only; cartLines combines it with the product list every time the page is drawn, so the cart can never show a stale name or price.
The styles
Replace src/index.css with the plain CSS from the sample. It lays the products out in a grid with the cart beside them, stacks them on narrow screens, and follows the light or dark mode of your operating system. src/main.jsx from the template already imports it, so it needs no changes.
Try it
Start the Vite development server:
npm run dev
# output
> storefront@0.0.0 dev
> vite
VITE v8.3.5 ready in 357 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
Open http://localhost:5173/, add a few products to the cart and change the quantities:
While the development server runs, every change you save appears in the browser at once. Press Ctrl+C to stop it.
Step-4: Add the nginx configuration and Dockerfile
The development server is great while coding, but it is not meant to serve real users. For production, npm run build compiles the app into a few static files in the dist folder, and any web server can serve them. We use nginx, a small and very fast web server.
The nginx configuration
Create nginx.conf in the storefront folder:
server {
# nginx-unprivileged runs as a normal user, which may not open ports below 1024
listen 8080;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
# Serve the file if it exists, otherwise index.html, so the React app
# handles every page address (single-page application fallback)
try_files $uri $uri/ /index.html;
}
}
rootis the folder nginx serves files from; the Dockerfile copies our built site there.try_filesis the SPA fallback. A single-page application has one real HTML file, but as it grows it shows different pages at addresses like/orders/123. No such file exists on the server, so without this line nginx would answer404when a user reloads that page or opens a bookmark.try_filesfirst looks for a matching file (such as/products.jsonor a JavaScript file), and otherwise returnsindex.html, so the React app starts and shows the right page.listen 8080instead of the usual port 80: see the next section.
The Dockerfile
Create a Dockerfile:
# Build stage: compile the static site with Vite
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Serve stage: nginx running as a non-root user on port 8080
FROM nginxinc/nginx-unprivileged:alpine AS final
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 8080
USER nginx
This is a multi-stage Dockerfile:
- The build stage uses Node.js to install the dependencies (
npm ci, including the development tools such as Vite) and to build the static files (npm run build) into/app/dist. - The final stage starts from a clean nginx image and copies in only two things: our
nginx.conf, which replaces nginx's default site, and the built files from the build stage. The final image contains no Node.js, nonode_modulesand no source code, so it is small, and no development server runs in the container.
Why nginxinc/nginx-unprivileged instead of the official nginx image? The official image starts as root so that it can open port 80; on Linux only root may open ports below 1024. The unprivileged variant, published by the nginx team, runs as the nginx user from the start and therefore listens on port 8080. Running as a normal user means a flaw in the web server doesn't hand an attacker root rights in the container. USER nginx makes that choice visible in our own Dockerfile.
Finally, add a .dockerignore file so that your local node_modules and dist folders are not sent to Docker. The build stage creates both itself:
Step-5: Docker build and run locally
Build the image:
# output (trimmed)
#5 [build 1/6] FROM docker.io/library/node:24-alpine@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5
...
#7 [final 1/3] FROM docker.io/nginxinc/nginx-unprivileged:alpine@sha256:b5047b9b76845eac124358373c6852377c52e4b05834a47647e955dd91cb8f1e
...
#11 [build 4/6] RUN npm ci
#11 3.920 added 24 packages, and audited 25 packages in 3s
...
#13 [build 6/6] RUN npm run build
#13 0.902 vite v8.3.5 building client environment for production...
#13 0.931 transforming...
#13 1.041 ✓ 16 modules transformed.
#13 1.114 rendering chunks...
#13 1.170 computing gzip size...
#13 1.178 dist/index.html 0.45 kB │ gzip: 0.29 kB
#13 1.178 dist/assets/index-CUmT-K5S.css 1.85 kB │ gzip: 0.79 kB
#13 1.178 dist/assets/index-CTa8xR9A.js 221.68 kB │ gzip: 69.31 kB
#13 1.178
#13 1.180 ✓ built in 275ms
#13 DONE 1.3s
The build stage turned all our source code and packages into three files: one HTML, one CSS and one JavaScript file. Look at the size of the final image:
docker images sample/storefront
# output
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
sample/storefront:1.0 08440603b613 61.1MB 0B
About 61 MB, because the Node.js tools stayed behind in the build stage.
Run the container, mapping port 8080 on your machine to port 8080 in the container:
# output (first lines)
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: can not modify /etc/nginx/conf.d/default.conf (read-only file system?)
/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2026/11/15 21:16:53 [notice] 1#1: using the "epoll" event method
The can not modify /etc/nginx/conf.d/default.conf line is expected and harmless. At startup the image tries to add an IPv6 listen line to the default site, but that file is now our own nginx.conf, which was copied in as root, so the nginx user may not change it. Our site keeps exactly the configuration we wrote.
Check that nginx runs as the non-root user:
Test the site with curl. The home page:
curl -I http://localhost:8080/
# output
HTTP/1.1 200 OK
Server: nginx/1.31.7
Date: Sun, 15 Nov 2026 21:16:57 GMT
Content-Type: text/html
Content-Length: 455
...
The product list:
curl http://localhost:8080/products.json
# output
[
{ "id": 1, "sku": "MUG-001", "name": "Coffee mug", "description": "Ceramic mug, 350 ml.", "price": 9.99 },
{ "id": 2, "sku": "TEE-001", "name": "T-shirt", "description": "Cotton T-shirt with the store logo.", "price": 19.99 },
{ "id": 3, "sku": "CAP-001", "name": "Baseball cap", "description": "Adjustable cotton cap, one size.", "price": 14.50 },
{ "id": 4, "sku": "BAG-001", "name": "Tote bag", "description": "Reusable canvas tote bag.", "price": 12.00 },
{ "id": 5, "sku": "BTL-001", "name": "Water bottle", "description": "Stainless steel bottle, 500 ml.", "price": 24.95 }
]
And the SPA fallback: an address that is not a file still returns the HTML page, with status 200 instead of 404:
curl -s -o /dev/null -w "%{http_code} %{content_type}\n" http://localhost:8080/orders/123
# output
200 text/html
Open http://localhost:8080/ in your browser. You see the same store page as with the development server, now served by nginx from the container.
Running the sample code instead of your own
The finished sample in samples/microservices/storefront has no products.json any more: since Chapter-14 it loads the live products from the Product API through /api/products/. Run on its own like this, it shows "The products could not be loaded" instead of the list, and /products.json returns the HTML page. Run it with the store's compose file to see the products.
When you are done, remove the container:
Step-6: Push docker container to ACR
This step is optional. It pushes the image to Azure Container Registry (ACR), the same way as in Chapter-4; replace the example registry name acr1dev with your own.
-
Log in to Azure and to your registry:
-
Tag the image with the full name of your registry, and push it:
docker tag sample/storefront:1.0 acr1dev.azurecr.io/sample/storefront:1.0 docker push acr1dev.azurecr.io/sample/storefront:1.0Output (example; layer ids and digest differ on your machine):
-
Verify the image and its tag in the registry:
The output lists the tag
1.0.
Conclusion
In this chapter, we built the Storefront, the React single-page application where customers browse the products and fill their cart. We used Vite to create and build the app, and a multi-stage Dockerfile to serve the finished files from a small nginx image that runs as a non-root user on port 8080, with a fallback that lets the React app handle every page address.
We now have all four parts of the store that customers and staff use: the Product API, the Order API, the Admin site and the Storefront. Each one runs on its own, with its own temporary data. In the next chapters, we give the services real databases and then connect everything into one system.
