Search code examples
node.jsexpresspugtemplate-enginecheerio

Inject meta tag dynamically to HTML with Express


Summary:

I'm currently migrating a website on Apache + PHP stack over to Node + Express, and would like to know what is the best way/best practice (if there is one) for dynamically injecting meta tags under the new stack.

Details:

Under the existing stack, meta tags are injected dynamically by adding PHP codes into the HTML file directly. As rendering is done on server side, the tags are properly interpreted by Facebook/Google+/whatever web crawlers.

Under the new stack, after doing some research, I've come across two options:

  1. Use template engine like Pug (Jade) to render the HTML with locals. (It seems to be an overkill to rewrite the existing HTML with Pug's syntax though? Can Pug deal with HTML, or I've to consider other template engine like EJS? What template engine do you advise me to explore?)
  2. Use DOM manipulation plugin like Cheerio to inject the meta tags first, before rendering begins.

Between these two options, which one will have a better performance or there is no material difference? Are there any other ways that you'd otherwise recommend? Thanks!


Solution

  • EJS would probably be the simplest one for that and very similar to PHP.

    You can also take a look at Mustache and Handlebars for other options with minimal changes to your existing HTML.

    • with EJS: <html><head><%= yourMetaTags %> ...
    • with Mustache: <html><head>{{ yourMetaTags }} ...
    • with Handlebars: <html><head>{{ yourMetaTags }} ...

    Also doT.js is very fast.

    See:

    Parsing the HTML and manipulating it with a DOM API just to insert meta tags would be an overkill in my opinion.

    On the other hand if all you need is to insert meta tags then you could make a simple regex substitution, using something like yourHTML.replace('<head>', '<head>'+yourMetaTags); but it could potentially get more complex over time when you need more functionality. After all, everyone has made a templating engine at some point in life.