How to Set Subject Line in SendGrid with Dynamic Templates

Published Feb 21, 2022  ∙  Updated May 2, 2022

I recently ran into an issue where SendGrid wasn’t setting the subject line in my emails while using dynamic templates.

SendGrid with Node.js

I had SendGrid set up on the server-side using Node.js.

import sgMail from '@sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const sendEmail = async (email, subject, text) => {
  try {
    await sgMail.send({
      from: 'from@example.org',
      personalizations: [
        to: { email },
        dynamicTemplateData: { subject, text }
      ],
      templateId: 'd-f43daeeaef504760851f727007e0b5d0'
    });
  } catch (e) {
    console.error(e);
  }
}

However, the subject field was not being populated in the email.

No subject line with dynamic templates

In order for the subject line to be set, we need to set it in the template on the SendGrid website.

  • Head over to the Dynamic Templates page under Email API
  • Edit the appropriate template
  • Select Settings (gear icon on the left)
  • In the Subject field, add {{{subject}}}

Now after sending the payload, the subject field in dynamicTemplateData should populate the subject line.