Search code examples
javascriptdeploymentenvironment-variablesnext.jsnetlify

Getting environment variables to work in next js and netlify


I have deployed a next js application to netlify using git and I have a .env.local file that stores the backend route url that I use everywhere throughout the app when making fetch requests. The problem is that after deployment the process.env.NEXT_PUBLIC_BACKEND_ROUTE returns undefined.

The .env.local file:

NEXT_PUBLIC_BACKEND_ROUTE=https://[the name of the url].herokuapp.com/

An example of a page using the environment varible:

import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function Home() {
  const router = useRouter();
  useEffect(() => {
    axios
      .get(`${process.env.NEXT_PUBLIC_BACKEND_ROUTE}/findAllPictures`)
      .then((doc) => {
        const arr = doc.data;

        if (arr.length !== 0) {
          const mappedArr = arr.map((obj) => {
            return obj.id;
          });
          const amount = mappedArr.length;
          const rand = Math.floor(Math.random() * amount);
          const routeId = mappedArr[rand];
          router.push(`/view/${routeId}`);
        }
      });
  }, [null]);
  return <div></div>;
}


Solution

  • There are two possibilities I see

    1. your .env.local file is not in root

    2. Some weird formatting issue is going on with the variables. In that case, try surrounding your variable in quotes:

      NEXT_PUBLIC_BACKEND_ROUTE="https://[the name of the url].herokuapp.com/"