Standalone output copies .env files

Hi community! :waving_hand:
I’m currently struggling with environment variables settings with nextjs standalone output.

The standalone output copies .env file despite outputFileTracingExcludes set in next.config.ts.

Any one having the same issue?

Current

  • Next.js standalone mode copies .env files to the output directory

  • outputFileTracingExcludes doesn’t prevent this behavior

  • This creates security issues for Docker deployments where secrets get baked into images

  • Workaround: manually delete .env files post-build in Dockerfile

Expected

  • outputFileTracingExcludes should exclude .env files from standalone output

I tried with next.config.ts:

output: "standalone",
outputFileTracingExcludes: {
  "*": [
    ".env",
    ".env.*",
    ".env.local",
    ".env.development",
    ".env.production",
    "**/.env",
    "**/.env.*",
  ],
},

This is a known behavior with Next.js standalone output. The .env files are copied because Next.js needs them at runtime to provide environment variables to the application.

outputFileTracingExcludes is for to excluding files from dependency tracing and shouldn’t affect this at all

The standalone output needs to be self-contained with all necessary files for runtime, which means if you provide a .env file for environment variables then that becomes an expected file to run it. If you have an alternative way to provide environment variables at runtime (as you should and do), the output process doesn’t know about that.

If your environment variables are already available in the build environment, you should be able to delete the .env file before running the build and then Next.js will not copy it into the output directory

If you do need to read it while building the docker image, I’d recommend deleting the .env file in your Dockerfile immediately after your Build layer

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.