Configuration
Part of the REST APIs section of Coddy's Node.js journey. Lesson 16 of 18.
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. A process manager there restarts the server when it crashes and calls a route like GET /health to see that it is up.
// 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
Easy- In
config.js, readportfromPORTandpageSizefromPAGE_SIZE, as numbers, keeping the defaults. - Listen on
config.port, printingTask tracker API on port <port>; the defaultlimitisconfig.pageSize. GET /healthanswers{ "status": "ok" }.
This lesson runs with PORT=8080 and PAGE_SIZE=2. Send GET /api/v1/tasks, then GET /health.
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.