Authentication
When using the Route Optimization API in production, you need to authenticate with Google Cloud. This guide covers all authentication methods supported by RouteCalculator.
Overview
RouteCalculator supports three authentication methods:
- API Key - Simplest method, recommended for getting started
- Service Account - More secure, recommended for production
- Mock Mode - No authentication needed, for testing only
Authentication Methods
API Key (Recommended for Quick Start)
API Key authentication is the simplest way to get started with the Route Optimization API.
Setup
- Go to Google Cloud Console Credentials
- Click "Create Credentials" > "API Key"
- Copy the generated API key
- (Recommended) Click "Restrict Key" to add security restrictions
Usage
import { RouteCalculator } from '@route-optimization/core';
const calculator = new RouteCalculator({
projectId: 'your-project-id',
apiKey: 'AIzaSyC...your-api-key',
debug: true,
});
await calculator.initialize();Pros & Cons
Pros:
- ✅ Simple setup process
- ✅ No file management needed
- ✅ Easy to rotate and update
- ✅ Works well in serverless environments
Cons:
- ⚠️ Less granular permission control
- ⚠️ Should be restricted to specific APIs
- ⚠️ Needs proper secret management
Security Best Practices
Restrict the API Key:
- Set application restrictions (HTTP referrers, IP addresses, etc.) - Restrict to only "Cloud Optimization API"Store Securely:
- Never commit API keys to version control
- Use environment variables
- Use secret management services (AWS Secrets Manager, etc.)
Rotate Regularly:
- Change API keys periodically
- Have a rotation policy in place
Environment Variables
// .env file
GOOGLE_PROJECT_ID=your-project-id
GOOGLE_API_KEY=AIzaSyC...your-api-key
// In your code
const calculator = new RouteCalculator({
projectId: process.env.GOOGLE_PROJECT_ID,
apiKey: process.env.GOOGLE_API_KEY,
});Service Account (Recommended for Production)
Service Account provides more secure authentication with granular IAM permissions.
Setup
- Go to IAM & Admin > Service Accounts
- Click "Create Service Account"
- Name it (e.g., "route-optimizer")
- Click "Create and Continue"
- Grant role: "Cloud Optimization API User"
- Click "Done"
- Click on the created service account
- Go to "Keys" tab
- Click "Add Key" > "Create new key"
- Choose JSON format
- Save the downloaded file securely
Usage with File Path
import { RouteCalculator } from '@route-optimization/core';
const calculator = new RouteCalculator({
projectId: 'your-project-id',
credentialsPath: './service-account-key.json',
debug: true,
});
await calculator.initialize();Usage with Credentials Object
import { RouteCalculator } from '@route-optimization/core';
import serviceAccountKey from './service-account-key.json';
const calculator = new RouteCalculator({
projectId: 'your-project-id',
credentials: serviceAccountKey,
});
await calculator.initialize();Usage with Environment Variable
import { RouteCalculator } from '@route-optimization/core';
// Set environment variable: GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
const calculator = new RouteCalculator({
projectId: 'your-project-id',
// No credentials needed - will use GOOGLE_APPLICATION_CREDENTIALS
});
await calculator.initialize();Pros & Cons
Pros:
- ✅ More secure than API keys
- ✅ Granular IAM permissions
- ✅ Better audit trail
- ✅ Supports role-based access control
- ✅ Can be used with Workload Identity Federation
Cons:
- ⚠️ More complex setup
- ⚠️ File management required
- ⚠️ JSON file must be kept secure
Security Best Practices
Principle of Least Privilege:
- Only grant "Cloud Optimization API User" role
- Don't use Owner or Editor roles
Secure Storage:
- Never commit service account keys to Git
- Use
.gitignoreto exclude key files - Store in secure secret management systems
Key Rotation:
- Rotate keys regularly (every 90 days recommended)
- Maintain multiple active keys during rotation
- Delete old keys after rotation
Monitor Usage:
- Enable Cloud Audit Logs
- Monitor for unusual API usage
- Set up alerts for security events
Mock Mode (Development & Testing)
Mock mode allows testing without any Google Cloud setup or authentication.
Usage
import { RouteCalculator } from '@route-optimization/core';
const calculator = new RouteCalculator({
useMockMode: true,
debug: true,
});
await calculator.initialize(); // No authentication neededFeatures
- ✅ No API key or credentials required
- ✅ No billing charges
- ✅ Instant responses
- ✅ Deterministic results for testing
- ❌ Simplified optimization algorithm
- ❌ No real-world traffic data
When to Use
- Local development
- Unit testing
- Integration testing
- CI/CD pipelines
- Demos and prototypes
Comparison Table
| Feature | API Key | Service Account | Mock Mode |
|---|---|---|---|
| Setup Complexity | Low | Medium | None |
| Security | Medium | High | N/A |
| Cost | Paid | Paid | Free |
| IAM Integration | Limited | Full | N/A |
| Audit Trail | Basic | Complete | N/A |
| Best For | Quick start, small apps | Production, enterprise | Development, testing |
Troubleshooting
API Key Issues
Error: "API key not valid"
Cause: API key is incorrect or has been deleted.
Solution:
- Verify the API key is correct
- Check if the key still exists in Google Cloud Console
- Generate a new API key if needed
Error: "API keys are not supported by this API"
Cause: Some Google APIs don't support API key authentication.
Solution:
- Use Service Account authentication instead
- Check if the API supports API keys
Error: "API key has been restricted"
Cause: API key restrictions are blocking the request.
Solution:
- Check API restrictions in Cloud Console
- Ensure "Cloud Optimization API" is allowed
- Verify IP/referrer restrictions match your setup
Service Account Issues
Error: "Could not load the default credentials"
Cause: Service account credentials are not found or invalid.
Solution:
- Verify
credentialsPathpoints to correct file - Check file permissions (readable by your app)
- Ensure JSON file is valid format
- Try setting
GOOGLE_APPLICATION_CREDENTIALSenvironment variable
Error: "Permission denied"
Cause: Service account lacks required permissions.
Solution:
- Go to IAM & Admin in Cloud Console
- Find your service account
- Add role: "Cloud Optimization API User"
- Wait a few minutes for permissions to propagate
Error: "Service account key is expired"
Cause: The service account key has been deleted or expired.
Solution:
- Create a new service account key
- Update your application with new credentials
- Delete the old key
Best Practices Summary
Development
// Use mock mode for local development
const calculator = new RouteCalculator({
useMockMode: true,
debug: true,
});Testing
// Use mock mode for tests
const calculator = new RouteCalculator({
useMockMode: true,
});Staging
// Use API Key with environment variables
const calculator = new RouteCalculator({
projectId: process.env.GOOGLE_PROJECT_ID,
apiKey: process.env.GOOGLE_API_KEY,
debug: true,
});Production
// Use Service Account with secure storage
const calculator = new RouteCalculator({
projectId: process.env.GOOGLE_PROJECT_ID,
credentialsPath: process.env.GOOGLE_CREDENTIALS_PATH,
debug: false, // Disable debug logging in production
});