Use dotenv (.env-files) in the build process

Hi. We are build a web app with Contentful + Gatsby. To enable Gatsby to get content from Contentful we need to add a spaceId and accessToken. I 've created an .env-file for this to use during development, but for obvious reasons I do not want to commit this file, so I need to add the variables in another way (I also use the dotenv-package for the .env integration). So I've created Environment Variables in Teamcity for this and everything seems fine - I am able to add a NodeJs build step and run:

console.log(`Your accessToken is ${process.env.CONTENTFUL_ACCESS_TOKEN}`);

and the correct token is printed. But for some reason my code that runs during npm run build doesn't get the token:

contentfulConfig = {
   spaceId: process.env.CONTENTFUL_SPACE_ID || contentfulConfig.spaceId,
   accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || contentfulConfig.accessToken

I get:

TypeError: Cannot read property 'accessToken' of undefined

Does anyone have an idea what might be wrong? Thanks in advance!

Erik Lidälv

1 comment

Hi Erik,


I'm not particularly familiar with npm or "dotenv". Are you using the npm plugin or are you running a command line runner running the npm commands? If you are using the runner, please try with the command line. I'd recommend following the steps here:


I'm not familiar with the "proces.env...." syntax, I assume it comes from dotenv, but TeamCity offers the possibility of using "%env.CONTENTFUL_ACCESS_TOKEN%" instead that should be resolved when passing the build to the agent. That might be an option.


Please sign in to leave a comment.