Avoid Hardcoding API URLs — Use Environment Variables Properly
~1 min read
💡TL;DR
Hardcoding API URLs makes your app hard to manage across environments. Use environment variables for flexibility and security.
Many developers directly write API URLs in code like this:
const API_URL = "https://api.production.com";
This creates problems when switching between environments (local, staging, production).
Better approach:
Use environment variables:
For Next.js:process.env.NEXT_PUBLIC_API_URL
For Node.js:process.env.API_URL
Example:
TypeScript
const API_URL = process.env.NEXT_PUBLIC_API_URL;Benefits:
- Easy environment switching
- Cleaner code
- Better security (no secrets in code)
Pro tip:
Never expose sensitive keys using NEXT_PUBLIC — only use it for public data.
environment-variablesbest-practicesNode.jsNext.js
💡
Get a new Daily Dev Tip in your inbox
Subscribe to Stack Dev Life — free, no spam, unsubscribe anytime.
Subscribe free →