Search code examples
javascriptreactjsenvironment-variablesgatsbydotenv

Using private key in a .env file


I have a multiline private key in a gatsby .env file:

GATSBY_GOOGLE_CLIENT_ID="12345"
GATSBY_GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nflkdflkdf...\n-----END PRIVATE KEY-----"

In my gatsby-config file I have:

module.exports = {
    resolve: 'gatsby-source-google-sheets',
    options: {
        credentials: {
            "type": "service_account",
            "private_key": process.env.GATSBY_GOOGLE_PRIVATE_KEY,
            "client_id": process.env.GATSBY_GOOGLE_CLIENT_ID
        }
    }
}

The client_id works fine because it's just a one line string but the private_key doesn't work, presumably because it's multi line.

Is there a way I can get around this?

Thanks


Solution

  • You could use string.replace with a regular expression as below to escape the \n characters again:

    "private_key": process.env.GATSBY_GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'),