1

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.

4
  • 3
    It should be named .env not .env.environment Commented Aug 8, 2020 at 9:03
  • 1
    Try restarting npm run start command. Commented Aug 8, 2020 at 9:04
  • You need to restart your React app every time you make some changes to environment file. Rerun npm. Commented Aug 8, 2020 at 10:57
  • is it a create-react-app project ?? Commented Aug 8, 2020 at 11:23

1 Answer 1

2

#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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.