node.jstwiliosendgridsendgrid-templatessendgrid-nodejs

How to provide dynamic_template_data without hardcoding it?


TLDR; How do I fetch my dynamic_template_data from an API call instead of hardcoding it? I am using the node.js implementation.

I am following the How to send email with dynamic templates guide.

According to the docs...

In order to send dynamic content, you need to specify a JSON blob containing the dynamic data your template will use in the dynamic_template_data object.

And they provide this example where they have hardcoded in some JSON data. The data I would be providing would be coming from an API call to a database. How do I provide the data from an API call instead of hardcoding it like in the example?

         "dynamic_template_data":{
            "total":"$ 239.85",
            "items":[
               {
                  "text":"New Line Sneakers",
                  "image":"https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png",
                  "price":"$ 79.95"
               },
               {
                  "text":"Old Line Sneakers",
                  "image":"https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png",
                  "price":"$ 79.95"
               },
               {
                  "text":"Blue Line Sneakers",
                  "image":"https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png",
                  "price":"$ 79.95"
               }
            ],
            "receipt":true,
            "name":"Sample Name",
            "address01":"1234 Fake St.",
            "address02":"Apt. 123",
            "city":"Place",
            "state":"CO",
            "zip":"80202"
         }

Solution

  • You can use the object you get back from your DB query and directly pass it to the sendgridClient.send() function of the @sendgrid/mail client.

    This pseudo code hopefully explains this:

    const sendgridClient = new MailService();
    sendgridClient.setApiKey(process.env.SENDGRID_API_KEY || "");
    const dbClient = new DBClient()
    
    const movies = dbClient.collection('movies');
    const query = { title: 'Back to the Future' };
    const movie = await movies.findOne(query);
    
    await sendgridClient.send({
       to: {
          email: entry.email,
       },
       from: {
          email: "lottery@<YOUR DOMAIN HERE>",
          name: "SendGrid Demo",
       },
       templateId: "<TEMPLATE ID>",
       dynamicTemplateData: {
          movie
       },
    });