SonS
Convex Community2y ago
6 replies
Son

Using crypto in convex functions

i have this utility function...
util.ts, stored outside/inside convex folder, same issues.

import crypto from 'crypto';

export function encrypt(text: string) {
  const secret = process.env.SECRET;
  if (!secret) {
    throw new Error('Secret for encryption is not defined');
  }
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secret), Buffer.alloc(16));
  let encrypted = cipher.update(text, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return encrypted;
}


which i want to use in a query like this

export const createMessage = mutation({
    args: { author: v.string(), body: v.string() },
    handler: async (ctx, { author, body }) => {

        const encryptedText = encrypt(body);
        
        const response = await ctx.db.insert('messages', { author, body: encryptedText });

        if (!response) {
            return 'failed';
        }

        return 'success';
    }
});


This does not work because the code is running on the client side and the crypto module only exists on the sever, this might be a silly question but where can i write the sever code to encrypt my messages.
Screenshot_2024-02-01_at_21.40.52.png
Was this page helpful?