Source:  Twitter logo

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 losted).

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 an .env file to protect it and don't make it 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 about 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 like 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,
  },
});

You can't make this kind of request from the client-side without exposing your API credentials. You have to have a backend.

You can use Next.js /pages/api to make a request to Contentful and then pass it to your front-end.

Just create a .env file, add variables and reference it in your API route as following:

process.env.CONTENTFUL_SPACE_ID

Since Next.js 9.4 you don't need next.config.js for that.


By adding the variables to next.config.js you've exposed the secrets to client-side. Anyone can see these secrets.

New Environment Variables Support

Create a Next.js App with Contentful and Deploy It with Vercel

Blog example using Next.js and Contentful

16 users liked answer #0dislike answer #016
Nikolai Kiselev profile pic
Nikolai Kiselev

Don't put sensitive things in next.config.js however in my case I have some env variables that aren't sensitive at all and I need them Server Side as well as Client side and then you can do:

// .env file:
VARIABLE_X=XYZ

// next.config.js
module.exports = {
  env: {
    VARIABLE_X: process.env.VARIABLE_X,
  },
}
7 users liked answer #1dislike answer #17
OZZIE profile pic
OZZIE

I recomended to update at nextjs 9.4 and up, use this example:

.env.local
NEXT_PUBLIC_SECRET_KEY=i7z7GeS38r10orTRr1i

and in any part of your code you could use:

.js
const SECRET_KEY = process.env.NEXT_PUBLIC_SECRET_KEY

note that it must be the same name of the key "NEXT_PUBLIC_ SECRET_KEY" and not only "SECRET_KEY"

and when you run it make sure that in the log says

$ next dev
Loaded env from E:\awesome-project\client\.env.local
ready - started server on http://localhost:3000
...

To read more about environment variables see this link

7 users liked answer #2dislike answer #27
D4ITON profile pic
D4ITON

if you are using latest version of nextJs ( above 9 )

then follow these steps :

  1. Create a .env.local file in the root of the project.
  1. Add the prefix NEXT_PUBLIC_ to all of your environment variables.
eg: NEXT_PUBLIC_SOMETHING=12345
  1. use them in any JS file like with prefix process.env
eg: process.env.NEXT_PUBLIC_SOMETHING
4 users liked answer #3dislike answer #34
confused_ profile pic
confused_

You have to make a simple change in next.config.js

const nextConfig = {
  reactStrictMode: true,
  env:{
    MYACCESSTOKEN : process.env.MYACCESSTOKEN,
    MYSPACEID: process.env.MYSPACEID,
  }
}

module.exports = nextConfig

change it like this

4 users liked answer #4dislike answer #44
AJO ALEX profile pic
AJO ALEX

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.

1 users liked answer #5dislike answer #51
Achal Jain profile pic
Achal Jain
  npm i --save dotenv-webpack@2.0.0 // version 3.0.0 has a bug

create .env.development.local file in the root. and add your environment variables here:

 AUTH0_COOKIE_SECRET=eirhg32urrroeroro9344u9832789327432894@@@
 NODE_ENV=development
 AUTH0_NAMESPACE=https:ilmrerino.auth0.com 

create next.config.js in the root of your app.

const Dotenv = require("dotenv-webpack");
module.exports = {
  webpack: (config) => {
    config.resolve.alias["@"] = path.resolve(__dirname);
    config.plugins.push(new Dotenv({ silent: true }));
    return config;
  },
};

However those env variables are gonna be accessed by the server. if you want to use any of the env variables you have to add one more configuration.

 module.exports = {
  webpack: (config) => {
    config.resolve.alias["@"] = path.resolve(__dirname);
    config.plugins.push(new Dotenv({ silent: true }));
    return config;
  },
 env: {
   AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
  },
};
0 users liked answer #6dislike answer #60
Yilmaz profile pic
Yilmaz

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).