The E-Commerce API uses environment variables for configuration. This guide explains all available options and how to set them up.
Environment file setup
Create a .env file in the root directory of your project:
Never commit your .env file to version control. Add it to your .gitignore file to prevent exposing sensitive credentials.
Required environment variables
Server configuration
PORT
The port number on which the server will run.
Default: 5000
Usage in code:
const PORT = process . env . PORT || 5000 ;
app . listen ( PORT , () => {
console . log ( `Server running on http://localhost: ${ PORT } ` );
});
Database configuration
The API uses MySQL as its database. Configure the connection with these variables:
DB_HOST
The hostname of your MySQL server.
DB_USER
The MySQL user for database connections.
DB_PASSWORD
The password for the MySQL user.
DB_PASSWORD = your_secure_password
DB_NAME
The name of your database.
Usage in code:
import mysql from 'mysql2/promise' ;
import dotenv from 'dotenv' ;
dotenv . config ();
const db = mysql . createPool ({
host: process . env . DB_HOST ,
user: process . env . DB_USER ,
password: process . env . DB_PASSWORD ,
database: process . env . DB_NAME ,
});
export default db ;
Authentication configuration
JWT_SECRET
Secret key used for signing and verifying JWT tokens.
JWT_SECRET = your-super-secret-jwt-key-change-this-in-production
Use a strong, randomly generated secret in production. Never use a simple or predictable value.
Recommended generation method:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
Usage in code:
middlewares/authMiddleware.mjs
import jwt from "jsonwebtoken" ;
export const authenticate = ( req , res , next ) => {
const token = req . headers . authorization ?. split ( " " )[ 1 ];
if ( ! token ) {
return res . status ( 401 ). json ({ error: "Access Denied" });
}
try {
const decoded = jwt . verify ( token , process . env . JWT_SECRET );
req . user = decoded ;
next ();
} catch ( err ) {
errorResponse ({ res , statusCode: 400 , message: err . message });
}
};
API_KEY
API key required for accessing public and authenticated routes.
API_KEY = your-api-key-for-public-routes
Usage in code:
middlewares/authMiddleware.mjs
export const apiKeyAuth = ( req , res , next ) => {
const apiKey = req . headers [ "x-api-key" ];
if ( apiKey !== process . env . API_KEY ) {
return errorResponse ({ res , statusCode: 403 , message: "Invalid API Key" });
}
next ();
};
All requests to /api/* routes must include the x-api-key header with this value.
ADMIN_API_KEY
Separate API key for admin-only operations.
ADMIN_API_KEY = your-super-secret-admin-api-key
Usage in code:
middlewares/adminMiddleware.mjs
export const adminKeyAuth = ( req , res , next ) => {
const adminKey = req . headers [ "x-api-key" ];
if ( adminKey !== process . env . ADMIN_API_KEY ) {
return errorResponse ({ res , statusCode: 403 , message: "Invalid Admin API Key" });
}
next ();
};
Admin routes (/api/admin/*) use a different API key for enhanced security. Keep this key highly confidential.
Complete .env example
Here’s a complete example .env file with all required variables:
# Server Configuration
PORT = 5000
# Database Configuration
DB_HOST = localhost
DB_USER = root
DB_PASSWORD = your_secure_password
DB_NAME = ecommerce_db
# Authentication
JWT_SECRET = your-super-secret-jwt-key-change-this-in-production
API_KEY = your-api-key-for-public-routes
ADMIN_API_KEY = your-super-secret-admin-api-key
Loading environment variables
The application loads environment variables using the dotenv package:
import dotenv from "dotenv" ;
dotenv . config ();
This must be called before accessing any process.env values.
Configuration by environment
You can maintain different configurations for different environments:
Development (.env.development)
Production (.env.production)
Testing (.env.test)
PORT = 5000
DB_HOST = localhost
DB_NAME = ecommerce_dev
To use a specific environment file, you can specify it when loading dotenv: dotenv . config ({ path: '.env.production' });
Security best practices
Follow these security practices for production deployments:
Never commit secrets - Add .env to .gitignore
Use strong keys - Generate cryptographically secure random values
Rotate credentials - Regularly update API keys and JWT secrets
Restrict permissions - Use database users with minimal required privileges
Use HTTPS - Always use TLS/SSL in production
Environment isolation - Use separate credentials for dev, staging, and production
Validating configuration
The application validates database connectivity on startup:
( async () => {
try {
await db . getConnection ();
console . log ( "Connected to MySQL database." );
} catch ( err ) {
console . error ( "Database connection failed:" , err );
}
})();
If you see “Database connection failed” in your console, verify your database configuration variables.
Next steps
Rate limiting Configure rate limits to protect your API
File uploads Set up file upload handling for images