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 :


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 (
        <title>My Page</title>
        <link rel="icon" href="/favicon.ico" />

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

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!


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 {
      module: { ...config.module, rules: [...config.module.rules, ...rules] },
  env: {

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:


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:

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

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


and in any part of your code you could use:


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

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.
  1. use them in any JS file like with prefix process.env
4 users liked answer #3dislike answer #34
confused_ profile pic

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

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

module.exports = nextConfig

change it like this

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

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:


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: {
0 users liked answer #6dislike answer #60
Yilmaz profile pic

Copyright © 2022 QueryThreads

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