Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How to encrypt field level using payload?

default discord avatar
kalib-code2 years 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

  • Selected Answer
    discord user avatar
    DanRibbens
    2 years 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-code2 years ago

    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.