Search code examples
rubymiddlemancontentful

How do you use the Contentful Middleman preview API in different build environment?


Here's what I'm trying to achieve in principle, which obviously doesn't work since the contentful data needs to be retrieved before the build:

# Build command
bundle exec middleman contentful && bundle exec middleman build -e <ENV>
# config.rb

configure :prod do
  set :build_dir, 'build/prod'
  set :ENV, 'prod'

  activate :contentful do |f|
    f.space         = { hs: 'SPACE' }
    f.access_token  = 'TOKEN'
    f.cda_query     = { include: 2 }
    f.all_entries   = true
    f.content_types = { #... }
  end
end

configure :testSite do
  set :build_dir, 'build/test-site'
  set :ENV, 'test'

  activate :contentful do |f|
    use_preview_api = true
    #...
  end
end

Solution

  • You can use environment variables to switch on that.

    # Build command
    CONTENTFUL_ENV=<env> bundle exec middleman contentful && bundle exec middleman build -e <env>
    
    
    # config.rb
    access_token = nil
    use_preview = false
    case ENV['CONTENTFUL_ENV']
    when 'prod'
      access_token = ENV['CONTENTFUL_PROD_TOKEN']
    when 'testSite'
      access_token = ENV['CONTENTFUL_TEST_TOKEN']
      use_preview = true
    end
    
    activate :contentful do |f|
      f.space = {space_alias: ENV['CONTENTFUL_SPACE']}
      f.use_preview_api = use_preview
      f.access_token = access_token
      # ...
    end
    

    This way you can have multiple environments working together