Episode 7 of 21
Securing Keys
Store API keys and secrets securely — use a separate config file excluded from version control to protect sensitive credentials.
Securing Keys
Your Client ID and Client Secret are sensitive credentials. If someone gets your secret, they can impersonate your app. Never commit secrets to Git.
The Keys File
// config/keys.js
module.exports = {
google: {
clientID: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET'
},
mongodb: {
dbURI: 'mongodb://username:password@host:port/dbname'
},
session: {
cookieKey: 'a_random_string_for_cookie_encryption'
}
};
Adding to .gitignore
# .gitignore
node_modules/
config/keys.js
Add config/keys.js to your .gitignore before making any commits. This ensures the file is never pushed to GitHub.
Using the Keys
// config/passport-setup.js
const keys = require('./keys');
passport.use(
new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL: '/auth/google/redirect'
}, callback)
);
Alternative: Environment Variables
# .env
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
MONGODB_URI=mongodb://...
COOKIE_KEY=random_string
// With dotenv
require('dotenv').config();
new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/redirect'
}, callback);
Key Takeaways
- Never commit API keys, secrets, or database URIs to version control
- Use a separate config file (
keys.js) or environment variables (.env) - Add the keys file to
.gitignorebefore your first commit - Store all sensitive values in one place for easy management