Managing Secrets in PocketPages
When building secure applications, managing secrets like API keys, database credentials, and other sensitive information is crucial. PocketPages provides a secure way to access environment variables through the global env()
function.
Using the env()
Function
The env()
function is available globally in both templates and JavaScript files. It provides secure access to environment variables:
const apiKey = env('API_KEY')
const dbPassword = env('DB_PASSWORD')
In Templates
<% const apiKey = env('API_KEY') %>
<script>
// Use environment variables to configure your application
const config = {
apiEndpoint: '<%= env('API_ENDPOINT') %>',
// ...
}
</script>
In JavaScript Files
/** @type {import('pocketpages').PageDataLoaderFunc} */
module.exports = function () {
const apiKey = env('API_KEY')
const dbUrl = env('DATABASE_URL')
// Use environment variables for configuration
return {
config: {
apiEndpoint: env('API_ENDPOINT'),
// ...
},
}
}
Best Practices
Never Expose Secrets in Templates
<!-- DON'T: Expose secrets directly --> <meta name="api-key" content="<%= env('API_KEY') %>"> <!-- DO: Use environment variables for configuration --> <meta name="api-endpoint" content="<%= env('PUBLIC_API_ENDPOINT') %>">
Check for Required Variables
const apiKey = env('API_KEY') if (!apiKey) { error('Missing required API_KEY environment variable') // Handle error appropriately }
Use Descriptive Names
// Good const stripeSecretKey = env('STRIPE_SECRET_KEY') const mailgunApiKey = env('MAILGUN_API_KEY') // Avoid const key = env('KEY') const secret = env('SECRET')
Document Required Variables
/** * Required environment variables: * - API_KEY: External service API key * - DB_PASSWORD: Database password * - SMTP_PASSWORD: Email service password */
Setting Environment Variables
Environment variables can be set in various ways depending on your deployment environment:
Development Environment
# .env file API_KEY=your_api_key DB_PASSWORD=your_db_password
Production Environment
# Set directly in your hosting environment export API_KEY=your_api_key export DB_PASSWORD=your_db_password
Docker Environment
ENV API_KEY=your_api_key ENV DB_PASSWORD=your_db_password
Security Considerations
- Never commit secrets to version control
- Use different values for development and production
- Rotate secrets regularly
- Use environment-specific configurations
- Implement proper access controls