Direct answer
How to connect Gemini API to Replit means storing a Google API key in Replit Secrets and calling Gemini from server-side code. Use `GEMINI_API_KEY`, install Google's current Gen AI SDK, make one test request, then verify Preview and production separately. This guide helps you keep the key out of browser code and choose between direct Google access and Replit's managed AI option.
Summary: how to connect Gemini API to Replit
Create or copy a key in Google AI Studio. In Replit, open Secrets and add an app secret named `GEMINI_API_KEY`. Install `@google/genai` for JavaScript or `google-genai` for Python. Initialize the SDK on the server and send a small request through the current Interactions API.
Do not place the key in source files, public environment variables, frontend bundles, local storage, or screenshots. Route browser requests through your own server endpoint. Add production Secrets in the Publishing pane and test the public URL after deployment.
Use a six-stage connection flow. Generate the key, save the secret, install the SDK, call from the server, test Preview, and verify deployment.
Choose managed AI or a direct Gemini key
Replit offers a managed AI Integrations route that can provision credentials and charge model usage through Replit. A direct Gemini API connection uses your Google AI Studio project, key, quotas, billing, model access, and usage records.
- Choose Replit AI Integrations when you want Agent to connect a supported model with platform-managed credentials and Replit billing.
- Choose a direct Gemini key when you need Google's SDK, project controls, API features, quotas, or billing relationship.
- Use one route for each request path so ownership, cost, and failure handling remain clear.
- Confirm current model availability and plan limits before choosing a route for production.
Create a Gemini API key in Google AI Studio
A Gemini API key belongs to a Google Cloud project. New AI Studio users may receive a default project and key after accepting the terms. Existing Google Cloud users may need to import a project before creating a key.
- Open the API Keys page in Google AI Studio and choose the Google Cloud project that should own usage and billing.
- Generate a new API key or copy an existing key that is restricted for Gemini API use.
- Record which environment owns the key, such as development, staging, or production.
- Review the project's usage, billing, member access, and key restrictions before sharing the Replit app.
- Plan a rotation path so a replacement key can be deployed and tested before the old key is revoked.
Store the key as a Replit Secret
Replit Secrets encrypts sensitive values and exposes them to the app as environment variables. Use an app-level secret for one project. Use an account-level secret only when several projects need the same credential and its access has been reviewed.
- Open the Replit project and select All tools from the left tool dock.
- Open Secrets, remain on the App Secrets tab, and select New Secret.
- Set Key to `GEMINI_API_KEY` and paste the Google key into Value.
- Select Add Secret, then restart the running process if it does not read the new environment variable.
- Check only whether the variable exists. Avoid printing its value into the console or logs.
Connect with JavaScript and the current SDK
Google's current JavaScript package is `@google/genai`. The client detects `GEMINI_API_KEY` from the environment, so the application does not need to pass the secret through source code.
- Open Replit Shell and run `npm install @google/genai`.
- In a server-only module, import `GoogleGenAI` from `@google/genai`.
- Initialize the client with `const ai = new GoogleGenAI({});`.
- Send a small text input through the Interactions API with a current model.
- Return only the required output to your browser client.
Minimal server-side request: `const interaction = await ai.interactions.create({ model: "gemini-3.6-flash", input: "Reply with one short test sentence." }); console.log(interaction.output_text);`
Connect with Python
Google's current Python package is `google-genai`. It also detects the environment key when you create the client without embedding credentials.
- Open Replit Shell and run `pip install -U google-genai`.
- Import the SDK with `from google import genai`.
- Build the client with `client = genai.Client()` in server-side code.
- Send a bounded input through the Interactions API with a current model.
- Return a validated output from your server route.
Minimal request: `interaction = client.interactions.create(model="gemini-3.6-flash", input="Reply with one short test sentence.")` followed by `print(interaction.output_text)`.
Keep Gemini calls on the server
A Replit Secret protects the key only while the value stays on the server. Browser code is delivered to users and can expose embedded values or responses that contain sensitive data.
- Add a server route that accepts the smallest input needed for the Gemini task.
- Authenticate the caller when the route is private, personalized, expensive, or connected to user data.
- Validate input type, length, file size, and allowed operations before sending a model request.
- Set request timeouts and output limits that fit the product experience and cost boundary.
- Return a controlled error message to the browser while logging a safe diagnostic on the server.
- Remove secrets, personal data, and unnecessary prompt content from application logs.
Test one request in Replit Preview
Start with a small server-only test before building a chat interface. This isolates key, SDK, model, network, and response problems from frontend state and styling.
- Check that `GEMINI_API_KEY` exists without printing its value.
- Run a one-sentence input from the server and confirm that output text is returned.
- Open Preview and call your server route through the same path the browser will use.
- Test missing input, oversized input, invalid authentication, and upstream API failure.
- Inspect server logs for status codes and request identifiers without logging the key or full private prompt.
- Add a small automated test around input validation and the application response shape.
Configure production before publishing
A project that works in Preview can still fail after publishing. Replit's current troubleshooting guide says Project Editor Secrets do not automatically carry into the published app. Add the production value in the Publishing pane.
- Add `GEMINI_API_KEY` to production Secrets and environment variables in the Publishing pane.
- Confirm the deployed server uses the correct build command, start command, host, port, and backend deployment type.
- Publish, open the public URL, and send the same small request used in Preview.
- Compare Preview and production logs when only the public app fails.
- Review Google AI Studio usage to confirm that the expected project receives the request.
- Set budget and usage monitoring before real traffic reaches the endpoint.
Troubleshoot connection errors in order
- Missing key
- confirm the exact `GEMINI_API_KEY` name in the active Replit environment and restart the process.
- Authentication error
- verify the key, its Google project, restrictions, status, and current key type in AI Studio.
- Package error
- check that `@google/genai` or `google-genai` is installed in the environment that runs the server.
- Model error
- use a model listed in the current Gemini documentation and available to the key's project and region.
- Rate limit response
- inspect the API error, reduce unnecessary requests, apply bounded backoff, and review current project limits.
- Billing response
- confirm the intended Google Cloud project and paid-tier setup when the requested usage needs it.
- Preview succeeds but production fails
- check production Secrets, deployment logs, server start behavior, and network settings.
- Browser reveals the key
- rotate the key, remove it from client code, deploy the replacement, and audit usage.
Use a production readiness checklist
- Separate development and production keys when the team needs independent access, quotas, rotation, or incident response.
- Give the server route authentication, authorization, validation, rate limiting, timeouts, and safe error handling.
- Track request count, latency, failures, model, environment, and cost signals without storing sensitive prompts by default.
- Test the exact model behavior your product depends on instead of treating a successful API call as product validation.
- Document who owns the Google project, Replit app, production Secret, billing alerts, key rotation, and incident response.
- Recheck current SDK, model, key, quota, and deployment guidance before a major release.
Frequently asked questions
Use `GEMINI_API_KEY`. Google's current client libraries detect this environment variable. They also detect `GOOGLE_API_KEY`, which takes precedence if both names exist.
Use Google's current Gen AI SDK: `@google/genai` for JavaScript or `google-genai` for Python. Check the current quickstart before upgrading an older integration.
A production app should keep the provider key on the server. Send browser input to your authenticated server route, validate it, then make the Gemini request there.
Replit documents Secrets for deployment types except Static Deployments. A direct Gemini call needs server-side behavior, so choose a backend-capable deployment.
Check production Secrets first. Then inspect deployment logs, start commands, the server port, model access, and the Google project tied to the production key.
Replit AI Integrations can provide managed access to supported Gemini models without a separate Google key. Confirm current model availability, plan limits, usage pricing, and control requirements.
