Use dynamic window.CONFIG.API_URL
based on location.hostname
, no build tools required.
<!-- In index.html -->
<script>
window.CONFIG = {
API_URL: location.hostname === 'localhost'
? '<http://localhost:5000>' // local backend server
: '<https://your-production-server.com>' // production backend server
};
</script>
Use in fetch:
fetch(`${window.CONFIG.API_URL}/api/xxx`)
.then(res => res.json())
.then(data => console.log(data));
Use .env
locally + environment panel on cloud platform (Render/Fly.io/etc).
Install dotenv
:
npm install dotenv
At the top of your server code:
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
.env (for local development):
PORT=5000
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
NODE_ENV=development
Important:
PORT
in production .env
.PORT
, your server must use process.env.PORT
.SUPABASE_URL
, SUPABASE_ANON_KEY
are identical between dev and prod..env
in Git: add .env
to .gitignore
.https://your-app.fly.dev
).