To connect a Replit project to external API endpoints, store all API keys and tokens in the Secrets panel (Tools > Secrets), access them in code via process.env (Node.js) or os.getenv (Python), and configure authentication headers in your HTTP requests. This tutorial focuses on the setup side: creating and managing secrets, configuring different auth methods (API key, Bearer token, OAuth), and ensuring credentials work correctly across development and deployment environments.
Set Up API Authentication and Credentials in Replit
This tutorial is about the setup and configuration side of working with external APIs in Replit. While our companion tutorial covers making API calls and handling responses, this guide focuses on securely storing credentials, configuring different authentication methods, and managing API keys across workspace and deployment environments. It is for intermediate developers who need to connect Replit projects to third-party services like Stripe, Twilio, GitHub, or any API that requires authentication.
Prerequisites
- A Replit account with an active Repl
- An API key or token from an external service you want to connect
- Basic understanding of HTTP requests and authentication headers
- Familiarity with Node.js or Python (examples are provided in both)
Step-by-step guide
Add your API credentials to the Secrets panel
Add your API credentials to the Secrets panel
Open the Tools dock on the left sidebar of your Replit workspace and click Secrets. In the App Secrets tab, click the plus button to add a new secret. Enter the key name (use uppercase with underscores, such as STRIPE_API_KEY or TWILIO_AUTH_TOKEN) and paste the value. Replit encrypts all secrets with AES-256 encryption and transmits them over TLS. You can add multiple secrets for different services. Use the Edit as JSON or Edit as .env buttons for bulk entry if you are migrating from another platform.
Expected result: Your API credentials appear in the Secrets panel with key names listed (values are hidden by default).
Access secrets in your Node.js code
Access secrets in your Node.js code
In Node.js, access secrets through the process.env object. Create a configuration file that centralizes all your API credentials in one place. This makes it easy to see which services your project depends on and catches missing secrets early with clear error messages. Never import dotenv or create .env files in Replit. The Secrets panel replaces .env files entirely, and secrets are automatically injected as environment variables at runtime.
1// config.js — centralize all API credential access2const config = {3 stripe: {4 secretKey: process.env.STRIPE_SECRET_KEY,5 publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,6 },7 twilio: {8 accountSid: process.env.TWILIO_ACCOUNT_SID,9 authToken: process.env.TWILIO_AUTH_TOKEN,10 },11 openai: {12 apiKey: process.env.OPENAI_API_KEY,13 }14};1516// Validate that required secrets are set17for (const [service, keys] of Object.entries(config)) {18 for (const [key, value] of Object.entries(keys)) {19 if (!value) {20 console.warn(`WARNING: ${service}.${key} is not set. Check Secrets panel.`);21 }22 }23}2425module.exports = config;Expected result: Your config module loads all secrets and logs warnings for any missing values.
Configure API key authentication in request headers
Configure API key authentication in request headers
Most APIs use one of three authentication methods: API key as a query parameter, API key in a custom header, or Bearer token in the Authorization header. Set up your HTTP client to include the correct authentication for each API you connect. Using axios, you can create preconfigured instances with default headers so you do not need to pass authentication on every request.
1const axios = require('axios');2const config = require('./config');34// Method 1: API key in custom header (e.g., OpenAI)5const openaiClient = axios.create({6 baseURL: 'https://api.openai.com/v1',7 headers: {8 'Authorization': `Bearer ${config.openai.apiKey}`,9 'Content-Type': 'application/json'10 }11});1213// Method 2: API key as query parameter14async function fetchWithKeyParam(endpoint) {15 const url = `https://api.example.com${endpoint}?api_key=${config.stripe.publishableKey}`;16 return axios.get(url);17}1819// Method 3: Basic auth (e.g., Twilio)20const twilioClient = axios.create({21 baseURL: 'https://api.twilio.com/2010-04-01',22 auth: {23 username: config.twilio.accountSid,24 password: config.twilio.authToken25 }26});Expected result: Axios instances are configured with the correct authentication headers for each external API.
Add deployment secrets separately from workspace secrets
Add deployment secrets separately from workspace secrets
This is the most critical step that most users miss. Workspace secrets (the ones you added in step 1) are only available in the development environment. When you deploy your app, you must add the same secrets separately in the Deployments pane. Open the Deployments tab, find the Secrets section, and add each secret again. The values can be different (for example, a live Stripe key instead of a test key). This separation is intentional: it prevents accidentally using test credentials in production.
Expected result: All required secrets are configured in both the workspace Secrets panel and the deployment Secrets section.
Test your API connections in development
Test your API connections in development
Before deploying, verify that each API connection works in the development environment. Create a simple test script that calls each API with a minimal request and logs the response status. Run it from the Shell. This catches issues like invalid API keys, incorrect authentication methods, or network restrictions early. If a call fails, check that the secret value is correct and that the API service is not blocking requests from cloud IP addresses.
1// test-connections.js — run with: node test-connections.js2const config = require('./config');3const axios = require('axios');45async function testConnections() {6 console.log('Testing API connections...\n');78 // Test OpenAI9 try {10 const res = await axios.get('https://api.openai.com/v1/models', {11 headers: { 'Authorization': `Bearer ${config.openai.apiKey}` }12 });13 console.log(`OpenAI: Connected (${res.data.data.length} models available)`);14 } catch (err) {15 console.error(`OpenAI: FAILED - ${err.response?.status || err.message}`);16 }1718 // Add similar tests for each API you use19}2021testConnections();Expected result: Each API connection test reports success with a valid response, or a clear error message indicating what went wrong.
Handle environment-specific API configurations
Handle environment-specific API configurations
Many APIs provide separate keys for test and production environments (like Stripe's test vs live keys). Use the REPLIT_DEPLOYMENT predefined environment variable to detect whether your code is running in the workspace or in a deployed environment. This variable is set to 1 in production deployments and is undefined in the workspace. Use this to select the correct configuration, such as Stripe test keys in development and live keys in production. For complex multi-environment setups that require staging environments or advanced credential rotation, RapidDev can help design a secure configuration architecture.
1// config.js — environment-aware configuration2const isProduction = process.env.REPLIT_DEPLOYMENT === '1';34const config = {5 stripe: {6 secretKey: isProduction7 ? process.env.STRIPE_LIVE_SECRET_KEY8 : process.env.STRIPE_TEST_SECRET_KEY,9 },10 apiBaseUrl: isProduction11 ? 'https://api.production-service.com'12 : 'https://api.sandbox-service.com',13 environment: isProduction ? 'production' : 'development'14};1516console.log(`Running in ${config.environment} mode`);17module.exports = config;Expected result: Your app automatically uses test credentials in the workspace and production credentials when deployed.
Complete working example
1/**2 * Centralized API configuration for Replit projects3 * All secrets are stored in the Replit Secrets panel (Tools > Secrets)4 * Deployment secrets must be added separately in Deployments > Secrets5 */67const isProduction = process.env.REPLIT_DEPLOYMENT === '1';89const config = {10 environment: isProduction ? 'production' : 'development',1112 stripe: {13 secretKey: isProduction14 ? process.env.STRIPE_LIVE_SECRET_KEY15 : process.env.STRIPE_TEST_SECRET_KEY,16 publishableKey: isProduction17 ? process.env.STRIPE_LIVE_PUBLISHABLE_KEY18 : process.env.STRIPE_TEST_PUBLISHABLE_KEY,19 },2021 openai: {22 apiKey: process.env.OPENAI_API_KEY,23 model: 'gpt-4o',24 },2526 twilio: {27 accountSid: process.env.TWILIO_ACCOUNT_SID,28 authToken: process.env.TWILIO_AUTH_TOKEN,29 },3031 database: {32 url: process.env.DATABASE_URL,33 },34};3536// Validate required secrets at startup37const required = ['OPENAI_API_KEY'];38const missing = required.filter(key => !process.env[key]);3940if (missing.length > 0) {41 console.error(`Missing required secrets: ${missing.join(', ')}`);42 console.error('Add them in Tools > Secrets (workspace) and Deployments > Secrets (production)');43 if (isProduction) {44 process.exit(1);45 }46}4748console.log(`Config loaded for ${config.environment} environment`);4950module.exports = config;Common mistakes when connecting Replit to external APIs
Why it's a problem: Creating a .env file in Replit instead of using the Secrets panel
How to avoid: Delete the .env file and add all variables to the Secrets panel (Tools > Secrets). Replit Secrets are AES-256 encrypted. A .env file in your project is visible to anyone who views the public Repl.
Why it's a problem: Forgetting to add secrets to the Deployments pane
How to avoid: Workspace secrets do not carry to deployments. Open the Deployments tab, find the Secrets section, and add each required secret. This is the number one cause of deployed apps showing undefined errors.
Why it's a problem: Using the same API key for development and production (especially with payment APIs)
How to avoid: Use test/sandbox keys in workspace secrets and live/production keys in deployment secrets. The REPLIT_DEPLOYMENT variable helps your code select the right set automatically.
Why it's a problem: Installing dotenv package in a Replit project
How to avoid: The dotenv package is unnecessary in Replit. Secrets are automatically available as environment variables through process.env. Adding dotenv can cause conflicts if it tries to load a nonexistent .env file.
Best practices
- Always use the Replit Secrets panel instead of .env files or hardcoded credentials
- Create a centralized config module that validates all required secrets at startup
- Add deployment secrets separately from workspace secrets in the Deployments pane
- Use REPLIT_DEPLOYMENT to detect production vs development and select appropriate credentials
- Create separate axios instances for each external service with preconfigured authentication
- Use consistent naming conventions for secrets: SERVICE_KEY_TYPE (e.g., STRIPE_LIVE_SECRET_KEY)
- Test all API connections in development before deploying
- Never log secret values, even in development. Log only connection success or failure status.
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
I need to connect my Replit Node.js project to the [service name] API. My API key is stored in Replit Secrets as [KEY_NAME]. Show me how to create a secure configuration module that accesses the secret, sets up authenticated API requests, and handles the difference between workspace and deployment environments using REPLIT_DEPLOYMENT.
Set up API authentication for my project. I need to connect to [service name] using a Bearer token stored in Secrets as [KEY_NAME]. Create a config module that validates the secret at startup, an axios instance with the auth header preconfigured, and a test script I can run in Shell to verify the connection works.
Frequently asked questions
Workspace secrets do not automatically transfer to deployments. You must add each secret separately in the Deployments pane under the Secrets section. This is the most common cause of deployment failures in Replit.
Technically yes, but you should not. A .env file in your project is visible to anyone who views your public Repl. The Secrets panel encrypts values with AES-256 and never exposes them to visitors or forkers.
Check the REPLIT_DEPLOYMENT environment variable. It is set to 1 in production deployments and is undefined in the workspace. Use this to select the appropriate credentials in your config module.
No. Secrets are only available at runtime, not during the build phase. If your build process needs environment variables, you need to find alternative approaches such as setting build-time defaults.
Yes. Collaborators with edit access can view both secret names and values. Only invite trusted team members as collaborators. Cover page visitors see nothing, and users who fork your Repl see secret names but not values.
Yes. RapidDev specializes in configuring production-grade API integrations including OAuth flows, webhook handling, multi-environment credential management, and secure architecture design for Replit-based projects.
The secret is available to new processes immediately, but existing running processes may not pick it up. Click the Stop button and then Run to restart your app. In Shell, run kill 1 to reload the environment.
Use os.getenv('MY_SECRET') or os.environ['MY_SECRET'] after importing the os module. The Secrets panel works the same way regardless of programming language.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation