Home > Web Front-end > JS Tutorial > API Keys and Environment Variables in Astro: Complete Security Guide

API Keys and Environment Variables in Astro: Complete Security Guide

Patricia Arquette
Release: 2024-12-28 08:22:09
Original
303 people have browsed it

API Keys y Variables de Entorno en Astro: Guía Completa de Seguridad

When we develop web applications with Astro, we frequently need to interact with external APIs and services. Managing credentials and API keys securely is crucial to protecting our applications. In this guide, we will explore best practices for managing API keys and environment variables in Astro projects.

Environment Variables in Astro

Basic Configuration

In Astro, environment variables are handled similarly to other modern frameworks. First, we create a .env file in the root of our project:

# .env
PUBLIC_API_URL=https://api.ejemplo.com
PRIVATE_API_KEY=tu_clave_secreta
DATABASE_URL=postgresql://usuario:password@localhost:5432/db
Copy after login
Copy after login

For TypeScript, it is advisable to create an env.d.ts file to type our variables:

/// <reference types="astro/client" />
interface ImportMetaEnv {
  readonly DATABASE_URL: string;
  readonly PRIVATE_API_KEY: string;
  readonly PUBLIC_API_URL: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}
Copy after login
Copy after login

Accessing Variables

In Astro, we can access environment variables in different ways depending on the context:

---
// En archivos .astro
const apiKey = import.meta.env.PRIVATE_API_KEY;
const publicUrl = import.meta.env.PUBLIC_API_URL;
---
Copy after login
Copy after login
// En archivos .ts o .js
const apiKey = import.meta.env.PRIVATE_API_KEY;
Copy after login
Copy after login

Frontend Security

Public vs Private Variables

Astro follows an important convention for environment variables:

  • PUBLIC_*: Accessible on the client and server
  • No PUBLIC_ prefix: Only accessible on the server
# .env
PUBLIC_API_URL=https://api.publica.com    # ✅ Visible en el cliente
PRIVATE_API_KEY=secreto123                # ⛔ Solo servidor
Copy after login
Copy after login

Protecting Sensitive Keys

To handle APIs that require authentication, we must create serverless endpoints:

// src/pages/api/data.ts
export async function GET() {
  try {
    const response = await fetch('https://api.externa.com/data', {
      headers: {
        'Authorization': `Bearer ${import.meta.env.PRIVATE_API_KEY}`
      }
    });

    const data = await response.json();
    return new Response(JSON.stringify(data), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Error al obtener datos' }), {
      status: 500
    });
  }
}
Copy after login
Copy after login

Best Practices

1. Validation of Environment Variables

Implement a validation function at the start of your application:

// src/utils/validateEnv.ts
export function validateEnv() {
  const requiredEnvVars = [
    'DATABASE_URL',
    'PRIVATE_API_KEY',
    'PUBLIC_API_URL'
  ];

  for (const envVar of requiredEnvVars) {
    if (!import.meta.env[envVar]) {
      throw new Error(`La variable de entorno ${envVar} es requerida`);
    }
  }
}

// src/pages/index.astro
---
import { validateEnv } from '../utils/validateEnv';

if (import.meta.env.MODE === 'development') {
  validateEnv();
}
---
Copy after login
Copy after login

2. Multiple Environment Management

Create different files for each environment:

.env                # Variables por defecto
.env.development    # Variables de desarrollo
.env.production     # Variables de producción
.env.local          # Variables locales (ignoradas en git)
Copy after login

3. Environment Variables Template

Provides a .env.example file:

# .env.example
PUBLIC_API_URL=https://api.ejemplo.com
PRIVATE_API_KEY=tu_clave_aqui
DATABASE_URL=postgresql://usuario:password@localhost:5432/db
Copy after login

4. Git configuration

Make sure to include sensitive files in .gitignore:

# .env
PUBLIC_API_URL=https://api.ejemplo.com
PRIVATE_API_KEY=tu_clave_secreta
DATABASE_URL=postgresql://usuario:password@localhost:5432/db
Copy after login
Copy after login

Integration with External Services

Example with Stripe

/// <reference types="astro/client" />
interface ImportMetaEnv {
  readonly DATABASE_URL: string;
  readonly PRIVATE_API_KEY: string;
  readonly PUBLIC_API_URL: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}
Copy after login
Copy after login

Example with Firebase

---
// En archivos .astro
const apiKey = import.meta.env.PRIVATE_API_KEY;
const publicUrl = import.meta.env.PUBLIC_API_URL;
---
Copy after login
Copy after login

Deployment and CI/CD

Configuration in Vercel

// En archivos .ts o .js
const apiKey = import.meta.env.PRIVATE_API_KEY;
Copy after login
Copy after login

GitHub Actions

# .env
PUBLIC_API_URL=https://api.publica.com    # ✅ Visible en el cliente
PRIVATE_API_KEY=secreto123                # ⛔ Solo servidor
Copy after login
Copy after login

Additional Safety Tips

  1. Key Rotation: Implement a system to periodically rotate API keys
// src/pages/api/data.ts
export async function GET() {
  try {
    const response = await fetch('https://api.externa.com/data', {
      headers: {
        'Authorization': `Bearer ${import.meta.env.PRIVATE_API_KEY}`
      }
    });

    const data = await response.json();
    return new Response(JSON.stringify(data), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Error al obtener datos' }), {
      status: 500
    });
  }
}
Copy after login
Copy after login
  1. Usage Monitoring: Implement logging to detect misuse
// src/utils/validateEnv.ts
export function validateEnv() {
  const requiredEnvVars = [
    'DATABASE_URL',
    'PRIVATE_API_KEY',
    'PUBLIC_API_URL'
  ];

  for (const envVar of requiredEnvVars) {
    if (!import.meta.env[envVar]) {
      throw new Error(`La variable de entorno ${envVar} es requerida`);
    }
  }
}

// src/pages/index.astro
---
import { validateEnv } from '../utils/validateEnv';

if (import.meta.env.MODE === 'development') {
  validateEnv();
}
---
Copy after login
Copy after login

Secure handling of API keys and environment variables is crucial for any modern web application. By following these best practices at Astro, we can:

  • Keep our credentials secure
  • Separate configurations by environment
  • Implement robust validations
  • Integrate external services securely

The above is the detailed content of API Keys and Environment Variables in Astro: Complete Security Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template