I built a static website using gatsbyJS and prismic.io as a headless CMS. Does anybody know how to use different configs when building the website (gatsby build) ( for example : gatsby config 1 / gatsby config 2). The end goal is to use Jenkins to auto build different sites with the same code base but different css/config.
1 Answers
Well, it's not exactly using "different gatsby-config.js
" files but the most similar approach is using environment variables. This will allow you to use the same gatsby-config.js
with different setups.
Gatsby by default uses development
and production
as environments when running gatsby develop
and gatsby build
respectively (you can override this behavior as desired using your custom environments). In that way, you need to tell Gatsby where are those variables set. This is done by the following snippet (in gatsby-config.js
):
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
If you create a .env.development
and .env.production
at the root of your project, you can simply do:
GATSBY_API_URL=https://example.com/api
API_KEY=927349872349798
Now, in any configuration parameter, you can use the environment variables stored in those files like:
module.exports = {
plugins: [
{
resolve: `gatsby-source-patronus`,
options: {
apiKey: process.env.API_KEY,
},
},
],
}
Extending this behavior, you can customize the running commands to use different environment files like .env.siteOne
and .env.siteTwo
simply changing and creating your own scripts in your package.json
and using the GATSBY_ACTIVE_ENV
variable:
"scripts": {
"build-site-one": "GATSBY_ACTIVE_ENV=siteOne gatsby build",
"build-site-two": "GATSBY_ACTIVE_ENV=siteTwo gatsby build",
},
Just running:
npm run build-site-one
You will be taking the environment variables stored in the .env.siteOne
file so you can point to a different CMS configuration, different theming, different routes, and paths, etc.
Disclaimer: the whole process aims to use server-side variables to change some configuration/parameters. To use the client-side (JavaScript) variables you can omit the require("dotenv").config({ path: `.env.${process.env.NODE_ENV}`})
part.

- 28,630
- 6
- 39
- 67