Search code examples
gatsbynetlifycontentful

How to create Client-side environment variables in netlify


I use netlify to deploy a gatsby app from a git repos, and I use contentful as my CMS. In order to use content delivery api, I have defined accessToken and space id at client-side, now it works fine. But the accessToken is plain text so it’s a security issue to expose the accessToken. I know netlify can create enviroment variables, but it seems the variables only works at Server-side. I have created a variable named CONENTFUL_ACCESS_TOKEN, I can access it use process.env.CONENTFUL_ACCESS_TOKEN at gatsby-config.js, gatesby-node.js and so on, but I can't access it at client-side, so How to do? this is my client.js, it runs at client-side.

const client=contentful.createClient({
  space:'your spaceid',
  accessToken:'your access token',
})

how to change to: const client=contentful.createClient({ space:'your space id', accessToken:NETLIFY_ENVIROMENT_VARIABLE_NAME, })


Solution

  • With Netlify, you need to prefix with GATSBY_ all your environment variables. As it is shown in Gatsby documentation.

    In addition to these Project Environment Variables defined in .env.* files, you could also define OS Env Vars. OS Env Vars which are prefixed with GATSBY_ will become available in browser JavaScript.

    So you CONENTFUL_ACCESS_TOKEN and other variables will become GATSBY_CONENTFUL_ACCESS_TOKEN (and so on). Once they are set locally (to keep cohesion and avoid duplicity), you must change them in your Netlify application (under https://app.netlify.com/sites/YOURSTIE/settings/deploys#environment):

    enter image description here

    The same procedure for the spaceId.

    To use this variables, you need to simply add them in you gatsby-config.js:

    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: process.env.GATSBY_CONTENTFUL_SPACEID,
        accessToken: process.env.GATSBY_CONTENTFUL_ACCESS_TOKEN,
        host: `preview.contentful.com`,
      },
    },
    

    And:

    const client=contentful.createClient({
      space:process.env.GATSBY_CONTENTFUL_SPACEID,
      accessToken: process.env.GATSBY_CONTENTFUL_ACCESS_TOKEN,
    })
    

    Reference: https://www.gatsbyjs.org/packages/gatsby-source-contentful/