Like what we’re doing? Star us on GitHub!

How to encrypt field level using payload?

kalib-code
4 months ago
1 1

I am new to payload and I was hoping if payload can handle encrypt field level to DB and decrypt on payload UI

  • DanRibbens
    Payload Team
    4 months ago

    Here is an example using Payload's own ecrypt and decrypt functions.

    // encryptionHooks.ts
    import { FieldHook } from 'payload/types';
    
    const encryptKey: FieldHook = ({ req, value }) => (value ? req.payload.encrypt(value as string) : undefined);
    const decryptKey: FieldHook = ({ req, value }) => (value ? req.payload.decrypt(value as string) : undefined);
    
    const encryptionHooks = {
      beforeChange: [
        encryptKey,
      ],
      afterRead: [
        decryptKey,
      ],
    };
    
    export default encryptionHooks;

    Example usage in a field:

    import encryptionHooks from '../../fields/encryptionHooks';
    
    const Customers: CollectionConfig = {
    	slug: 'customers',
    	fields: [
    		{
    			name: 'ssn',
    			label: 'SSN',
    			type: 'text',
    			hooks: encryptionHooks,
    		},
    	],
    };
    1 reply
  • kalib-code
    4 months ago

    so payload encrypts and decrypt is already in the payload you just need to use it. that's amazing

Open the post
Continue the discussion in GitHub
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More