Incorrect NODE_ENV settings affecting API calls

Loading

When your NODE_ENV environment variable is misconfigured, it can cause API calls to point to wrong endpoints, use incorrect credentials, or apply improper request/response handling. Here’s how to diagnose and fix these issues.

Common Symptoms

  1. API calls going to development endpoints in production
  2. Missing authentication headers in production
  3. Debug logging appearing in production
  4. CORS errors that only occur in certain environments
  5. Different API behavior between local development and deployed app

Correct Configuration Approaches

1. Basic Environment Detection

// In your API configuration file
const baseURL = process.env.NODE_ENV === 'production'
  ? 'https://api.production.com'
  : 'https://api.development.com';

const axiosInstance = axios.create({
  baseURL,
  timeout: 10000,
});

2. Using .env Files

# .env.development
REACT_APP_API_BASE_URL=https://api.dev.example.com
REACT_APP_DEBUG=true
# .env.production
REACT_APP_API_BASE_URL=https://api.example.com
REACT_APP_DEBUG=false

3. Webpack Configuration (for custom builds)

// webpack.config.js
const webpack = require('webpack');

module.exports = (env) => ({
  plugins: [
    new webpack.DefinePlugin({
      'process.env.API_URL': JSON.stringify(
        env.production 
          ? 'https://prod.api.com' 
          : 'https://dev.api.com'
      )
    })
  ]
});

Common Mistakes and Fixes

Mistake 1: Hardcoding API URLs

// ❌ Bad - hardcoded URL
const response = await axios.get('http://localhost:3000/api/data');

Fix: Use environment variables

// ✅ Good - environment-based URL
const response = await axios.get(`${process.env.REACT_APP_API_BASE}/data`);

Mistake 2: Incorrect NODE_ENV in build scripts

// ❌ Bad - might not set NODE_ENV properly
{
  "scripts": {
    "build": "webpack"
  }
}

Fix: Explicitly set environment

// ✅ Good
{
  "scripts": {
    "build": "NODE_ENV=production webpack",
    "build:dev": "NODE_ENV=development webpack"
  }
}

Advanced Configuration

1. Dynamic API Configuration

// api/config.js
const env = process.env.NODE_ENV || 'development';

const configs = {
  development: {
    apiBase: 'https://dev.api.com',
    authType: 'basic',
    logging: true
  },
  production: {
    apiBase: 'https://api.com',
    authType: 'bearer',
    logging: false
  },
  test: {
    apiBase: 'http://localhost:3000',
    authType: 'none',
    logging: false
  }
};

export default configs[env];

2. Conditional Interceptors

// axios instance configuration
if (process.env.NODE_ENV === 'development') {
  axiosInstance.interceptors.request.use(request => {
    console.log('Request:', request);
    return request;
  });
}

Deployment Considerations

  1. Verify environment variables are set correctly on your hosting platform
  2. Check build process ensures proper NODE_ENV is set
  3. Test API endpoints in staging environment before production
  4. Use different API keys for development and production

For Create React App users, remember that:

  • Variables must start with REACT_APP_ to be included in the build
  • The development server uses development by default
  • npm run build sets NODE_ENV=production automatically

Troubleshooting Checklist

  1. Verify process.env.NODE_ENV value at runtime
  2. Check bundled code for replaced environment variables
  3. Ensure hosting platform has correct environment variables set
  4. Test API calls from different environments
  5. Verify CORS settings on API servers for all environments

Leave a Reply

Your email address will not be published. Required fields are marked *