Skip to main content

Overview

Astro Portfolio v3 uses environment variables to securely manage API keys and configuration. The project leverages Astro’s built-in environment variable system with type safety and validation defined in astro.config.mjs:29-47.

Environment Schema

The project defines a strict environment schema for type safety:
env: {
  schema: {
    BEEHIIV_PUBLICATION_ID: envField.string({
      context: 'server',
      access: 'secret',
      default: 'abc',
    }),
    BEEHIIV_API_KEY: envField.string({
      context: 'server',
      access: 'secret',
      default: '',
    }),
    GTM_ID: envField.string({
      context: 'client',
      access: 'public',
      default: '',
    }),
  },
}

Required Variables

BEEHIIV_PUBLICATION_ID
string
required
Your Beehiiv publication ID for newsletter integration.Context: Server-side only
Access: Secret (not exposed to client)
Used in: Newsletter subscription API endpoint (/api/newsletter)
Get your publication ID from your Beehiiv dashboard. Navigate to Settings > API to find your publication details.
BEEHIIV_API_KEY
string
required
Your Beehiiv API key for authenticating newsletter subscription requests.Context: Server-side only
Access: Secret (not exposed to client)
Used in: Newsletter API endpoint for creating subscriptions
Never commit your API key to version control. Always use environment variables for sensitive credentials.
How to get your API key:
  1. Log in to Beehiiv
  2. Go to Settings > API
  3. Click Create API Key
  4. Copy the generated key
API Documentation: Beehiiv API v2 Docs
GTM_ID
string
Your Google Tag Manager container ID for analytics and tracking.Context: Client-side
Access: Public (exposed to browser)
Format: GTM-XXXXXXX
Used in: Analytics tracking across the site
This variable is public and will be visible in the browser. Only the container ID is exposed, not sensitive tracking data.
How to get your GTM ID:
  1. Log in to Google Tag Manager
  2. Select or create a container
  3. Find your container ID (format: GTM-XXXXXXX) in the top bar

Local Development

Setup

1

Copy the example file

Create a .env file from the provided template:
cp .env.example .env
2

Add your credentials

Edit .env with your actual values:
# Beehiiv Newsletter API Configuration
# API Documentation: https://developers.beehiiv.com/docs/v2/
BEEHIIV_PUBLICATION_ID=your_publication_id_here
BEEHIIV_API_KEY=your_api_key_here
GTM_ID=GTM-XXXXXXX
3

Start development server

The environment variables will be automatically loaded:
pnpm dev
Never commit the .env file to version control. It’s already included in .gitignore to prevent accidental commits.

Cloudflare Pages Configuration

Setting Environment Variables

1

Access Project Settings

  1. Log in to the Cloudflare Dashboard
  2. Navigate to Pages > Your project
  3. Click Settings > Environment Variables
2

Add Production Variables

For the Production environment, add:
Variable NameValueType
BEEHIIV_PUBLICATION_IDYour publication IDSecret
BEEHIIV_API_KEYYour API keySecret
GTM_IDYour GTM container IDPlain text
Mark BEEHIIV_PUBLICATION_ID and BEEHIIV_API_KEY as Secret to encrypt them in Cloudflare’s system.
3

Add Preview Variables (Optional)

For preview deployments, you can:
  • Use the same production values
  • Use separate test/staging credentials
  • Leave GTM_ID empty to disable analytics in previews
4

Redeploy

After adding or updating variables, trigger a new deployment:
  • Push a new commit to your repository, or
  • Click Retry deployment in the Cloudflare dashboard

Environment-Specific Configuration

You can set different values for different environments:
  • Production: Used for the main branch
  • Preview: Used for pull request previews
  • Per-branch: Override variables for specific branches
Preview environments are useful for testing with sandbox APIs or disabling analytics during development.

Security Best Practices

Follow these security guidelines to protect your API keys and user data:

Do’s ✅

  • Use Secret Variables: Mark sensitive values as “Secret” in Cloudflare Pages
  • Rotate Keys Regularly: Change API keys periodically
  • Use Server Context: Keep sensitive variables server-side only (context: 'server')
  • Validate Input: Always validate data before using with API keys
  • Monitor Usage: Track API usage in Beehiiv dashboard for suspicious activity

Don’ts ❌

  • Never Commit Secrets: Don’t commit .env files or hardcode API keys
  • Don’t Expose Server Variables: Never pass server-side secrets to client components
  • Avoid Logging Secrets: Don’t log API keys in error messages or console
  • Don’t Share Keys: Each developer should use their own test credentials
  • Don’t Use Production Keys Locally: Use separate development/test keys for local work

Accessing Variables in Code

Server-Side (API Routes)

import { BEEHIIV_API_KEY, BEEHIIV_PUBLICATION_ID } from 'astro:env/server';

export async function POST({ request }) {
  const response = await fetch(
    `https://api.beehiiv.com/v2/publications/${BEEHIIV_PUBLICATION_ID}/subscriptions`,
    {
      headers: {
        'Authorization': `Bearer ${BEEHIIV_API_KEY}`,
      },
    }
  );
  // ...
}

Client-Side (Components)

---
import { GTM_ID } from 'astro:env/client';
---

{GTM_ID && (
  <script>
    // Google Tag Manager initialization
    window.dataLayer = window.dataLayer || [];
    // ...
  </script>
)}
Astro’s environment system provides type safety and prevents accidental exposure of server-side secrets to the client.

Validation and Defaults

The environment schema includes default values for graceful degradation:
  • BEEHIIV_PUBLICATION_ID: Defaults to 'abc' (placeholder)
  • BEEHIIV_API_KEY: Defaults to empty string (disables newsletter)
  • GTM_ID: Defaults to empty string (disables analytics)
With default values, the site will build successfully even without environment variables, but features like newsletter subscription won’t work until properly configured.

Troubleshooting

Newsletter Not Working

1

Verify Variables

Check that BEEHIIV_PUBLICATION_ID and BEEHIIV_API_KEY are set correctly in Cloudflare Pages.
2

Test API Key

Use the Beehiiv API documentation to test your credentials with a curl request.
3

Check Logs

Review function logs in the Cloudflare Pages dashboard for error messages.

Analytics Not Tracking

  • Verify GTM_ID format is correct (GTM-XXXXXXX)
  • Check browser console for GTM initialization errors
  • Ensure the variable is set in the Production environment

Build Failures

  • Missing required variables may cause build errors
  • Check the build logs for specific environment variable errors
  • Ensure all variables are spelled correctly (case-sensitive)

Next Steps

Cloudflare Pages

Deploy your portfolio with environment variables

Custom Domain

Configure a custom domain for your site

Build docs developers (and LLMs) love