Environmental Variables
Environment variables can be API keys, URLs, database credentialsβanything you need to configure a specific environment really. Some are sensitive so they should never be shared as-is in your code or in public, but others are simply useful constants to have around that you only want to define once
Environment Variable Types in Next.jsβ
Next.js distinguishes between two types of environment variables based on who can access them:
-
Server (backend)
-
Client (browser)
1. π Server-Only Variablesβ
These variables are accessible only in server-side code, such as:
-
API routes (/pages/api/*)
-
getServerSideProps -
Custom server logic
-
Any code that runs on the server
-
Do not prefix or start Server-Only Variables with
NEXT_PUBLIC_. -
Never expose secrets (API keys, DB credentials) to the client.
-
Available via
process.env.[key]only in server-side code.
2. π Public Variables (Client + Server)β
These variables are available both on the client and the server.
They are typically used for:
-
Public API endpoints
-
Project IDs
-
Analytics keys
-
Any non-sensitive config used in the browser
If you are working inside Next.js framework then you should have to prefix Public Variables with NEXT_PUBLIC_