Access variables in NextJs - next.js

I want to use variables in NEXTjs application. For this i did:
created file: .env.local with:
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword
And i want to access this: console.log(process.env.DB_HOST, 'local variables') When i do this i get undefined. Why it happens, and how to get the variables?

If you want to access to your environment variables on client side and server side, they must be prefixed with NEXT_PUBLIC
NEXT_PUBLIC_DB_HOST=localhost
NEXT_PUBLIC_DB_USER=myuser
NEXT_PUBLIC_DB_PASS=mypassword
if you are going to use them only on the server side, then your example will work
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

If you are using nextjs higher than 9.4 you can use next.config.js
Snippet from nextjs documentation
https://nextjs.org/docs/api-reference/next.config.js/environment-variables
To add environment variables to the JavaScript bundle, open next.config.js and add the env config:
module.exports = {
env: {
customKey: 'my-value',
},
}

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;

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.

How to start react app on custom port with CRACO?

I want to use Tailwind CSS for my react apps. The problem is CRACO start starts the app on the default port, which is 3000 and I want to have custom ports but I can't figure out what is the right approach. ( Can't find anything about this in their documentation )
I tried something like PORT=5000 CRACO start inside the scripts field of the package.json file but doesn't work.
Any idea?
The accepted answer contains links to the relevant information, but in case they become invalid or you are too lazy to look at them here is the config you need to add to your craco.config.js file.
module.exports = {
devServer: {
port: 5000
}
}
Note that devServer is a top level property in the config.
CRACO use the webpack devserver configuration to set the port.
you need to create a configuration. read more here in the readme:
https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#configuration-file
So you solution need to redefine devServer. How to define it read in the webpack documentation:
https://webpack.js.org/configuration/dev-server/#devserver

Auth0 and Next.js deployed to Vercel: Location header error

I started with this sample repo: https://github.com/vercel/next.js/tree/canary/examples/auth0
My current repo: https://github.com/rebeccapeltz/next-auth-app-1
Login/Logout work fine locally. When I deploy to Vercel and logout I get this message in the browser:
Invalid character in header content ["Location"]
I've double checked the Auth0 env variables and they seem correct. Login works fine on Vercel. Can't figure out how to troubleshoot the header Location value that is causing the problem.
Nothing much going on yet and easy to reproduce: https://next-auth-app-1.now.sh/
Solved this by removing all env variables added to the Vercel online application settings. Then added the secrets using the now CLI now secrets add and deployed the app by setting up other env variables in now.json and using now --prod. Working OK now. For further external env secrets and references, I'm wondering if t's better to add them via now.json or to use the online settings GUI. One thing that wasn't clear is that when you add variables with now add secrets you need to prefix the value in the now.json with #. Kind of like accessing bash env variables with $. So after adding secrets my now.json looks like this
{
"build": {
"env": {
"AUTH0_DOMAIN": "<name of auth0 domain>",
"AUTH0_CLIENT_ID": "<what you get from auth0>",
"AUTH0_CLIENT_SECRET": "#auth0_client_secret",
"REDIRECT_URI": "<name of vercel app or domain name>/api/callback",
"POST_LOGOUT_REDIRECT_URI": "<name of vercel app>/",
"SESSION_COOKIE_SECRET": "#session_cookie_secret"
}
}
}
Should you add all env using secrets add and then just reference by name in the now.json? not sure.

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