Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Configuration and environment variables

The port, secret keys and database path differ on your computer and on the server. You cannot write them into the code: secrets would end up in Git, and changing the port would mean editing files. Such values are passed through environment variables — "name=value" pairs the operating system gives a process when it starts.

The .env file

Create a .env file in the project root:

PORT=3000
SESSION_SECRET=a-long-random-string-for-sessions
JWT_SECRET=another-long-random-string
DATABASE_FILE=blog.db

Add it to .gitignore right away so it does not reach the repository:

node_modules/
.env
blog.db

Loading the file

Node.js 22 can read .env by itself — the --env-file flag passes the values into the process. Update the script in package.json:

{
  "scripts": {
    "dev": "node --watch --env-file=.env src/server.js",
    "start": "node src/server.js"
  }
}

A separate package such as dotenv is not needed. On a production server the variables are usually set by the hosting or the process manager, so start has no flag.

A config module

To avoid scattering process.env across the code, collect the settings in one file, src/config.js:

// src/config.js
function required(name) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Environment variable ${name} is not set`);
  }
  return value;
}
 
export const config = {
  port: Number(process.env.PORT ?? 3000),
  isProduction: process.env.NODE_ENV === 'production',
  sessionSecret: required('SESSION_SECRET'),
  jwtSecret: required('JWT_SECRET'),
  databaseFile: process.env.DATABASE_FILE ?? 'blog.db',
};

If a required variable is missing, the application stops right at startup with a clear message instead of failing later on the first user login.

Using it

Other files import config instead of reading process.env directly:

// src/server.js
import app from './app.js';
import { config } from './config.js';
 
app.listen(config.port, () => {
  console.log(`Server started: http://localhost:${config.port}`);
});

In the same way pass config.sessionSecret to session() in src/app.js, and config.databaseFile to new Database() in src/db.js. Change PORT in .env to 4000, and after a restart the server opens at http://localhost:4000.

An example for teammates

Since .env does not go into Git, create a .env.example file next to it with the same names but no real values. A new developer copies it to .env and fills in their own.

Common mistake

All environment variables are strings. DEBUG=false gives the string 'false', which counts as true in a condition: if (process.env.DEBUG) runs. Compare explicitly — process.env.DEBUG === 'true' — and convert numbers with Number(), as with the port in config.js.

Thanks for reading!

Donate to the site — we work hard for you.