Environment Variables in Production
Set config through the host's environment, not a committed file.
Syntax
const PORT = process.env.PORT || 3000In production you do not ship a .env file. Instead you set variables in your hosting dashboard or deployment config, and Node.js reads them from process.env the same way.
Always read the port from the environment, because the platform assigns one. Fall back to a local default for development.
Example
const PORT = process.env.PORT || 3000;
const app = require('./app');
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});When to use it
- A cloud deployment sets DATABASE_URL and JWT_SECRET as environment variables in the platform dashboard rather than in code.
- A Docker container receives PORT and NODE_ENV via the -e flag so the same image runs differently in staging and production.
- A developer uses a .env.example file committed to source control to document required variables, while .env itself is git-ignored.
More examples
Reading env vars in Express
Loads .env, reads PORT and NODE_ENV from process.env, and uses them to configure the server.
require('dotenv').config(); // loads .env in development
const express = require('express');
const app = express();
const port = parseInt(process.env.PORT, 10) || 3000;
const isProd = process.env.NODE_ENV === 'production';
app.listen(port, () => console.log(`Mode: ${isProd ? 'prod' : 'dev'}, Port: ${port}`));Dockerfile with env vars
Sets NODE_ENV=production at image build time while port and secrets are injected at runtime via docker run -e.
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
ENV NODE_ENV=production
CMD ["node", "server.js"].env.example documentation file
A .env.example template committed to Git that documents required variables without exposing real secrets.
# Copy this file to .env and fill in your values
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
JWT_SECRET=
SESSION_SECRET=
REDIS_URL=redis://localhost:6379
Discussion