How to replace content in static files with Node.js

How to replace content in static files with Node.js

Sometimes we have HTML files with content that depends on the environment or a variable in order to render specific content and send it to the browser. A natural way to handle this type of use cases is by using a server-side rendering library like handlebars or pug. Unfortunately, to include these libraries is not always possible or we don’t want to set up the project to support them.

If that’s the case (as it was for us) you’ll find the package string-replace-middleware very useful.

The core value of this package is to add the ability to replace simple strings in a static file before it’s sent to the browser. Based on our experience we have a few recommendations:

  • If you are serving images of other files that are not HTML, you might want to add a middleware to handle those files before you include this middleware.
  • In the example, they use serve-static to serve files but the middleware works fine with express.static, there is no need to add an extra dependency if you are already using express.
  • This technique is not recommended for large replacements. If that’s your case, we encourage you to set up pug, handlebars or something that you are familiar with.

We hope you find this package helpful. Please share in the comments below more use cases for this package, so that others can benefit from it.

. . .

Regos Dev Studio is a product development company that builds add-ons for Jira and Confluence, combined with the development of custom solutions in a variety of languages.

Don’t forget to check out our website, visit our Atlassian marketplace listing. You can also follow us on Twitter or LinkedIn and stay tuned for updates!

Leave a Reply

Your email address will not be published. Required fields are marked *