Search code examples
javascriptreactjsenvironment-variablesnext.jscontentful

Environment variables not working (Next.JS 9.4.4)


So I'm using the Contentful API to get some content from my account and display it in my Next.Js app (I'm using Next 9.4.4). Very basic here. Now to protect my credentials, I'd like to use environment variables (I've never used it before and I'm new to all of this so I'm a little bit lost).

I'm using the following to create the Contentful Client in my index.js file :

const client = require('contentful').createClient({
    space: 'MYSPACEID',
    accessToken: 'MYACCESSTOKEN',
});

MYSPACEID and MYACCESSTOKEN are hardcoded, so I'd like to put them in a .env file to protect them and don't make them public when deploying on Vercel.

I've created a .env file and filled it like this :

CONTENTFUL_SPACE_ID=MYSPACEID
CONTENTFUL_ACCESS_TOKEN=MYACCESSTOKEN

Of course, MYACCESSTOKEN and MYSPACEID contains the right keys.

Then in my index.js file, i do the following :

const client = require('contentful').createClient({
  space: `${process.env.CONTENTFUL_SPACE_ID}`,
  accessToken: `${process.env.CONTENTFUL_ACCESS_TOKEN}`,
});

But it doesn't work when I use yarn dev, I get the following console error :

{
  sys: { type: 'Error', id: 'NotFound' },
  message: 'The resource could not be found.',
  requestId: 'c7340a45-a1ef-4171-93de-c606672b65c3'
}

Here is my Homepage and how I retrieve the content from Contentful and pass them as props to my components :

const client = require('contentful').createClient({
    space: 'MYSPACEID',
    accessToken: 'MYACCESSTOKEN',
});

function Home(props) {
  return (
    <div>
      <Head>
        <title>My Page</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main id="page-home">
        <Modal />
        <NavTwo />
        <Hero item={props.myEntries[0]} />
        <Footer />
      </main>
    </div>
  );
}

Home.getInitialProps = async () => {
  const myEntries = await client.getEntries({
    content_type: 'mycontenttype',
  });

  return {
    myEntries: myEntries.items
  };
};

export default Home;

Where do you think my error comes from?

Researching my issue, I've also tried to understand how api works in next.js as I've read it could be better to create API requests in pages/api/ but I don't understand how to get the content and then pass the response into my pages components as I did here.

Any help would be much appreciated!

EDIT:

So I've fixed this by adding my env variables to my next.config.js like so :

const withSass = require('@zeit/next-sass');

module.exports = withSass({
  webpack(config, options) {
    const rules = [
      {
        test: /\.scss$/,
        use: [{ loader: 'sass-loader' }],
      },
    ];

    return {
      ...config,
      module: { ...config.module, rules: [...config.module.rules, ...rules] },
    };
  },
  env: {
    CONTENTFUL_SPACE_ID: process.env.CONTENTFUL_SPACE_ID,
    CONTENTFUL_ACCESS_TOKEN: process.env.CONTENTFUL_ACCESS_TOKEN,
  },
});


Solution

  • Refer docs

    You need to add a next.config.js file in your project. Define env variables in that file and those will be available inside your app.