Hello Friends,

Welcome To Infinitbility!

This article explain and provide example to implement Mustache template in node js. we are assuming you want send mustache template content in your mail function.

Let’s start today topic integrate mustache template in nodejs with typescript

  1. Start with Installation

        npm install consolidate mustache --save

    install consolidate and mustache library to setup mustache render engine

  2. Setup mustache engine


    • import consolidate engine
    import engine from "consolidate";
    • create private function initializeMailTemplate
    private initializeMailTemplate(){
        // set templates folder
        this.app.set('views', __dirname + '/views');
        // // set html templating engine
        this.app.engine('html', engine.mustache);
        this.app.set('view engine', 'html');
    • call from constructor
    constructor(routes: Routes[]) {
        this.app = express();
  3. use engine in nodejs controler for render template


    import { NextFunction, Request, Response } from 'express';
    import sendMail from "@utils/sendMail";
    class MailsController {
        * Send Mail
        * @param req 
        * @param res 
        * @param next 
        public emails = async (req: Request, res: Response, next: NextFunction) => {
            try {
                const email: string = req.body.email;
                const template: string = req.body.template;
                const template_data: object = req.body.template_data;
                // template will be your template file name
                res.render(template, template_data, function (err, html) {
                    const msg = {
                        to: email, // Change to your recipient
                        from: process.env.SENT_MAIL_ID, // Change to your verified sender
                        subject: 'Welcome To Infinitbility',
                        html: html,
                res.status(200).json({ message: 'Mail Sent Successfully' });
            } catch (error) {
    export default MailsController;
  4. Create html template

    • create views folder on your src folder and add below registration template


    <!DOCTYPE html>
                    Hi {{name}},
                    Thank You For Registration.

Thanks For Reading…