Back to Blog
Lesson 29 of the Cloudflare: Cloudflare for Developers: DNS to CDN course
Cloud NativeAugust 7, 20264 min read

Managing Secrets Securely: A Cloudflare Workers Guide

Learn how to use Wrangler secrets to protect API keys and credentials. Stop hardcoding sensitive data and master secure environment configuration for your Workers.

CloudflareWorkersSecuritySecretsDevOps
A rustic 'Private' sign nestled within lush green foliage, suggesting seclusion.

Previously in this course, we built a Dynamic Backend that integrates D1 and R2. Now that our application is functional, it’s time to move beyond development-only practices. Hardcoding API keys or database connection strings is the fastest way to leak sensitive data—in this lesson, we’ll move those credentials into secure storage using wrangler secret.

Why Secrets Matter

When you build applications, you inevitably need external services: third-party APIs, database passwords, or private encryption keys. A common beginner mistake is placing these directly into your wrangler.toml or your JavaScript files.

If you commit those files to a version control system like GitHub, your credentials are compromised the moment they are pushed. Handling secrets securely to prevent accidental credential leakage is a fundamental skill for any engineer, as it separates your application logic from the configuration that allows it to talk to the outside world.

Secrets vs. Environment Variables

It is helpful to distinguish between two types of configuration:

  • Environment Variables: These are non-sensitive configuration values (e.g., API_BASE_URL, DEBUG_MODE=true). They are defined in your wrangler.toml and are visible to anyone with access to your repository.
  • Secrets: These are sensitive values that should never be exposed in plain text. Examples include STRIPE_API_KEY, DATABASE_PASSWORD, or JWT_SECRET.

While environment variables are stored in your project configuration, secrets are encrypted at rest and injected into the Worker environment only at runtime.

Worked Example: Using wrangler secret

Let’s secure an hypothetical API key used to communicate with an external email service.

1. Creating a Secret

Instead of editing a file, you use the Wrangler CLI to push the secret directly to Cloudflare's infrastructure. Open your terminal in your project directory and run:

Bash
npx wrangler secret put EMAIL_API_KEY

Wrangler will prompt you to enter the value. Once you type it and hit enter, the value is encrypted and stored in Cloudflare's secure vault for your specific Worker.

2. Accessing the Secret in Code

Your Worker accesses these secrets through the env object, which is passed as the second argument to your fetch handler. It behaves exactly like a standard environment variable:

JAVASCRIPT
export default {
  async fetch(request, env, ctx) {
    // Accessing the secret injected via Wrangler
    const apiKey = env.EMAIL_API_KEY;

    if (!apiKey) {
      return new Response("Missing API Key", { status: 500 });
    }

    // Use the key...
    return new Response("Authenticated request sent!");
  }
};

Hands-on Exercise

To practice this, let's update our project:

  1. Think of a "fake" API key you might need for an external service (e.g., MY_SERVICE_TOKEN).
  2. Run npx wrangler secret put MY_SERVICE_TOKEN in your terminal.
  3. Modify your existing Worker fetch handler to log that you are accessing the environment variable (use console.log(env.MY_SERVICE_TOKEN ? "Key present" : "Key missing")).
  4. Deploy your updated worker with npx wrangler deploy.
  5. Verify that your code can read the secret without having the actual value written anywhere in your repository.

Common Pitfalls

  • Committing to Git: Never, under any circumstances, place a secret value in wrangler.toml. Even if you delete it later, it remains in your Git commit history.
  • Local Development: Remember that secrets stored via wrangler secret are remote. When developing locally, you should use a .dev.vars file in your root directory to store local equivalents. Add .dev.vars to your .gitignore immediately.
  • Typo in naming: Ensure the name you use in wrangler secret put matches exactly what you call in the env object in your code.

FAQ

Q: Can I see my secrets in the dashboard? A: No. Once a secret is set, it cannot be retrieved. You can only overwrite it by running wrangler secret put again.

Q: Are these secrets available during local development? A: No, wrangler dev will not pull secrets from the cloud by default. You must define them in a local .dev.vars file to simulate the environment.

Q: How do I delete a secret? A: Use npx wrangler secret delete <SECRET_NAME>.

Recap

We’ve learned that security starts by keeping sensitive data out of our codebase. By using wrangler secret, we ensure that our credentials stay encrypted on Cloudflare's servers, accessible only to our Workers at runtime. This approach, similar to Managing Environment Variables: A Docker Configuration Guide, allows us to build robust, production-ready applications without risking our infrastructure's integrity.

Up next: We'll dive into formalizing our project configuration using Environment Variables for non-sensitive settings.

Similar Posts