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
EasyOn 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.
- In
config.js, readportfrom thePORTenvironment variable andpageSizefromPAGE_SIZE. Both arrive as text, so turn them into numbers. When a variable is missing, keep today's values: 3000 and 10. - In
server.js, importconfig. Start the server onconfig.port, and print the port it uses. WithPORT=8080the Console shows exactly:Task tracker API on port 8080 - In
routes/tasks.js, importconfigtoo. In the list route, a request without?limit=usesconfig.pageSizeinstead of 10. A?limit=in the request still wins. - In
server.js, addGET /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,
};
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the APIPractice on your own: Express playground