gridsome icon indicating copy to clipboard operation
gridsome copied to clipboard

Environment variables not working in main.js

Open kissu opened this issue 4 years ago • 5 comments

Description

For some reason, I cannot interpolate env variables in code alike

[...]
const accessToken = process.env.AUTH_TOKEN

export default function(Vue, { router, head, isClient }) {
  Vue.use(PrismicVue, {
    endpoint: process.env.PRISMIC_ENDPOINT,
    linkResolver,
    apiOptions: { accessToken },
  })
}

the AUTH_TOKEN and PRISMIC_ENDPOINT variables are just not taken into account. It does work everywhere else but not in this file.

Steps to reproduce

I pretty much ran a stock gridsome project out of the box, trying to get Prismic.io to work. Nothing too fancy, I may add a demo if really needed.

Expected result

As far as the docs are saying, I could use process.env.AUTH_TOKEN to get an interpolated variable everywhere (main.js file included).

Actual result

It returns undefined, even in some ${process.env.AUTH_TOKEN} way. Oh and my key is totally working too. :+1:

Great news tho, I found that solution to work actually ! I wished to know if it was an intended behavior (maybe add a line in the docs in that case) or if it is a bug.

Thanks ! :pray:

kissu avatar Nov 17 '19 00:11 kissu

You must prefix the variables with GRIDSOME_ to access them in the browser bundle (usually all files in the src folder). Read more about it in the Usage in the browser section :)

hjvedvik avatar Nov 17 '19 15:11 hjvedvik

I don't really want my Auth token variable to be accessible on the browser tbh. 😅

kissu avatar Nov 17 '19 15:11 kissu

@kissu I have the same issue with an env. var. that I don't want to make accessible on the browser. Did you solve this?

GonzaloHirschToptal avatar Oct 15 '21 11:10 GonzaloHirschToptal

@GonzaloHirschToptal You can try to wrap your code in if (process.isServer) { ... } to ensure it only runs on the server. Environment variables without the GRIDSOME_ prefix should be accessible during the build process.

hjvedvik avatar Oct 15 '21 11:10 hjvedvik

@GonzaloHirschToptal You can try to wrap your code in if (process.isServer) { ... } to ensure it only runs on the server. Environment variables without the GRIDSOME_ prefix should be accessible during the build process.

@hjvedvik it could work, but I need to access during build time a secret key used for encryption during client sessions. I need to encrypt part of my localStorage for security reasons.

GonzaloHirschToptal avatar Oct 15 '21 12:10 GonzaloHirschToptal