Skip to content

use env to get api key#84

Open
honwhy wants to merge 3 commits intoPublicAffairs:mainfrom
honwhy:main
Open

use env to get api key#84
honwhy wants to merge 3 commits intoPublicAffairs:mainfrom
honwhy:main

Conversation

@honwhy
Copy link

@honwhy honwhy commented Dec 14, 2025

  • use env to get api key, support clouflare workers for example
  • add wrangler dev support

Summary by CodeRabbit

  • New Features

    • API keys can be provided via environment variables and runtime env contexts
    • Enhanced observability with richer request and invocation logging
  • Chores

    • Added a development script and tooling entry for local worker dev
    • .env added to ignored files to keep local secrets out of source control

✏️ Tip: You can customize this high-level summary in your review settings.

@netlify
Copy link

netlify bot commented Dec 14, 2025

Deploy Preview for gemini-pro ready!

Name Link
🔨 Latest commit 317c8e1
🔍 Latest deploy log https://app.netlify.com/projects/gemini-pro/deploys/694174acc66f2400083d320d
😎 Deploy Preview https://deploy-preview-84--gemini-pro.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link

coderabbitai bot commented Dec 14, 2025

Walkthrough

Adds .env to .gitignore, introduces Wrangler dev tooling and observability config, and extends the Cloudflare Worker fetch handler to accept an env parameter with a fallback helper to read the GEMINI_API_KEY from env or global scope.

Changes

Cohort / File(s) Summary
Environment & Build Configuration
/.gitignore, package.json, wrangler.toml
.env added to .gitignore. Added wrangler devDependency (^4.54.0) and dev:wrangler npm script in package.json. wrangler.toml updated with keep_vars = true and an [observability] block enabling logs and related settings.
Worker Handler
src/worker.mjs
Exported fetch handler signature changed from fetch(request) to fetch(request, env). Added getEnv(key, env) helper and API key fallback: reads from Authorization header or env.GEMINI_API_KEY/global scope. No other control-flow changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review src/worker.mjs for runtime compatibility (Wrangler/Cloudflare Workers vs other targets) and ensure getEnv correctly covers intended runtimes and edge cases (undefined/empty auth header, precedence).
  • Check package.json for devDependency placement and npm script naming conflicts.
  • Validate wrangler.toml observability settings (sampling/persist) are intentional for target environments.

Poem

🐰 I sniffed the air and found a key,
Tucked in env where secrets be,
Wrangler hopped in with a helpful grin,
Logs now hum where traces begin,
A tiny bounce for developer glee.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'use env to get api key' directly reflects the main change in the PR: refactoring to obtain the API key from environment variables with a new getEnv helper function, enabling Cloudflare Workers support.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aac492d and 317c8e1.

📒 Files selected for processing (2)
  • src/worker.mjs (3 hunks)
  • wrangler.toml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • wrangler.toml
  • src/worker.mjs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/worker.mjs (1)

14-14: Consider adding explicit validation for missing API key.

The fallback logic auth?.split(" ")[1] || env.GEMINI_API_KEY will result in apiKey being undefined if both the Authorization header and env.GEMINI_API_KEY are absent. While downstream Google API calls will fail with authentication errors, consider adding explicit validation here for better error messages.

Apply this diff to add explicit validation:

 const apiKey = auth?.split(" ")[1] || env.GEMINI_API_KEY;
+if (!apiKey) {
+  throw new HttpError("API key not provided. Set GEMINI_API_KEY environment variable or provide Authorization header.", 401);
+}
wrangler.toml (1)

5-10: Consider whether 100% sampling is appropriate for production.

The observability configuration with head_sampling_rate = 1 enables 100% request sampling, which is excellent for development but may be excessive for production environments with high traffic.

If this configuration will be used in production, consider:

  • Reducing head_sampling_rate to a lower value (e.g., 0.1 for 10% sampling)
  • Using environment-specific wrangler configuration files (e.g., wrangler.toml for dev, wrangler.production.toml for production)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe22245 and aac492d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • package.json (1 hunks)
  • src/worker.mjs (2 hunks)
  • wrangler.toml (1 hunks)
🔇 Additional comments (4)
.gitignore (1)

5-5: LGTM!

Adding .env to gitignore is essential when using environment variables for API keys, preventing accidental exposure of secrets.

src/worker.mjs (1)

4-4: LGTM!

The extended signature to accept env is correct for Cloudflare Workers and enables environment variable access.

package.json (2)

6-6: LGTM!

Adding the trailing comma improves diff readability for future changes.


16-16: LGTM!

The dev:wrangler script correctly invokes the Wrangler development server and aligns with the other runtime-specific dev scripts in this project.

@johnd0e
Copy link
Contributor

johnd0e commented Dec 14, 2025

worker.mjs is used also for Netlify, Vercel, and Deno deploy, where environment is handled in different ways.

@honwhy
Copy link
Author

honwhy commented Dec 15, 2025

worker.mjs is used also for Netlify, Vercel, and Deno deploy, where environment is handled in different ways.

would you like to rewrite worker.mjs in hono ? for cross-platform deployment.

@johnd0e
Copy link
Contributor

johnd0e commented Dec 15, 2025

would you like to rewrite worker.mjs in hono ? for cross-platform deployment.

Do you think it might help to support different environments easier? How?

Anyway I would prefer to stay away from any framework for such a simple project.

@honwhy
Copy link
Author

honwhy commented Dec 16, 2025

would you like to rewrite worker.mjs in hono ? for cross-platform deployment.

Do you think it might help to support different environments easier? How?

Anyway I would prefer to stay away from any framework for such a simple project.

accord to chatgpt, suggets this codes (I have push to this pr)

function getEnv(key, env) {
  // Cloudflare Workers
  if (env && key in env) return env[key]

  // Vercel Edge / Deno / Bun
  if (key in globalThis) return (globalThis)[key]

  return undefined
}

@johnd0e
Copy link
Contributor

johnd0e commented Dec 16, 2025

accord to chatgpt

You'd better to check that thoroughly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants