Sharif Ahmed
Sharif Ahmed

Reputation: 160

React .env.environment file's variable not working

I connected my react app with Contentful's database. When I give the access key directly, it works fine. But when I give an access key in .env.environment file, the variable does not work.

contentful.js file:

import {createClient} from 'contentful';

export default createClient({
  space: process.env.REACT_APP_API_SPACE,
  accessToken: process.env.REACT_APP_ACCESS_TOKEN
});

.env.enviroment file:

 REACT_APP_API_SPACE= my access key
 REACT_APP_ACCESS_TOKEN= my access token

Console error:

Uncaught TypeError: Expected parameter accessToken
at createClient (contentful.node.js:7563)
at Object.<anonymous> (Contentful.js:3)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)
at Object.<anonymous> (context.js:5)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)
at Object.<anonymous> (FeaturedRooms.js:2)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)

But it works fine when I give the access key directly in my contentful.js file like this:

import {createClient} from 'contentful';

export default createClient({
  space: my access key,
  accessToken: my access token
});

As I am uploading to Git, I don't want to give the key directly.

Upvotes: 1

Views: 1106

Answers (1)

ezio4df
ezio4df

Reputation: 4195

#if using create-react-app

I don't think you can name your .env file like that, as of create-react-app.dev

  • .env: Default.
  • .env.local: Local overrides. This file is loaded for all environments except test.
  • .env.development, .env.test, .env.production: Environment-specific settings.
  • .env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

So, your .env.environment env file by default shouldn't work. Unless you modified somehow.

Restarting your Server

If so, Dont forget to restart your server as this note,

Note: You need to restart the development server after changing .env files.

Upvotes: 2

Related Questions