How to encrypt field level using payload?

default discord avatar
kalib-code
10 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

  • discord user avatar
    DanRibbens
    Payload Team
    10 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
  • default discord avatar
    kalib-code
    10 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
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.