Next.js doesn't pick up variables from the .env file - next.js

I want to use a variable from the .env file, but I'm getting the following error:
Uncaught (in promise) IntegrationError: Please call Stripe() with your publishable key. You used an empty string.
code
import Stripe from "stripe";
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);
.env
NEXT_PUBLIC_STRIPE_SECRET_KEY=***

In Next.js you should declare your environment variables in a .env.localĀ file.
For more informations check the official docs.
However, as suggested by #juliomalves, you can declare your environment variables in a .env.* file, making sure that you respect the environment variables load order.

Related

process.env variables undefined in Nextjs

I'm reading undefined for my enviroment variable.When I console log process.env I can't seem to find the variable I defined In my .env file at the root directory.
.env.local file
privateKey="444455....."
scripts/hardhat.config.js
mumbai: {
url: 'https://polygon-mumbai.g.alchemy.com/v2/3333.....',
accounts: [process.env.privateKey]
},
Is it because I'm reading process.env outside of pages? I aslo tried prefixing like NEXT_PUBLIC_privateKey="0033....." and then reading it process.env.NEXT_PUBLIC_privateKey but value would only show inside pages folder and not in scripts/hardhat.config.js
Make sure you have installed and initialized the doting NPM package that is needed to use environment variables.
FINALLY WORKS
I ended up adding the dotenv AS SOMEONE SUGGESTED and starts reading.
Note to self
Enviroment variables outside next.js pages need that dotnev thing;

using .env.local with playwright

I'm setting up some first playwright tests for my nextjs project. I already have environment variables in my .env.local and I'd like to pull them into my test env.
I'm looking at the documentation and I see that I can add require("dotenv").config(); to my playwright.config.js but nothing is happening when I do that (the scripts are erroring out because of undefined.
I tried both calling process.env.foo directly within the script, and also adding a use: {foo: process.env.FOO} clause to the playwright.config.js and moving my variables to .env file instead of .env.local but nothing worked.
Help would be much appreciated! thank you.
After reading using dotenv path with JEST I found the solution is to configure the require statement:
install the dotenv package (the one that comes with next.js isn't loaded)
npm install --save-dev dotenv
In .env.local - set the vars
FOO=bar
In playwright.config.js - set which env file to use
require("dotenv").config({ path: "./.env.local" });
console.log(process.env.FOO); // prints "bar"
In a spec
test("env", async ({ page }) => {
console.log(process.env.FOO); // also prints "bar"
})

Firebase cloud function cannot read .env variables

I followed this doc and added .env file with variables in a Firebase Cloud Function project.
When trying to deploy, I get this message: Loaded environment variables from .env.
However, it is always undefined when I try to use process.env.ENV_VAR. Am I missing something?
I'm using firebase-cli 11.0.1 and firebase-functions 3.21.2
I used env variables for firebase credentials. Seems like it was loaded before env var. So my solution is to use firebase function config

Env vars are undefined in Nextjs v12.0.8

I created a .env.local file and tried to console process.env.TEST (test env var) but I'm getting undefined. It seems process.env is always empty.
I restarted the server but I still don't see the env vars. I even tried to start a new empty project and process.env is still empty.
Am I missing something? All the other posts I see seem to have figured it out but I still can't.
My .env.local file is on the root level. I also tried to append the var with NEXT_PUBLIC, but that didn't help.
By convention, React env variables must be prefixed with REACT_APP_ in order to be used with process.env. In the case of Next.js, you can put them in the .env.local, but they would only be available in the Node.js environment. If you need to make them available in the browser, you need to prefix them with NEXT_PUBLIC_.
Refer to the documentation for more details.
Another way (more old school Next.js) would be to have a next.config.js file.
A possible config would be:
const conf = {
env: {
myVar: process.env.MY_VAR,
},
};
module.exports = conf;
Then you could simply use process.env.myVar inside your code. See this page for more information.

Where to put secret keys in Netlify? [duplicate]

I'm trying to set an environment variable for an API key that I don't want in my code. My source javascript looks something like this :
.get(`http://api-url-and-parameters&api-key=${process.env.API_KEY}`)
I'm using webpack and the package dotenv-webpack https://www.npmjs.com/package/dotenv-webpack to set API_KEY in a gitignored .env file and it's all running fine on my local. I'd like to also be able to set that variable when deploying through Netlify, I've tried adding it through to GUI to the 'build environment variables', and also to set it directly in the build command, but without success.
Any idea what might be the issue ?
WARNING: If this is a secret key, you will not want to expose this environment variable value in any bundle that gets returned to the client. It should only be used by your build scripts to be used to create your content during build.
Issue
dotenv-webpack expects there to be a .env file to load in your variables during the webpack build of your bundle. When the repository is checked out by Netlify, the .env does not exist because for good reason it is in .gitignore.
Solution
Store your API_KEY in the Netlify build environment variables and build the .env using a script prior to running the build command.
scripts/create-env.js
const fs = require('fs')
fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}\n`)
Run the script as part of your build
node ./scripts/create-env.js && <your_existing_webpack_build_command>
Caveats & Recommendations
Do not use this method with a public facing repository [open] because any PR or branch deploy could create a simple script into your code to expose the API_KEY
The example script above is for simplicity so, make any script you use be able to error out with a code other than 0 so if the script fails the deploy will fail.
You can set Dotenv-webpack to load system environment variables as well as those you have declared in your .env file by doing the following:
plugins: [
new Dotenv({
systemvars: true
})
]
I.e Setting the systemvars attribute of your webpack dotenv plugin to true.
Note that system environment variables with the same name will overwrite those defined in your .env file.
Source: https://www.npmjs.com/package/dotenv-webpack#properties
if you go to corresponding site's settings in Netlify, under build&deploy you can find a section called environment variables you can easily add your environment variables from there. if you add MY_API_KEY variable to environment variables you will be able to access it inside your project via process.env.MY_API_KEY.
If you're using Nuxt JS there is a more "straight forward" approach.
Just edit the nuxt.config.js like so:
module.exports = {
env: {
GOOGLE_API_KEY: process.env.GOOGLE_API_KEY
},
// ...
Then add the GOOGLE_API_KEY to Netlify through the build environment variables as usual.
Credit goes to yann-linn and his answer on github.
What you can also do is also to define a global constant in Webpack. Netlify environment variables defined in UI will work with it. You don't need dotenv or dotenv-webpack.
webpack.config.js
const webpack = require("webpack");
module.exports = {
plugins: [
new webpack.DefinePlugin({
"process.env.API_KEY": JSON.stringify(process.env.API_KEY)
}),
]
}
However again, of course you shouldn't do it just inputting enviornmental variables in the frontend if your API key is confidential and project public. The API key will appear in the source code of the website and will be easily accessible for everyone visiting it. Lambda function would be a better option.
You can use the Netlify's config file also ...
You can find documentation here.
Also i wanted to have the same ENV variables with with different values per branch/environment.
This workaround worked for me:
Create a netlify.toml file like:
[build]
NUXT_ENV_BASE_API = "/api"
NUXT_ENV_HOST_DOMAIN = "https://your-domain.gr"
[context.branch-deploy]
environment = { NUXT_ENV_BASE_API = "/dev-api", NUXT_ENV_HOST_DOMAIN = "https://dev.your-domain.gr" }
[context.production]
environment = { NUXT_ENV_BASE_API = "/api", NUXT_ENV_HOST_DOMAIN = "https://your-domain.gr" }
And deploy in Netlify ...

Resources