Start learning free

LESSON 45 OF 58 · FULL-STACK: SHIPPING IT

One Server for Both

Practice

While you build the shop, two programs run: Vite serves the storefront on http://localhost:5173, and Express answers the API on http://localhost:3000. In production there is no Vite dev server. The storefront is built once into plain files in client/dist: index.html and assets/app-4f2a.js. Your Express server can send those files itself, so the browser gets the page and the API from one origin.

express.static(folder) is a middleware that answers a request whose path is a file in that folder, and passes every other request on. A request for / gets the folder's index.html. For example, with a folder public inside server/ that holds logo.png:

app.use(express.static(path.join(__dirname, "public")));
// GET /logo.png  →  200  the file server/public/logo.png
// GET /nope.png  →  passed on to the next handler

__dirname is the folder of the file that runs, here server/. path.join glues folder names together, and ".." goes up one folder. Put the static files after the /api handlers, so API requests are answered first.

Your server must answer:

GET /                    →  200  text/html         the file client/dist/index.html
GET /assets/app-4f2a.js  →  200  text/javascript   the file client/dist/assets/app-4f2a.js
GET /api/products/1      →  200  application/json  {"id": 1, "name": "Mug", "price": 12, "stock": 10}

Your task: in server/app.js, below the /api 404 handler, build the path of client/dist and serve its files with express.static.


Assignment
Follow the Coding Tutorial to make dist, the path of client/dist, and serve its files from the shop's server.


Hint
From server/, client/dist is one folder up, then client, then dist: path.join takes each part as its own string.


STEP 1 OF 2
    Ctrl + Enter to check