-1

If I have HTML code within a document in a MongoDB database collection, which includes ${process.env.MY_VARIABLE}:

{
    "page_name": "home_page",
    "page_content": "<div id='some_id'>Here is an environment variable:  ${process.env.MY_VARIABLE}</div>"
}

How can I 'evaluate' the environment variable within the string before returning the string from the backend to the frontend?

I have tried this (simplified for brevity):

import * as dotenv from 'dotenv';
dotenv.config(); 
import { mongodb_connection } from '../../config/mongodb_connection.js';

let page_html; 
let dynamic_page_name = "home_page"; 

mongodb_connection.connect(async err => {
        const collection = mongodb_connection.db('pages').collection('pages');
        const result = await collection.findOne({ "page_name": dynamic_page_name }); 

        // trying to 'force' this to be a string so that the env var is 'evaluated'  
        page_html = `${result.page_content}`; 

        res.render('index', { page_html: page_html });

        mongodb_connection.close();
});

But it, kind of predictably, returns the string 'as is':

Here is an environment variable: ${process.env.MY_VARIABLE}

In other words, this:

${process.env.MY_VARIABLE}

has not been converted to the environment variable it is referencing.

How can I 'evaluate' process.env values which are referenced in string values returned from a database request?

For reference:

The following does work (if the string is defined explicitly and not the result of a MongoDB request):

import * as dotenv from 'dotenv';
dotenv.config(); 

let page_html = `<div id='some_id'>Here is an environment variable:  ${process.env.MY_VARIABLE}</div>`; 

res.render('index', { page_html: page_html });
user1063287
  • 10,265
  • 25
  • 122
  • 218

1 Answers1

1

Evaluating arbitrary expressions that come from a database is dangerous, because they may contain expressions that execute malicious actions. But if you restrict yourself to process.env variables, you can achieve it with a string replacement operation like this:

function varsubst(s) {
  return s.replace(/\$\{process\.env\.(.*?)\}/g, function(m, p) {
    return process.env[p];
  });
}
page_html = varsubst(result.page_content);
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31