Environment variables

Environment variables store configuration outside your application code, such as API addresses, service keys and database connection strings. They let you use different settings for local development and production.

Add your variables

For local development, create .env.local in the project root, beside package.json. Add the variables required by the services you connect. These names are examples:

.env.local
SERVICE_API_KEY=your_service_key
NEXT_PUBLIC_API_URL=https://api.example.com

Next.js loads the file automatically. Keep .env.local and real credentials out of version control. See Next.js environment variables for supported files and loading rules.

Read variables in your code

Read a value through process.env using its exact name. Adding a variable makes it available to your code; you still need to use it in the service or setting it configures.

Server-only values

By default, variables without NEXT_PUBLIC_ are available to server-side code, such as server functions and route handlers:

const serviceApiKey = process.env.SERVICE_API_KEY

Use these for private credentials. Keep the values on the server: returning them in API responses or passing them to client components would expose them.

Browser-visible values

Prefix a variable with NEXT_PUBLIC_ when browser code needs it. Use this only for values safe to share publicly, such as a public API address:

const apiUrl = process.env.NEXT_PUBLIC_API_URL

Use the direct property access shown above. Next.js does not inline browser values read through a dynamic name such as process.env[variableName].

Deployment

Configure the variables in your hosting provider's environment settings, using the values needed for that deployment.

Set NEXT_PUBLIC_ values before next build. Next.js embeds them in the browser JavaScript, so changing them requires rebuilding and redeploying the app.

Server-side values read while handling a request can come from the running server's environment. Values used while building pages must also be available during the build. See the Next.js deployment guidance for build-time and runtime configuration.