Start learning free

LESSON 47 OF 58 · FULL-STACK: SHIPPING IT

Production Is Different in JavaScript

Practice

The same server/app.js runs on your computer and on a host. Hosting platforms set the environment variable NODE_ENV to "production". Your code reads it as process.env.NODE_ENV and can behave differently there.

One origin, no CORS. In production the server sends the storefront itself, so no page needs Access-Control-Allow-Origin. Only development, where Vite runs on http://localhost:5173, needs allowDevOrigin. The starting code still defines it, but no longer uses it.

HTTPS ends at the host's proxy. Your app gets plain HTTP with the header X-Forwarded-Proto: https. app.set("trust proxy", 1) tells Express to believe that one proxy, so req.secure is true. Then a session cookie with secure: true is sent marked Secure: the browser only sends it back over HTTPS.

A real secret. In production, the fallback "dev-secret-123" would let anyone who reads the code sign their own session cookie. Better to refuse to start. An error thrown while a file loads stops the server before it listens:

const port = process.env.PORT || 3000;
if (!process.env.PAYMENTS_KEY) {
  throw new Error("PAYMENTS_KEY is missing");
}

The check starts your server three ways:

development (NODE_ENV not set)
  GET /api/products/1 from http://localhost:5173  →  200  Access-Control-Allow-Origin: http://localhost:5173
  POST /api/login  →  200  Set-Cookie: connect.sid=…; Path=/; HttpOnly; SameSite=Lax
NODE_ENV=production, no SESSION_SECRET
  it does not start: Error: SESSION_SECRET is missing
NODE_ENV=production, its own SESSION_SECRET
  GET /api/products/1 from http://localhost:5173  →  200  Access-Control-Allow-Origin: None
  POST /api/login through the HTTPS proxy  →  200  Set-Cookie: connect.sid=…; Path=/; HttpOnly; Secure; SameSite=Lax

The check prints None when an answer has no such header.

Your task: in server/app.js, make isProduction, refuse to start in production without SESSION_SECRET, trust the proxy in production, use allowDevOrigin only outside production, and make the session cookie secure in production.


Assignment
Follow the Coding Tutorial to make the shop's server behave safely in production and keep working in development.


Hint
Type each if empty first, then fill it in. !process.env.SESSION_SECRET is true when the variable is missing.


STEP 1 OF 8
    Ctrl + Enter to check

    Fsship Production Settings in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free