56

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,
  },
});

1
  • I can get .env.local variables in getServerSideProps() using process.env.VARIABLE_NAME but unable to get them when I submit the form on client side Oct 22, 2021 at 6:16

11 Answers 11

97

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
7
24

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

1
  • 1
    Restart the server after the change.
    – Valladão
    Apr 11, 2023 at 0:37
19

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

3
  • 2
    Is this required to use NEXT_PUBLIC Oct 22, 2021 at 6:11
  • 6
    Note that this approach does not protect your secrets - they're visible for anyone in frontend package. To protect your secrets you must create a backend function as Nikolai Kiselev already suggested in his response. .env files can be used to store secrets but then never prefix them with "NEXT_PUBLIC_" as that makes them visible also to frontend. Without "NEXT_PUBLIC_" prefix the variable will be available only in next.js backend which is what you'd want to.
    – ronkot
    Jan 25, 2022 at 12:58
  • Restart the server after the change.
    – Valladão
    Apr 11, 2023 at 0:36
9

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

1
  • Restart the server after the change.
    – Valladão
    Apr 11, 2023 at 0:35
7

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,
  },
}
1
  • 1
    Restart the server after the change.
    – Valladão
    Apr 11, 2023 at 0:36
5

Not related to 9.4.4 but faced the same problem of env not loading properly.

Checklist:

  • .env.local file naming
  • make sure .env.local is in the root folder. Mine was in src/.env.local (This was my problem).
  • Prefix NEXT_PUBLIC_ for client side environments variables.
  • Reload the environment (Hot reloading does not pick up .env file changes)

Also, Refer to Official Docs: https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables

0
2

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.

7
  • Ok so i know what my error was.. I've added it to my next.config.js but i did it wrong.. now it works, i'll edit my post. Thanks!
    – Perdixo
    Jun 15, 2020 at 11:00
  • 1
    There is way to directly read .env file in node and browser environment. I didn't get a chance to try that. It was not supported in earlier versions.
    – Achal Jain
    Jun 15, 2020 at 11:09
  • 3
    @Perdixo, this is incorrect answer because the suggested way exposes credentials. It can be used only for variables that can be openly published. Jun 15, 2020 at 12:04
  • I have the same issue that @Perdixo, the problem to me continue being the same, if I add the env to next.config.js I solve the problem, because I really dont know why if I create a .env of any type, the result is always undefined, I'm using next v10, and I want to be sure that my credential are no exposed
    – Raul
    Dec 28, 2020 at 14:01
  • This solution is for old versions. The author of the problem should accept @NikolaiKiselev answer. Jan 17, 2021 at 19:42
2

For me, the solution was simply restarting the local server :)

Gave me a headache and then fixed it on accident.

It did not occur to me that env variables are loaded when the server is starting.

1
  npm i --save [email protected] // 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

You have to define your secrets in .env.local and then do this in your next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  env: {
    VARIABLE_IN_ENV: process.env.VARIABLE_IN_ENV
  }
};

module.exports = nextConfig;

This will work.

0

You need to define your env variables into next.config.mjs file.

Suppose you have defined a variable name API_PATH in .env file. Next you have to defined process.env.API_PATH into your next.config.mjs file under env object.

enter image description here enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.