Start learning free

LESSON 123 OF 161 · FRONTEND: THE PROJECT AROUND THE CODE

Settings per Environment

Practice

Some values change with where the page runs. On your computer, npm run dev serves the page, and its proxy carries /api to the shop's API. On the real site, the API has its own address. Instead of editing the code before every build, you put such values in .env files: .env is read in every mode, and .env.production is read only by npm run build, after .env, so its lines win.

Vite hands these settings to your code as import.meta.env, but only the names that start with VITE_. Their values are pasted into the page's JavaScript, which every visitor downloads, so a secret must never get a VITE_ name. Vite adds settings of its own too: MODE, and DEV and PROD, which are true or false. For example, with another value:

# .env
VITE_SHOP_NAME=Corner Shop (test)

# .env.production
VITE_SHOP_NAME=Corner Shop

// in a component
const shopName = import.meta.env.VITE_SHOP_NAME;

The check opens the page with npm run dev, then prints import.meta.env for both modes and the request the built page would make. The grader can't build the project or reach the real site, so that last line is where the request would go. Until getProducts returns the products, the page is empty with an error. When you're done, it prints:

> open the page
  console.log: Development: the API is at /api
  request: GET /api/products -> 200
  …
    text: 8 products
> import.meta.env with npm run dev (mode "development")
  BASE_URL "/", DEV true, MODE "development", PROD false, SSR false
  VITE_API_URL "/api" (from .env)
  not in the browser: DEPLOY_TOKEN (its name does not start with VITE_)
> import.meta.env with npm run build (mode "production")
  BASE_URL "/", DEV false, MODE "production", PROD true, SSR false
  VITE_API_URL "https://api.cornershop.example/api" (from .env.production)
  not in the browser: DEPLOY_TOKEN (its name does not start with VITE_)
  the built page at https://cornershop.example/ asks: GET https://api.cornershop.example/api/products

Your task: in src/api.js, read import.meta.env.VITE_API_URL into a constant API_URL, log where the API is only in development, and make getProducts fetch the products from that address and return the JSON.


Assignment
Follow the Coding Tutorial to read the API's address from the environment, log it while you develop, and use it in getProducts.


Hint
Build the request's address from the setting plus the path, so it changes with the mode. Never give DEPLOY_TOKEN, or any secret, a VITE_ name.


STEP 1 OF 5
    Ctrl + Enter to check