Search code examples
reactjstypescriptfirebasenext.jsgoogle-cloud-functions

How to make React-Email & Resend work with Firebase Cloud Functions


I have a Nextjs app that utilizes both React-Email, Resend & Firebase Cloud Functions. The directory structure looks like this:

enter image description here

I want to send an email to a user whenever a doc is created in "emailVerification" collection, here's what the cloud function looks like:

import * as logger from "firebase-functions/logger";
import {onDocumentCreated} from "firebase-functions/v2/firestore";
import { Resend } from 'resend'
import EmailVerificationTemplate from '../../react-email/emails/EmailVerification'
import { render } from '@react-email/components';

const resend = new Resend(RESEND_API_KEY);

export const sendEmailVerification = onDocumentCreated("/emailVerifications/{id}", async (event) => {
    // Grab the current value of what was written to Firestore.
    const data = event?.data?.data();

    // Access the parameter `{documentId}` with `event.params`
    logger.log("Requesting email verification for uid", event.params.id, data);

    const emailHtml = render(EmailVerificationTemplate({
        validationCode: data?.code.toString()
    }));

    await resend.emails.send({
        from: '[email protected]',
        to: data?.email,
        subject: 'Your Halbert Verification Code',
        html: emailHtml
    });

});

However, I'm getting this error when I try to deploy this function using: firebase deploy --only functions:

enter image description here

How do I solve for these errors?


Solution

  • I very much suggest that you NOT use React in a Cloud Function for the sole purpose of generating an HTML email body. Pulling in all of the dependencies that would entail is insane and you almost certainly will run into dependency hell since many of React or its packages assume they are executing in a browser context, which Cloud Functions very much is not.

    I recommend you look to some NodeJS package that does not rely on React (or any other heavy UI framework). Maybe something like email-templates ?

    You might be able to get the above code to eventually work through all of the TypeScript warnings/errors and get all the correct dependencies installed, but that is an incredible amount of technology for what is essentially a search-and-replace effort of an HTML body.