Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting environment variables for client side #6533

Closed
karinchechik opened this issue Mar 5, 2019 · 7 comments
Closed

Setting environment variables for client side #6533

karinchechik opened this issue Mar 5, 2019 · 7 comments
Assignees

Comments

@karinchechik
Copy link

Bug report

Describe the bug

After deploying to Heroku:
At the index - First load returns the data I fetched in getInitialProps, but in a regular function I get an error message because the env vars are missing.

When I go to a different page I get the same error, but when I refresh I can see the data fetched at getInitialProps. But again, in a regular function I get an error for the missing env variables.

Locally it works. I tried dotenv-webpack but it doesn't help. I added the config vars in Heroku.

The code uses the environment variables on server side rendering (first load of index and in general, every page after refresh), so the problem is probably not the way I set the config vars. On a regular function (triggered by a button click), I get a message for the missing variables and also after I navigate to a different page.

This is my attemps in next.config.js:
First option that failed:

const { parsed: localEnv } = require('dotenv').config()
const webpack = require('webpack')
const Dotenv = require('dotenv-webpack')
const path = require('path')

module.exports = {
    //target: 'serverless',
    webpack(config) {
        config.plugins.push(new webpack.EnvironmentPlugin(localEnv))
        config.node = {fs: "empty"};
        config.plugins = config.plugins || []

        config.plugins = [
            ...config.plugins,

            // Read the .env file
            new Dotenv({
                path: path.join(__dirname, '.env'),
                systemvars: true
            })
        ]

        return config
    },
    publicRuntimeConfig: {
        ADDRESS: process.env.ADDRESS,
        API_TOKEN: process.env.API_TOKEN,
        INFURA_API_KEY: process.env.INFURA_API_KEY
    }
}

Second option that failed:

const { parsed: localEnv } = require('dotenv').config()
const webpack = require('webpack');

const path = require('path')

module.exports = {
    webpack(config) {
        config.plugins.push(new webpack.EnvironmentPlugin(localEnv))
        config.node = {fs: "empty"};
        config.plugins = config.plugins || []

        config.plugins = [
            ...config.plugins,
        ]

        return config
    },
    env: {
        ADDRESS: '0xd6F75293ec795',
        API_TOKEN: 'YUBKzlbA2eFmNbkzk',
        INFURA_API_KEY: '97eb10aac61799f9e865',
        MNEMONIC: 'my not so secret for testing password',
    }
}

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Added the config vars in Heroku.
  2. Deployed the project.
  3. Index only able to use the env vars thet are in the getInitialProps.
  4. Click on any link results in an error
  5. After refreshing, again only able to access the vars that are in getInitialProps.

You can see it here - https://furrytales.herokuapp.com/

Expected behavior

Local version is able to use environment variable on the client side from .env file.

Screenshots

You can see it here - https://furrytales.herokuapp.com/

System information

  • OS: Windows
  • Browser: chrome
  • Version of Next.js: 8.0.3

Some dependencies:
"webpack": "^4.29.6"
"next-routes": "^1.4.2",
"react": "^16.8.3",
"react-dom": "^16.8.3",
"dotenv": "^6.2.0"

Any idea how I can fix this? I've been tring for over a week :(

@ijjk
Copy link
Member

ijjk commented Mar 5, 2019

@karinchechik I'm not sure I follow, are the environment variables valid in your getInitialProps but not in a different function? Could you add a snippet from where the environment variables aren't being swapped or if possible a link to a repo with the code?

Note: the env Next config is used at build time so if you change a value there it won't take effect unless you re-build

@karinchechik
Copy link
Author

@ijjk
Sure. This is my repo - https://github.com/karinchechik/FurryTales-Basic-Done

It happens in every page, for example:
Please take a look at the new.js page.

In getInitialProps I have a fetch that uses process.env.API_TOKEN that displays the data as it should (but only after refreshing and not after a click from the index).
At the onSubmit function I use factory which I import from ethereum/factory.js.
In factory.js I use process.env.ADDRESS but always get an error that says the process.env.ADDRESS is missing.

@ijjk
Copy link
Member

ijjk commented Mar 5, 2019

@karinchechik Thanks for the repo! Are you trying to provide your data as environment variables or using a .env file? Looking at the repo it looks like your configs are colliding.

If you're just using environment variables and not a .env file you don't need the webpack and dotenv-webpack dependencies and you can just use the env config in next.config.js.

During build Next.js will use the env config and replace any instances of process.env.VAR_NAME with the value defined in next.config.js.

If you need these values to be able to change without rebuilding and you aren't using serverless mode you can use the publicRuntimeConfig like you had, although next/config is a function so instead of getConfig you would do getConfig().

I can submit a PR with an updated config if this doesn't help.

@karinchechik
Copy link
Author

Thank you so much!!

I tried the webpack option (which didn't work) before the env in next.config.js option and I didn't remove the dotenv-webpack.

Now I used the env in next.config.js without the webpack and dotenv-webpack and it finally works as expected!

Thanks again :)

@goranefbl
Copy link

https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration publicRuntimeConfig can be used for this, as per https://whitefield.dev/blog/nextjs-env-variables

@fransoudelaar
Copy link

The made it really easy to expose environment variables to the browser:

In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_.

See: https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants