---
title: Set environment variable reactjs and nextjs
tags: Web Dev
---
# Set environment variable reactjs and nextjs
## Reactjs
> /.env
REACT_APP_.. should start in REACT_APP_ for enviroment variable
using in anywhere
process.env.REACT_APP_
## Nextjs
https://nextjs.org/docs/basic-features/environment-variables
> /.env
NEXT_PUBLIC_.. should start in NEXT_PUBLIC for enviroment variable
:::danger
/.env.local
Don't need to start with `NEXT_PUBLIC_..`
:::
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
using in anywhere
process.env.NEXT_PUBLIC_
## Non-create-react-app
### client
- Using dotenv in client with server (setting webpack.config.js)
https://trekinbami.medium.com/using-environment-variables-in-react-6b0a99d83cf5
- (on bottom this page)
https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project
- my example (setting https://github.com/jherr/wp5-starter-react template)
> client/webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const deps = require("./package.json").dependencies;
//setting for .env
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports =()=> {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return{
output: {
publicPath: "http://localhost:8080/",
},
resolve: {
extensions: [".jsx", ".js", ".json"],
},
devServer: {
port: 8080,
},
module: {
rules: [
{
test: /\.m?js/,
type: "javascript/auto",
resolve: {
fullySpecified: false,
},
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
//custom setting (for font .ttf load)
{
test: /\.(woff2?|eot|ttf|otf)$/,
use: {
loader: "url-loader",
options: {
name: "[name].[ext]?[hash]",
},
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "starter",
filename: "remoteEntry.js",
remotes: {},
exposes: {},
shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
},
}),
new HtmlWebPackPlugin({
template: "./src/index.html",
}),
new webpack.DefinePlugin(envKeys)
],
}
};
### server
- dotenv
https://github.com/motdotla/dotenv