With the new outputStandalone experimental feature (https://nextjs.org/docs/advanced-features/output-file-tracing#automatically-copying-traced-files-experimental) we can, after the build, have a standalone folder that contains the necessary dependencies, we simply copy it into our docker and don't need to rebuild inside the docker. It automatically detects the necessary dependencies in the source code UNLESS that dependency is only used in our package.json.
We use cross-env to start our Next app and of course this library is never imported in our source code, yet it needs to be present in the node_modules of the standalone folder.
So how can I force #vercel/nft to include a specific dependency ?
My case was that our dockerized Next.js project used Knex.js, where migrations were invoked with a npm script. Following this, some dependencies only required for knex.migrations() were never included in the standalone output.
Credits to sbstn, you can use unstable_includeFiles to create a list of dependencies, which should be included in the standalone output. This solution scans for .js and .json in a node_modules/ directory.
It should be highlighted that this setting is not available inside next.config.js, but as a page config prop, meaning it has to be exported inside a export const config = {} from a page different from _app.jsx and /api routes.
// pages/index.jsx
export default function Home(){
...
}
const requiredStandaloneDependencies = [
// some required deps that have not been included in standalone
"commander",
"debug",
"escalade",
"get-package-type",
"getopts",
"interpret",
"lodash",
"pg-connection-string",
"rechoir",
"resolve-from",
"tarn",
"tildify",
];
export const config = {
unstable_includeFiles: requiredStandaloneDependencies.map(
(dep) => `node_modules/${dep}/**/*.+(js|json)`
),
};
As a final thought for my case, where migrations are invoked with a custom npm script, npm run migrate:latest, I should also be able to circumvent the issue using programmatically invoked migrations. I'm just unsure as to how I add the method to the Next.js project tree to be run during runtime initialization.
I’m using react-app-rewired and I want to disable the overlay for Typescript warnings that appears every time I compile. For reasons I don't understand, warnings that the VSCode Typescript checker doesn't pick up appear on the overlay; webpack is being a stricter enforcer (stricter than I want it to be in fact).
Anyway, I tried react-app-rewired start --no-client-overlay and I tried this for my config-overrides.js file:
module.exports = {
webpack: function (config, _) {
config.devServer = {
client: {
overlay: false
}
}
return config
}
}
Neither has any effect. It would be good to know how to disable the overlay but an equally good solution would be how to have the compiler use the same level of strictness that VSCode does.
create-react-app generates a separate Webpack configuration for use with the dev server, so you need to use the devServer function, like so:
module.exports = {
devServer: function (configFunction) {
return function (proxy, allowedHost) {
// Create the default config by calling configFunction with the proxy/allowedHost parameters
const config = configFunction(proxy, allowedHost);
config.client = {
overlay: false,
};
return config;
};
},
};
From the react-app-rewired docs:
Webpack Dev Server
When running in development mode, create-react-app does not use the
usual Webpack config for the Development Server (the one that serves
the app pages). This means that you cannot use the normal webpack
section of the config-overrides.js server to make changes to the
Development Server settings as those changes won't be applied.
Instead of this, create-react-app expects to be able to call a
function to generate the webpack dev server when needed. This function
is provided with parameters for the proxy and allowedHost settings to
be used in the webpack dev server (create-react-app retrieves the
values for those parameters from your package.json file).
React-app-rewired provides the ability to override this function
through use of the devServer field in the module.exports object in
config-overrides.js. It provides the devServer function a single
parameter containing the default create-react-app function that is
normally used to generate the dev server config (it cannot provide a
generated version of the configuration because react-scripts is
calling the generation function directly). React-app-rewired needs to
receive as a return value a replacement function for create-react-app
to then use to generate the Development Server configuration (i.e. the
return value should be a new function that takes the two parameters
for proxy and allowedHost and itself returns a Webpack Development
Server configuration). The original react-scripts function is passed
into the config-overrides.js devServer function so that you are able
to easily call this yourself to generate your initial devServer
configuration based on what the defaults used by create-react-app are.
If you are using Webpack v4 (CRA v4), this should be the documentation you are looking for https://v4.webpack.js.org/configuration/dev-server/#devserveroverlay
module.exports = {
webpack: function (config, _) {
config.devServer = {
overlay: {
warnings: true,
errors: true
}
}
return config
}
}
The config you provided above is for Webpack v5 (CRA v5), so make sure you are using CRA v5 (and also check that react-app-rewired supports that version).
I'm running a node project + reactjs on it. the process.env works inside the server.js but undefined in other js file.
I tried to build the project using webpack and then run the nodejs project like
here are the steps I did.
yarn build
CALLBACK_URL=https://localhost:9999/ BASE_URL=https://localhost:9443/ node server.js
I'm getting the log in server.js
process.env.BASE_URL https://localhost:9443/
process.env.CALLBACK_URL https://localhost:9999/
but I'm getting process.env.BASE_URL : undefined in other js file.
Server.js is in the back end and is in scope of your "process" object.
React runs in the client browser engine. You need to get the environment variables From the "process" object available in your back-end's webpack build context into the webpack React Built files!
See
dotenv-webpack plugin
webpack-define plugin
for a possible elegant solution
in webpack.config you can add these lines in plugins section:
new webpack.DefinePlugin({
'process.env.CALLBACK_URL': 'https://localhost:9999/',
'process.env.BASE_URL': 'https://localhost:9443/'
})
I have finished building a simple resume/portfolio website using GatsbyJS in development.
I am using three environment variables (env var) to store my social media links (email/mobile/linkedin), as I will be displaying them in my React frontend.
I am storing all my env var(s) inside .env.development file in the root.
I am using the env-cmd package for accessing the env var(s).
In my package.json file, I modified the develop script to the following:
"develop": "env-cmd -f .env.development gatsby develop",
^ With that, I am able to access the environmental variables in my front end.
e.g.
<div>{process.env.EMAIL}</div>
I am using Netlify for deployment, and I tried putting env vars within Netlify after building it, but it didn't work.
So I think the problem is stems from the env vars being only accessible during development, so my question is, how do I make sure they are accessible after deploying the website (in production)?
Thank you!
Your variables are available on build/compile. In order to use them on the client you should create a .env.production (I was using dotenv) when building, you can place it for instance on top of gatsby-config.js
Example:
const fs = require('fs')
const VARS = [
'TEST'
]
function createProdEnv () {
var content = ''
VARS.map(varName => {
content += varName + '=' + process.env[varName] + '\n'
})
fs.writeFileSync('./.env.production', content)
}
module.exports = createProdEnv
And call it from gatsby-config.js
createProdEnv()
So after reading the docs again: https://www.gatsbyjs.org/docs/environment-variables/
I simply prefixed all my env var with GATSBY_ in my .env file, just like REACT_ in create-react-app. I didn't use .env.development nor .env.production files, simply just a .env file.
Then in Netlify I input the same env var, and it worked!
I am not sure if this is the optimal solution, so if there is a better way to do this, please share!
I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from '../src/components/Home'
import dotenv from 'dotenv'
import path from 'path'
class App extends Component {
render() {
console.log(process.env.API_URL)
return (
<div>
<Home/>
</div>
);
}
}
export default App;
Three things to note here
the variable should be prefixed with REACT_APP_
eg: REACT_APP_WEBSITE_NAME=hello
You need to restart the server to reflect the changes.
Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE
Additional tips
No need to wrap your variable value in single or double quotes.
Do not put semicolon ; or comma , at the end of each line.
Read more here(my own post) and the official docs
You will probably need to call dotenv.config() as suggested by the document
If you are using create-react-app, you don't need dotenv package. You will need to add REACT_APP_ prefix to the variable name in .env file. See the document here
when calling a .env variable from a JS file
you need to call it by process.env. prefix before you write the .env variable
thus it would look like process.env.REACT_APP_NOT_SECRET_CODE
and do not forget to start your variable name by REACT_APP_ prefix as mentioned in previous answers, otherwise react will ignore it for security reasons.
Add prefix REACT_APP_ on React environment variables.
apiKey: process.env.REACT_APP_API_KEY
Make sure .env file is in the root directory.
src/
.env
.gitignore
package.json
package-lock.json
Restart the development server after making changes in .env file.
Copy only the value inside the quotation marks and don't forget to remove trailing commas(It haunted me for several hours). These examples will give you an error.
REACT_APP_API_KEY=Ach2o1invVocSn25FcQhash209,
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209",
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209"
Make sure you used the prefix REACT_APP on every variable
Confirm that the variable names on the .env file match the ones on
your js file.For example,REACT_APP_KEY in .env versus
process.env.REACT_APP_KY
If the development server was running, stop it then rerun using npm
start it. I really struggled with this (variable is an undefined error).
Every time you update the .env file, you need to stop the server and
rerun it, as the environment variables are only updated during build
(variable is an undefined error).
Remove quotations from the values of the variables.
// Wrong:
REACT_APP_KEY=”AHEHEHR”
// Right:
REACT_APP_KEY=AHEHEHR
restart the vscode (close the project, close the editor)
open it again
launch the project
In my case it help a lot. Also remember to start the name of your key with REACT_APP_YOUR_NAME_KEY
If the above solutions don't work for you then please check where is your ".env" file place.
Like in my case everything I had done correctly but the mistake is I had placed the ".env" outside my project directory due to which I'm getting error.
Note: Your ".env" file should be in the same directory in which your "package.json" is.
Hey thanks guy what i did and worked was create a config.js file
const dev={
API_URL:"http://localhost:300"
}
const prod={
API_URL:"llll"
}
const config=process.env.NODE_ENV=='development'?dev:prod
export default config
Then i import wherever maybe in a component and get my data.
Another possible trap in which I fell was to define the variables not under the create-react-app folder but one above(where the Node server/backend .env is located). Make sure you don't do that because you will waste precious time, as I did today.
Solution:
1.Remove double quotation.("...").
2.Prefix Must be REACT_APP on every variable.
Right way:
REACT_APP_API_URL=http://localhost:8002
I hope its work.
In my case I started with naming the file process.env. As it happen and as the doc clearly states, the file should simply be named .env
try by clearing the cache also.
npx react-native start --reset-cache
FIX:
in babel.config.js, if you're using the optional configuration:
{
"plugins": [
["module:react-native-dotenv", {
"moduleName": "#env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}]
]
}
you should then import:
import {API_URL, API_TOKEN} from "#env"
instead of:
import {API_URL, API_TOKEN} from "react-native-dotenv"
the NPM Package description itself has this inconsistency
DO NOT STORE OR USE API KEYS IN FRONTEND CODE SINCE IT IS EASILY READABLE THROUGH DEV TOOLS
Saving API keys in .env and using them in your React app will still be unsecured since the API key can be read from DevTools.
Use some simple backend code that will act as a proxy to your service.
Send required data through a request and then the backend should use that data including the API key stored on the backend, and then make a request to some particular service that needs that API key.
No need to prefix it with REACT_APP_, just identify your environment -
if you are on development environment (npm start), you should be adding an environment variable in .env.development like - API_URL=http://example.com
if you are on production environment, updating .env should work
Then use the same in your JS file as process.env.API_URL
Note: I've tested this on React JS v16.8
If you are using dev server on localhost know this that .env doesn't work here, you need to deploy website on "normal" server, it is a safety reason to not allow browser to see .env in staging
I investigated a couple of options on how to set environment-specific variables and ended up with this:
You can directly use the dotenv-webpack(npm install dotenv-webpack --save) available in webpack to have access to any environment variable.
You just have to declare the plugin in your webpack.config.js file:
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
/*...*/
plugins: [
new Dotenv()
]
}
Just create the .env file in your root directory and set the variables there,
REACT_APP_API_URL=https://localhost:8080/api
REACT_APP_LOG_PATH=/usr/share/
Then you call it in your js file in the following way:
process.env.REACT_APP_API_URL
process.env.REACT_APP_LOG_PATH
I just found that I used different names for the variables :)
Also make sure that when you enter process.env.REACT_APP_YOURVARIABLE, your IDE don't add at the top of your file:
import process from "process";
This was my problem, I received undefined until I removed the accidentally added import