Menu
CoddyTech

Configuration

Part of the REST APIs section of Coddy's Node.js journey. Lesson 23 of 25.

On your laptop the server listens on port 3000. A hosting service starts it with node server.js and chooses the port itself, passing it in the environment as PORT. The host also calls a route like GET /health now and then, and restarts the server when it stops responding.

// MAX_UPLOAD_MB=5 node server.js
const maxUpload = Number(process.env.MAX_UPLOAD_MB ?? 2);
const shopName = process.env.SHOP_NAME ?? 'My Shop';

Every value in process.env is a string, and '5' + 1 is '51', so convert numbers with Number. Read the settings in one file, config.js, and import them everywhere else, so nothing else touches process.env.

challenge icon

Challenge

Easy

On a hosting service, the host picks the port and passes settings to your server in the environment. Read your settings from the environment in one place, and add a route the host can call to check that the server is up.

  1. In config.js, read port from the PORT environment variable and pageSize from PAGE_SIZE. Both arrive as text, so turn them into numbers. When a variable is missing, keep today's values: 3000 and 10.
  2. In server.js, import config. Start the server on config.port, and print the port it uses. With PORT=8080 the Console shows exactly:
    Task tracker API on port 8080
  3. In routes/tasks.js, import config too. In the list route, a request without ?limit= uses config.pageSize instead of 10. A ?limit= in the request still wins.
  4. In server.js, add GET /health, outside the tasks router. It returns status 200 and exactly:
    { "status": "ok" }

This lesson runs with PORT=8080 and PAGE_SIZE=2.

Try it: press Run, and the Console prints Task tracker API on port 8080. GET /api/v1/tasks returns 2 tasks with "total": 3 and "pages": 2. GET /api/v1/tasks?limit=3 returns all 3. GET /health returns { "status": "ok" }.

Try it yourself

// The settings that change between your laptop and a server.
// Read each one from process.env, keeping these values as defaults.
export const config = {
    port: 3000,
    pageSize: 10,
};
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in REST APIs

Practice on your own: Express playground