What is the difference between a regular environment variable and one prefixed with NEXT_PUBLIC in Next.js?
Short answer
A regular environment variable is only available on the server and stays hidden from the browser, while one prefixed with NEXT_PUBLIC gets included in the JavaScript bundle sent to the browser, making it accessible from client components, so you should never put secrets behind…
Advertisement
AModel answer
A regular environment variable is only available on the server and stays hidden from the browser, while one prefixed with NEXT_PUBLIC gets included in the JavaScript bundle sent to the browser, making it accessible from client components, so you should never put secrets behind that prefix.
# .env.local
DATABASE_URL=secret-connection-string
NEXT_PUBLIC_API_URL=https://api.example.comReal-world example
A weather app exposes its public API base URL using the NEXT_PUBLIC prefix so client components can build request URLs, while keeping its actual API secret key as a regular, server only environment variable.
Likely follow-ups
- What happens if you accidentally put a secret behind the NEXT_PUBLIC prefix?
- Can you change a NEXT_PUBLIC variable after the app has already been built?
Related topics