Capítulo 211 de 456

env (next.config.js)

Core Idea

Legacy API to inline environment variables into the JS bundle at build time via next.config.js; superseded by the standard .env files approach since Next.js 9.4 — avoid for new code.

Key Concepts

  • env config: object of key/value pairs; values are always inlined into the client bundle (no NEXT_PUBLIC_ prefix needed/relevant here).
  • Build-time replacement: process.env.customKey is replaced with the literal value via webpack DefinePlugin, so destructuring process.env doesn't work.

Code Examples

module.exports = {
  env: {
    customKey: 'my-value',
  },
}
  • O que demonstra: expor process.env.customKey no bundle.
function Page() {
  return <h1>The value of customKey is: {process.env.customKey}</h1>
}
  • O que demonstra: acessar a variável injetada; vira literal 'my-value' em build time.

Anti-patterns

  • Usar env config pra novos projetos: é API legada; prefira a abordagem padrão de variáveis de ambiente (.env, prefixo NEXT_PUBLIC_).
  • Destructurar process.env: const { customKey } = process.env não funciona por causa de como o webpack DefinePlugin substitui a expressão.

Key Takeaways

  1. Valores aqui SEMPRE vão pro bundle do cliente, mesmo sem NEXT_PUBLIC_, cuidado com segredos.
  2. Prefira o fluxo moderno de environment variables em vez desta config.

Connects To

  • Environment Variables guide: abordagem recomendada que substitui esta config legada.