Capítulo 247 de 456

taint

Core Idea

Experimental config that enables React's tainting APIs, letting you mark objects or values as forbidden from crossing the Server-Client boundary, an extra defensive layer against accidentally leaking sensitive data to Client Components.

Key Concepts

  • experimental.taint: boolean flag; enabling it also switches the app directory to the React experimental channel.
  • experimental_taintObjectReference: taints an object reference so passing the whole object to a Client Component throws.
  • experimental_taintUniqueValue: taints a specific primitive value (e.g. an API key) tracked by reference/lifetime, not by the variable holding it.
  • Caveats: tainting only tracks by reference (a copy is untainted); derived values are not automatically tainted; values remain tainted only while their reference is in scope.

Code Examples

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    taint: true,
  },
}

export default nextConfig
import { experimental_taintUniqueValue } from 'react'

async function getSystemConfig(): Promise<SystemConfig> {
  const config = await configService.getConfigDetails()

  experimental_taintUniqueValue(
    'Do not pass configuration tokens to the client',
    config,
    config.SERVICE_API_KEY
  )

  return config
}
  • O que demonstra: como taintar um valor único (API key) para que passá-lo a um Client Component lance erro, enquanto outros campos do objeto continuam acessíveis.

Anti-patterns

  • Confiar só no taint como mecanismo de segurança: a doc avisa explicitamente para não depender só disso; seguir as recomendações de segurança do Next.js para Server Components/Actions.
  • Esquecer de taintar cópias/valores derivados: version::${apiKey} não é bloqueado, pois tainting não propaga para valores derivados.
  • Reatribuir a uma nova variável esperando escapar do taint: reassignment não remove o taint de um valor único; ele continua rastreado.

Key Takeaways

  1. Habilitar taint também ativa o canal experimental do React para app.
  2. taintObjectReference protege o objeto inteiro; taintUniqueValue protege um campo/valor específico.
  3. O ideal é já modelar a API para não retornar dado sensível onde não é necessário, tainting é defesa extra, não solução primária.
  4. Tainting rastreia por referência: cópias e valores derivados (concatenação, template string) escapam do rastreio.

Connects To

  • Server/Client boundary de Server Components: taint existe justamente para reforçar esse limite.
  • security-nextjs-server-components-actions (blog): recomendações de segurança complementares citadas na doc.