How to encrypt field level using payload?

default discord avatar
kalib-codelast year
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

  • Selected Answer
    discord user avatar
    DanRibbens
    last year

    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-codelast year

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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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