I am using NextJs to build out an application. I have two different URL's for production and development and I want to access the corresponding URL to the environment for the client. I followed this guide but my PROCESS.ENV.API_URL on development is empty.
Here are my files:
.env:
API_URL=https://my-staging-url.com
.env.production:
API_URL=https://my-production-url.com
.babelrc:
{
"presets": [
"next/babel"
],
"env": {
"development": {
"plugins": ["inline-dotenv"]
},
"production": {
"plugins": ["transform-inline-environment-variables"]
}
}
}
Environment variable usage:
import 'isomorphic-fetch';
export const SET_QUERY = 'SET_QUERY';
export const CLEAR_SEARCH = 'CLEAR_SEARCH';
export const START_FETCHING_SEARCH = 'START_FETCHING_SEARCH';
export const SET_SEARCH_RESULTS = 'SET_SEARCH_RESULTS';
export const FETCHING_SEARCH_FAILED = 'FETCHING_SEARCH_FAILED';
export const getSearch = value => {
const url = `${process.env.API_URL}search?q=${value}`; // THIS IS EMPTY
console.log(url);
return fetch(url);
};
// Implement search action
export const doSearch = query => dispatch => {
dispatch({ type: START_FETCHING_SEARCH });
return dispatch => {
return getSearch(query).then(response => {
dispatch({ type: SET_SEARCH_RESULTS });
}, () => {
dispatch({ type: FETCHING_SEARCH_FAILED });
});
};
};
export const clearSearch = () => dispatch => {
return dispatch({ type: CLEAR_SEARCH })
};
Hope that helps, Cheers!
you must've forgot to install plugin
simply you can paste this in your package json file:
"dependencies": {
"next": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"babel-plugin-inline-dotenv": "^1.1.1",
"babel-plugin-transform-inline-environment-variables": "^0.1.1"
}
and run
npm install
or you can run
npm install babel-plugin-inline-dotenv babel-plugin-transform-inline-environment-variables --save -dev
OR You can simply achieve this feature differently as per this guide with-universal-configuration
.bablerc
{
"plugins":[
["transform-define", "./env-config.js"]
]
}
.env-config.js
const prod = 'production' === process.env.NODE_ENV
module.exports = {
'process.env.API_URL': prod ? 'http://api.dev.com' : 'http://api.local.com/',
}
and in package json you should ve to install babel-plugin-transform-define
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With