Skip to Content
Zod Config

Transform

Rename, reshape or drop key-value pairs before they are validated.

The transform option modifies key-value pairs before the schema processes them. Use it to normalize data, filter out unwanted keys or change values. The function receives an object with key and value, and returns either a transformed object or false to drop the pair.

transform can be set globally (all adapters) or on one adapter. When both are set, the adapter-level transform takes precedence.

transform is the first step of the processing pipeline: it runs before key matching, the nesting separator and the other features.

import {  } from 'zod';
import {  } from 'zod-config';
import {  } from 'zod-config/env-adapter';

const  = .({
  : .({
    : .(),
    : .(),
  }),
  : .(),
});

// Global transform - applied to all adapters
const  = await ({
  ,
  : ({ ,  }) => {
    // Drop sensitive keys
    if (.('SECRET')) {
      return false;
    }

    // Transform keys to lowercase
    return {
      : .(),
      ,
    };
  },
  : ({
    : {
      : 'localhost',
      : '5432',
      : 'my-key',
      : 'should-be-dropped',
    },
    : '_',
  }),
});

// Adapter-level transform - applied only to this adapter
const  = await ({
  ,
  : ({
    : {
      : 'localhost',
      : '5432',
      : 'my-key',
      : 'ignored',
    },
    : ({ ,  }) => {
      // Only process keys that start with 'MY_APP_'
      if (!.('MY_APP_')) {
        return false;
      }

      // Remove the prefix and convert to lowercase
      const  = .(/^MY_APP_/, '').();

      return {
        : ,
        ,
      };
    },
    : '_',
  }),
});

// Complex transformation with multiple operations
const  = await ({
  : .({
    : .({
      : .(),
      : .(),
    }),
    : .({
      : .(),
      : .(),
    }),
  }),
  : ({
    : {
      : 'secret123',
      : '30000',
      : 'localhost',
      : '5432',
      : '3600',
    },
    : ({ ,  }) => {
      // Transform different prefixes to nested structure
      if (.('API_')) {
        return {
          : .('API_', 'api.').(),
          ,
        };
      }

      if (.('DB_')) {
        return {
          : .('DB_', 'database.').(),
          ,
        };
      }

      // Drop other keys
      return false;
    },
    : '.',
  }),
});