No articles found
Try different keywords or browse our categories
Fix: Environment variables not working in Next.js error
Quick fix for environment variables not working in Next.js. Learn how to properly configure and use environment variables in Next.js applications.
The ‘Environment variables not working in Next.js’ error occurs when environment variables are not properly configured or accessed in Next.js applications. This can happen due to incorrect naming, wrong file placement, or misunderstanding the difference between server and client-side access.
How the Error Happens
❌ Error Scenario - Wrong Variable Naming:
// ❌ This won't work on client-side
// app/page.js
export default function HomePage() {
// ❌ Regular environment variables are not available on client
const apiKey = process.env.API_KEY; // ❌ Returns undefined on client
return <div>API Key: {apiKey}</div>;
}
❌ Error with Missing .env File:
// ❌ This won't work if .env file doesn't exist
// app/api/data/route.js
export async function GET() {
// ❌ Will be undefined if not properly configured
const apiUrl = process.env.API_URL;
const res = await fetch(apiUrl); // ❌ May fail
return Response.json(await res.json());
}
❌ Error with Wrong Prefix:
// ❌ This won't work
// .env file
API_KEY=your_secret_key # ❌ Missing NEXT_PUBLIC_ prefix for client access
✅ Quick Fix - Proper Environment Variable Setup
Solution 1: Correct .env File Setup
# ✅ Create .env.local file in project root
# .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_APP_NAME=My App
DB_HOST=localhost
DB_PORT=5432
API_KEY=your_secret_api_key
// ✅ Access environment variables correctly
// app/page.js
export default function HomePage() {
// ✅ Public variables available on client
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
const appName = process.env.NEXT_PUBLIC_APP_NAME;
// ✅ Private variables only available on server
// const apiKey = process.env.API_KEY; // ❌ Only available on server
return (
<div>
<h1>{appName}</h1>
<p>API URL: {apiUrl}</p>
</div>
);
}
Solution 2: Server-Side Environment Variables
// ✅ Server Component with private environment variables
// app/dashboard/page.js
export default async function DashboardPage() {
// ✅ Private variables work in Server Components
const apiKey = process.env.API_KEY;
const dbHost = process.env.DB_HOST;
// Use private variables for server-side operations
const res = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${apiKey}`
}
});
const data = await res.json();
return (
<div>
<h1>Dashboard</h1>
<p>Connected to: {dbHost}</p>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
Solution 3: API Route Environment Variables
// ✅ API route with environment variables
// app/api/data/route.js
import { NextResponse } from 'next/server';
export async function GET() {
const apiKey = process.env.API_KEY;
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
if (!apiKey) {
return NextResponse.json(
{ error: 'API key not configured' },
{ status: 500 }
);
}
try {
const res = await fetch(`${apiUrl}/endpoint`, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (!res.ok) {
throw new Error('Failed to fetch data');
}
const data = await res.json();
return NextResponse.json(data);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch data' },
{ status: 500 }
);
}
}
Solution 4: Client-Side with Server-Side Propagation
// ✅ Server Component that passes env vars to client
// app/page.js
async function fetchConfig() {
// ✅ Access private env vars on server
return {
publicApiUrl: process.env.NEXT_PUBLIC_API_URL,
isProduction: process.env.NODE_ENV === 'production',
// Private vars stay on server
serverTime: new Date().toISOString()
};
}
export default async function HomePage() {
const config = await fetchConfig();
return (
<div>
<h1>Home Page</h1>
{/* ✅ Pass only public data to client component */}
<ClientComponent config={config} />
</div>
);
}
// ✅ Client Component receiving server-provided config
// components/ClientComponent.js
'use client';
export default function ClientComponent({ config }) {
return (
<div>
<p>API URL: {config.publicApiUrl}</p>
<p>Environment: {config.isProduction ? 'Production' : 'Development'}</p>
<p>Server Time: {config.serverTime}</p>
</div>
);
}
Solution 5: Environment Variable Validation
// ✅ Utility for environment variable validation
// lib/env.js
export function getEnvVariable(name, fallback = null) {
const value = process.env[name] || fallback;
if (value === null || value === undefined) {
if (process.env.NODE_ENV === 'production') {
throw new Error(`Environment variable ${name} is required`);
}
console.warn(`Environment variable ${name} is not set`);
}
return value;
}
export const config = {
apiUrl: getEnvVariable('NEXT_PUBLIC_API_URL', 'http://localhost:3000/api'),
isProduction: process.env.NODE_ENV === 'production',
enableDebug: getEnvVariable('ENABLE_DEBUG', 'false') === 'true'
};
// ✅ Using validated environment variables
// app/utils/api.js
import { config } from '../lib/env';
export async function apiRequest(endpoint, options = {}) {
const response = await fetch(`${config.apiUrl}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
return response.json();
} Related Articles
Fix: cookies() can only be used in Server Components error Next.js
Quick fix for 'cookies() can only be used in Server Components' error in Next.js. Learn how to properly use cookies in Server Components.
Fix: document is not defined in Next.js Error - Complete Client-Side Guide
Complete guide to fix 'document is not defined' error in Next.js applications. Learn how to handle browser APIs safely in server-side rendering environments.
Fix: Dynamic server usage Next.js error
Quick fix for 'Dynamic server usage' error in Next.js. Learn how to handle dynamic data fetching and server components properly.