Skip to content

.env variables not prefixed with NEXT_PUBLIC_ are not being overridden by netlify.toml contexts #2754

Open
@ryanwalters

Description

@ryanwalters

Only variables defined in .env files that are prefixed with NEXT_PUBLIC_ are being properly overridden when defined in a netlify.toml context. (I'm using Stripe keys only for illustrative purposes and wouldn't recommend putting the secret key in .env or netlify.toml)

Example

# .env
NEXT_PUBLIC_SITE_KEY="test_site_123"
SECRET_KEY="test_secret_123"
# netlify.toml
[context.production.environment]
  NEXT_PUBLIC_SITE_KEY="live_site_456"
  SECRET_KEY="live_secret_456"

In this example, after deploying to production, the environment variables will have the following values:

  • NEXT_PUBLIC_SITE_KEY = live_site_456
  • SECRET_KEY = test_secret_123

Next.js environment variables docs. Note that Next.js supports environment variables not prefixed with NEXT_PUBLIC_.

We are using @netlify/[email protected].


I am opening the issue here since Netlify support pointed us in this direction:

I believe the different with the NEXT_PUBLIC_ environment variables is due to special processing done by the Next.js runtime plugin at Netlify:

https://www.npmjs.com/package/@netlify/plugin-nextjs

It does specially processing for any environment variables starting with NEXT_PUBLIC_ and there is a some documentation (but not about this behavior) here:

https://docs.netlify.com/frameworks/environment-variables/#custom-variables

I believe it is the runtime itself doing this. For example, if you tested this on a site that does not use Next.js or this plugin but you still made environment variables in both .env and netlify.toml you would not see the override behavior. This is because it is the plugin itself that is doing this override.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions