Keeping your database credentials secret is paramount for application security. Using dotenv is an excellent approach for managing environment variables locally in both your Next.js and Express parts of the project, preventing you from accidentally committing sensitive information.
Here's how to implement it effectively:
1. The .env File
Create a file named .env.local in the root of your project (where package.json is located). This file will hold your sensitive environment variables.
Crucially, add .env.local (and other .env files like .env.development, .env.production) to your .gitignore file immediately.
2. Express Backend
For your Express backend, you'll typically install and use the dotenv package.
-
Install
dotenv: -
Load Environment Variables: In your main Express server file (e.g.,
server.jsorapp.ts), at the very top, import and configuredotenv.Express will now have access to
process.env.DATABASE_URLand other variables defined in.env.local.
3. Next.js Frontend (and Server-side API Routes/Functions)
Next.js has built-in support for environment variables, so you generally don't need to install dotenv separately for the Next.js part of your project.
-
Accessing Variables:
- Server-side (API Routes,
getServerSideProps,getStaticProps): Variables from.env.localare directly available viaprocess.env. - Client-side (Browser): For variables to be exposed to the client-side code (browser), they must be prefixed with
NEXT_PUBLIC_. This ensures Next.js bundles them into the client-side JavaScript.
- Server-side (API Routes,
Summary of Best Practices:
.env.localfor Local Development: Use this file for all local environment variables..gitignore: Always add.env*to your.gitignoreto prevent sensitive files from being committed to version control.NEXT_PUBLIC_Prefix: Only useNEXT_PUBLIC_for variables that are safe to expose to the browser. Never prefix database credentials or API keys that should remain server-side.- Deployment: When deploying your application to platforms like Vercel, Netlify, Heroku, or AWS, you will set environment variables directly through their respective dashboards or CLI tools. This is the secure way to provide production credentials, as
dotenvis primarily for local development.